Package: openapi-pydantic
openapi-pydanticOpenAPI schema implemented inPydantic. Both Pydantic 1.8+ and 2.x are supported.The naming of the classes follows the schema inOpenAPI specification.This library is forked fromOpenAPI Schema Pydantic(at version1.2.4) which is no longer actively maintained.Installationpip install openapi-pydanticTry mefromopenapi_pydanticimportOpenAPI,Info,PathItem,Operation,Response# Construct OpenAPI by pydantic objectsopen_api=OpenAPI(info=Info(title="My own API",version="v0.0.1",),paths={"/ping":PathItem(get=Operation(responses={"200":Response(description="pong")}))},)# Note: for Pydantic 1.x, replace `model_dump_json` with `json`print(open_api.model_dump_json(by_alias=True,exclude_none=True,indent=2))Result:{"openapi":"3.1.0","info":{"title":"My own API","version":"v0.0.1"},"servers":[{"url":"/"}],"paths":{"/ping":{"get":{"responses":{"200":{"description":"pong"}},"deprecated":false}}}}Take advantage of PydanticPydantic is a great tool. It allows you to use object / dict / mixed data for input.The following examples give the same OpenAPI result as above:fromopenapi_pydanticimportparse_obj,OpenAPI,PathItem,Response# Construct OpenAPI from dict, inferring the correct schema versionopen_api=parse_obj({"openapi":"3.1.0","info":{"title":"My own API","version":"v0.0.1"},"paths":{"/ping":{"get":{"responses":{"200":{"description":"pong"}}}}},})# Construct OpenAPI v3.1.0 schema from dict# Note: for Pydantic 1.x, replace `model_validate` with `parse_obj`open_api=OpenAPI.model_validate({"info":{"title":"My own API","version":"v0.0.1"},"paths":{"/ping":{"get":{"responses":{"200":{"description":"pong"}}}}},})# Construct OpenAPI with mix of dict/object# Note: for Pydantic 1.x, replace `model_validate` with `parse_obj`open_api=OpenAPI.model_validate({"info":{"title":"My own API","version":"v0.0.1"},"paths":{"/ping":PathItem(get={"responses":{"200":Response(description="pong")}})},})Use Pydantic classes as schemaTheSchema Objectin OpenAPI has definitions and tweaks in JSON Schema, which are hard to comprehend and define a good data classPydantic already has a good way tocreate JSON schema.
Let's not reinvent the wheel.The approach to deal with this:UsePydanticSchemaobjects to represent theSchemainOpenAPIobjectInvokeconstruct_open_api_with_schema_classto resolve the JSON schemas and referencesfrompydanticimportBaseModel,Fieldfromopenapi_pydanticimportOpenAPIfromopenapi_pydantic.utilimportPydanticSchema,construct_open_api_with_schema_classdefconstruct_base_open_api()->OpenAPI:# Note: for Pydantic 1.x, replace `model_validate` with `parse_obj`returnOpenAPI.model_validate({"info":{"title":"My own API","version":"v0.0.1"},"paths":{"/ping":{"post":{"requestBody":{"content":{"application/json":{"schema":PydanticSchema(schema_class=PingRequest)}}},"responses":{"200":{"description":"pong","content":{"application/json":{"schema":PydanticSchema(schema_class=PingResponse)}},}},}}},})classPingRequest(BaseModel):"""Ping Request"""req_foo:str=Field(description="foo value of the request")req_bar:str=Field(description="bar value of the request")classPingResponse(BaseModel):"""Ping response"""resp_foo:str=Field(description="foo value of the response")resp_bar:str=Field(description="bar value of the response")open_api=construct_base_open_api()open_api=construct_open_api_with_schema_class(open_api)# print the result openapi.json# Note: for Pydantic 1.x, replace `model_dump_json` with `json`print(open_api.model_dump_json(by_alias=True,exclude_none=True,indent=2))Result:{"openapi":"3.1.0","info":{"title":"My own API","version":"v0.0.1"},"servers":[{"url":"/"}],"paths":{"/ping":{"post":{"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PingRequest"}}},"required":false},"responses":{"200":{"description":"pong","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PingResponse"}}}}},"deprecated":false}}},"components":{"schemas":{"PingRequest":{"title":"PingRequest","required":["req_foo","req_bar"],"type":"object","properties":{"req_foo":{"title":"Req Foo","type":"string","description":"foo value of the request"},"req_bar":{"title":"Req Bar","type":"string","description":"bar value of the request"}},"description":"Ping Request"},"PingResponse":{"title":"PingResponse","required":["resp_foo","resp_bar"],"type":"object","properties":{"resp_foo":{"title":"Resp Foo","type":"string","description":"foo value of the response"},"resp_bar":{"title":"Resp Bar","type":"string","description":"bar value of the response"}},"description":"Ping response"}}}}NotesUse of OpenAPI.model_dump() / OpenAPI.model_dump_json() / OpenAPI.json() / OpenAPI.dict()When usingOpenAPI.model_dump()/OpenAPI.model_dump_json()/OpenAPI.json()/OpenAPI.dict()functions,
the argumentsby_alias=True, exclude_none=Truehave to be in place.
Otherwise the resulting json will not fit the OpenAPI standard.# OK (Pydantic 2)open_api.model_dump_json(by_alias=True,exclude_none=True,indent=2)# OK (Pydantic 1)open_api.json(by_alias=True,exclude_none=True,indent=2)# Not goodopen_api.model_dump_json(indent=2)open_api.json(indent=2)More info about field aliases:OpenAPI versionField alias info3.1.0here3.0.3hereNon-pydantic schema typesSome schema types are not implemented as pydantic classes.
Please refer to the following for more info:OpenAPI versionNon-pydantic schema type info3.1.0here3.0.3hereUse OpenAPI 3.0.3 instead of 3.1.0Some UI renderings (e.g. Swagger) still do not support OpenAPI 3.1.0.
The old 3.0.3 version is available by importing from different paths:fromopenapi_pydantic.v3.v3_0_3importOpenAPI,...fromopenapi_pydantic.v3.v3_0_3.utilimportPydanticSchema,construct_open_api_with_schema_classPydantic version compatibilityCompatibility with both major versions of Pydantic (1.8+ and 2.*) is mostly achieved using a module calledcompat.py. It detects the installed version of Pydantic and exports version-specific symbols for use by the rest of the package. It also provides all symbols necessary for type checking. Thecompat.pymodule is not intended to be imported by other packages, but other packages may find it helpful as an example of how to span major versions of Pydantic.CreditsThis library is based from the original implementation by Kuimono ofOpenAPI Schema Pydanticwhich is no longer actively maintained.LicenseMIT License