🌐
PyPI
pypi.org › project › openapi-pydantic
openapi-pydantic · PyPI
OpenAPI schema implemented in Pydantic.
      » pip install openapi-pydantic
    
Published   Jan 08, 2025
Version   0.5.1
🌐
GitHub
github.com › mike-oakley › openapi-pydantic
GitHub - mike-oakley/openapi-pydantic: Modern, type-safe OpenAPI schemas in Python using Pydantic 1.8+ and 2.x
from openapi_pydantic import parse_obj, OpenAPI, PathItem, Response # Construct OpenAPI from dict, inferring the correct schema version open_api = parse_obj({ "openapi": "3.1.1", "info": {"title": "My own API", "version": "v0.0.1"}, "paths": { "/ping": { "get": {"responses": {"200": {"description": "pong"}}} } }, }) # Construct OpenAPI v3.1 schema from dict # For Pydantic 1.x, use `parse_obj` instead of `model_validate` 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 open_api = OpenAPI.model_validate({ "info": {"title": "My own API", "version": "v0.0.1"}, "paths": { "/ping": PathItem( get={"responses": {"200": Response(description="pong")}} ) }, })
Starred by 115 users
Forked by 23 users
Languages   Python 100.0% | Python 100.0%
🌐
GitHub
github.com › kuimono › openapi-schema-pydantic
GitHub - kuimono/openapi-schema-pydantic: OpenAPI (v3) specification schema as pydantic class
from openapi_schema_pydantic.v3.v3_0_3.util import PydanticSchema, construct_open_api_with_schema_class
Starred by 122 users
Forked by 22 users
Languages   Python 100.0% | Python 100.0%
🌐
Speakeasy
speakeasy.com › openapi › frameworks › pydantic
How To Generate an OpenAPI Document With Pydantic V2 | Speakeasy
January 22, 2026 - Next, we’ll update the print_json_schema function to print a JSON schema that resembles an OpenAPI document’s components section. import yaml from pydantic import BaseModel from pydantic.json_schema import models_json_schema class Pet(BaseModel): id: int name: str breed: str class Owner(BaseModel): id: int name: str pets: list[Pet] def print_json_schema(models): _, schemas = models_json_schema( [(model, "validation") for model in models], ref_template="#/components/schemas/{model}", ) openapi_schema = { "components": { "schemas": schemas.get('$defs'), } } print(yaml.dump(openapi_schema)) if __name__ == "__main__": print_json_schema([Pet, Owner])
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
This is useful if you need to extend or modify the JSON schema default definitions location. For example, with OpenAPI: import json from pydantic import BaseModel from pydantic.type_adapter import TypeAdapter class Foo(BaseModel): a: int class Model(BaseModel): a: Foo adapter = TypeAdapter(Model) print( json.dumps( adapter.json_schema(ref_template='#/components/schemas/{model}'), indent=2, ) )
🌐
PyPI
pypi.org › project › openapi-schema-pydantic
openapi-schema-pydantic · PyPI
from openapi_schema_pydantic.v3.v3_0_3 import OpenAPI, ...
      » pip install openapi-schema-pydantic
    
Published   Jun 29, 2022
Version   1.2.4
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › schema
Schema - Pydantic
This is useful if you need to extend or modify the JSON Schema default definitions location. E.g. with OpenAPI: ... import json from pydantic import BaseModel from pydantic.schema import schema class Foo(BaseModel): a: int class Model(BaseModel): a: Foo # Default location for OpenAPI top_level_schema = schema([Model], ref_prefix='#/components/schemas/') print(json.dumps(top_level_schema, indent=2))
🌐
GitHub
github.com › litestar-org › pydantic-openapi-schema
GitHub - litestar-org/pydantic-openapi-schema: Generate OpenAPI 3.x.x using Pydantic
Generate OpenAPI 3.x.x using Pydantic. Contribute to litestar-org/pydantic-openapi-schema development by creating an account on GitHub.
Starred by 11 users
Forked by 4 users
Languages   Python 99.8% | Dockerfile 0.2% | Python 99.8% | Dockerfile 0.2%
🌐
GitHub
github.com › kuimono › openapi-schema-pydantic › blob › master › openapi_schema_pydantic › v3 › v3_0_3 › README.md
openapi-schema-pydantic/openapi_schema_pydantic/v3/v3_0_3/README.md at master · kuimono/openapi-schema-pydantic
Due to the reserved words in python and pydantic, the following fields are used with alias feature provided by pydantic: ... The "in" field in Header object is actually a constant ({"in": "header"}). For convenience of object creation, the classes mentioned in above has configured allow_population_by_field_name=True. ... Due to the constriants of python typing structure (not able to handle dynamic field names), the following schema classes are actually just a typing of Dict:
Author   kuimono
🌐
FastAPI
fastapi.tiangolo.com › how-to › separate-openapi-schemas
Separate OpenAPI Schemas for Input and Output or Not - FastAPI
And if you check all the available Schemas (JSON Schemas) in OpenAPI, you will see that there are two, one Item-Input and one Item-Output. For Item-Input, description is not required, it doesn't have a red asterisk. But for Item-Output, description is required, it has a red asterisk. With this feature from Pydantic v2, your API documentation is more precise, and if you have autogenerated clients and SDKs, they will be more precise too, with a better developer experience and consistency.
Find elsewhere
Top answer
1 of 2
7

FastAPI will generate schemas for models that are used either as a Request Body or Response Model. When declaring query_args: FaultQueryParams = Depends() (using Depends), your endpoint would not expect a request body, but rather query parameters; hence, FaultQueryParams would not be included in the schemas of the OpenAPI docs.

To add additional schemas, you could extend/modify the OpenAPI schema. Example is given below (make sure to add the code for modifying the schema after all routes have been defined, i.e., at the end of your code).

class FaultQueryParams(BaseModel):
    f_id: Optional[int] = Field(None, description="id for the host", example=12345, title="Fault ID")
    hostname: Optional[str]
    status: Literal["open", "closed", "all"] = Field("open")
    ...
    
@app.post('/predict')
def predict(query_args: FaultQueryParams = Depends()):
    return query_args

def get_extra_schemas():
    return {
              "FaultQueryParams": {
                "title": "FaultQueryParams",
                "type": "object",
                "properties": {
                  "f_id": {
                    "title": "Fault ID",
                    "type": "integer",
                    "description": "id for the host",
                    "example": 12345
                  },
                  "hostname": {
                    "title": "Hostname",
                    "type": "string"
                  },
                  "status": {
                    "title": "Status",
                    "enum": [
                      "open",
                      "closed",
                      "all"
                    ],
                    "type": "string",
                    "default": "open"
                  },
                   ...
                }
              }
            }

from fastapi.openapi.utils import get_openapi

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="FastAPI",
        version="1.0.0",
        description="This is a custom OpenAPI schema",
        routes=app.routes,
    )
    new_schemas = openapi_schema["components"]["schemas"]
    new_schemas.update(get_extra_schemas())
    openapi_schema["components"]["schemas"] = new_schemas
    
    app.openapi_schema = openapi_schema
    return app.openapi_schema


app.openapi = custom_openapi

Some Helpful Notes

Note 1

Instead of manually typing the schema for the extra models that you would like to add to the docs, you can have FastAPI do that for you by adding to your code an endpoint (which you would subsequently remove, after getting the schema) using that model as a request body or response model, for example:

@app.post('/predict') 
def predict(query_args: FaultQueryParams):
    return query_args

Then, you can get the generated JSON schema at http://127.0.0.1:8000/openapi.json, as described in the documentation. From there, you can either copy and paste the schema of the model to your code and use it directly (as shown in the get_extra_schema() method above) or save it to a file and load the JSON data from the file, as demonstrated below:

import json
...

new_schemas = openapi_schema["components"]["schemas"]

with open('extra_schemas.json') as f:    
    extra_schemas = json.load(f)
    
new_schemas.update(extra_schemas)   
openapi_schema["components"]["schemas"] = new_schemas

...

Note 2

To declare metadata, such as description, example, etc, for your query parameter, you should define your parameter with Query instead of Field, and since you can't do that with Pydantic models, you either need to define the Query parameter(s) directly in the endpoint or use a custom dependency class, as shown below:

from fastapi import FastAPI, Query, Depends
from typing import Optional

class FaultQueryParams:
    def __init__(
        self,
        f_id: Optional[int] = Query(None, description="id for the host", example=12345)

    ):
        self.f_id = f_id

app = FastAPI()

@app.post('/predict')
def predict(query_args: FaultQueryParams = Depends()):
    return query_args

The above could be re-written using the @dataclass decorator as follows:

from fastapi import FastAPI, Query, Depends
from typing import Optional
from dataclasses import dataclass

@dataclass
class FaultQueryParams:
    f_id: Optional[int] = Query(None, description="id for the host", example=12345)

app = FastAPI()

@app.post('/predict')
def predict(query_args: FaultQueryParams = Depends()):
    return query_args

Update

There is no need for using a custom dependency class anymore, as FastAPI now allows using a Pydantic BaseModel to define query parameters by wrapping the Query() in a Field(); hence, one should be able to use a Pydantic model to define multiple query parameters and declare metadata for them, i.e., description, example, etc. Related answers could be found here and here.

2 of 2
2

Thank to @Chris for the pointers which ultimately led me to use dataclasses for defining query params in bulk and it just worked fine.

@dataclass
class FaultQueryParams1:
    f_id: Optional[int] = Query(None, description="id for the host", example=55555)
    hostname: Optional[str] = Query(None, example="test-host1.domain.com")
    status: Literal["open", "closed", "all"] = Query(
        None, description="fetch open/closed or all records", example="all"
    )
    created_by: Optional[str] = Query(
        None,
        description="fetch records created by particular user",
        example="user-id",
    )
🌐
PyPI
pypi.org › project › pydantic-openapi-schema
pydantic-openapi-schema · PyPI
OpenAPI Schema using pydantic. Forked for Starlite-API from 'openapi-schema-pydantic'.
      » pip install pydantic-openapi-schema
    
Published   Jan 17, 2023
Version   1.5.1
🌐
OpenAPI Generator
openapi-generator.tech › docs › generators › python-pydantic-v1
Documentation for the python-pydantic-v1 Generator | OpenAPI Generator
December 13, 2023 - schema · self · true · try · while · with · yield · METADATA · CONFIG OPTIONS · IMPORT MAPPING · INSTANTIATION TYPES · LANGUAGE PRIMITIVES · RESERVED WORDS · FEATURE SET · Client Modification Feature · Data Type Feature · Documentation Feature ·
🌐
Sanicframework
community.sanicframework.org › questions and help
Problem with generated OpenAPI schema via Pydantic - Questions and Help - Sanic Community Discussion
August 24, 2023 - I’m trying to document endpoints via Pydantic models. When the Pydantic model contains an Enum type, both Swagger and ReDoc fail to render the OpenAPI JSON properly. Here’s a minimal example: from enum import Enum from pydantic import BaseModel from sanic import Sanic, json from sanic_ext import openapi, validate class Size(str, Enum): S = "small" M = "medium" L = "large" class Test(BaseModel): size: Size app = Sanic("TestApp") @app.post("/") @openapi.definition(body={...
🌐
Medium
medium.com › @fberndt87 › autogenerate-pydantic-models-from-openapi-yaml-75ed38858e56
Autogenerate pydantic models from openapi.yaml | by Felix E. | Medium
November 15, 2022 - I had the same struggle as you until I decided to create my own custom project which could handle these with properly defined pydantic models and short, relevant request functions. ... You’re maybe wondering about the validators but this will guarantee the openapi specification about nullable and optional.
🌐
Pydantic
docs.pydantic.dev › latest › integrations › datamodel_code_generator
datamodel-code-generator - Pydantic Validation
The datamodel-code-generator project is a library and command-line utility to generate pydantic models from just about any data source, including: OpenAPI 3 (YAML/JSON) JSON Schema · JSON/YAML/CSV Data (which will be converted to JSON Schema) Python dictionary (which will be converted to JSON Schema) GraphQL schema ·