OpenAPI Schema Pydantic
openapi-schema-pydantic provides Pydantic classes that represent the OpenAPI (v3) specification schema. It allows developers to construct OpenAPI documents using native Python objects with type hints and validation. The library's latest version is 1.2.4. Note: This library is no longer actively maintained, and `openapi-pydantic` is a community-maintained fork.
Warnings
- breaking The `openapi-schema-pydantic` library is no longer actively maintained. A community-maintained fork, `openapi-pydantic`, is recommended for ongoing projects, as it includes support for Pydantic v2.x and continued development.
- breaking This library is primarily designed for Pydantic v1.x. Using it with Pydantic v2.x may lead to unexpected behavior or validation errors, especially regarding JSON Schema generation, as Pydantic v2.x aligns with OpenAPI v3.1.x's JSON Schema dialect by default, while Pydantic v1.x aligns with OpenAPI v3.0.x.
- gotcha Since version 1.2.0, the library defaults to generating OpenAPI v3.1.0 specifications. If you need to generate OpenAPI v3.0.3, you must explicitly import models from `openapi_schema_pydantic.v3.v3_0_3`.
- breaking In version 1.2.2, the default Pydantic `extra` configuration was changed from `Extra.forbid` to `Extra.ignore`. This means that unknown fields in input data, which previously would have raised a validation error, are now silently ignored. [GitHub Releases]
- gotcha When serializing OpenAPI models to JSON, for Pydantic v1.x (which this library primarily uses), you should call the `.json()` method. Using `.model_dump_json()` will not work as it's a Pydantic v2.x method.
Install
-
pip install openapi-schema-pydantic
Imports
- OpenAPI, Info, PathItem, Operation, Response
from openapi_schema_pydantic import OpenAPI, Info, PathItem, Operation, Response
- OpenAPI (for v3.0.3)
from openapi_schema_pydantic.v3.v3_0_3 import OpenAPI
Quickstart
from openapi_schema_pydantic import OpenAPI, Info, PathItem, Operation, Response
# Construct OpenAPI by pydantic objects
open_api = OpenAPI(
info=Info(
title='My own API',
version='v0.0.1',
),
paths={
'/ping': PathItem(
get=Operation(
responses={
'200': Response(description='pong')
}
)
)
},
)
# For Pydantic v1.x (which this library primarily supports), use .json()
print(open_api.json(by_alias=True, exclude_none=True, indent=2))