🌐
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 › 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%
🌐
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
The following examples all produce the same OpenAPI result as above: 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%
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
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_sch...
🌐
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
🌐
Speakeasy
speakeasy.com › openapi › frameworks › pydantic
How To Generate an OpenAPI Document With Pydantic V2 | Speakeasy
January 22, 2026 - Can have multiple owners." properties: id: description: The pet's unique identifier examples: - 1 title: Pet ID type: integer name: description: Name of the pet examples: - Fido title: Pet Name type: string breed: anyOf: - type: string - type: "null" default: null description: Breed of the pet examples: - Golden Retriever - Siamese - Parakeet title: Pet Breed required: - id - name title: Pet type: object · Enums in OpenAPI are useful for defining a set of possible values for a field. Let’s add an enum called PetType to the Pet model to represent different types of pets. from enum import StrEnum import yaml from pydantic import BaseModel, Field from pydantic.json_schema import models_json_schema class PetType(StrEnum): """ An enumeration of pet types.
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › schema
Schema - Pydantic
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, ...
🌐
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%
🌐
FastAPI
fastapi.tiangolo.com › tutorial › schema-extra-example
Declare Request Example Data - FastAPI
Even after OpenAPI 3.1.0 was released ... examples inside a Pydantic model, using schema_extra or Field(examples=["something"]) that example is added to the JSON Schema for that Pydantic model....
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",
    )
Find elsewhere
🌐
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: Class · Field name in the class · Alias (as in OpenAPI spec) Header* param_in · in · MediaType · media_type_schema · schema · Parameter ·
Author   kuimono
🌐
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 ·
🌐
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={...
Top answer
1 of 2
1

According to documentation, This OpenAPI-specific examples goes in another section in the OpenAPI specification. It goes in the details for each path operation, not inside each JSON Schema..

So, these examples relate to the path operation, not to the input parameter's schema.

You should pass these examples as a parameter of Path(), Query(), Header(), Cookie(), Body(), etc..

It's shown in the documentation how to use openapi_examples:

@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: Annotated[
        Item,
        Body(
            openapi_examples={
                "normal": {
                    "summary": "A normal example",
                    "description": "A **normal** item works correctly.",
                    "value": {
                        "name": "Foo",
                        "description": "A very nice Item",
                        "price": 35.4,
                        "tax": 3.2,
                    },
                },
                "converted": {
                    "summary": "An example with converted data",
                    "description": "FastAPI can convert price `strings` to actual `numbers` automatically",
                    "value": {
                        "name": "Bar",
                        "price": "35.4",
                    },
                },
                "invalid": {
                    "summary": "Invalid data is rejected with an error",
                    "value": {
                        "name": "Baz",
                        "price": "thirty five point four",
                    },
                },
            },
        ),
    ],
):
    results = {"item_id": item_id, "item": item}
    return results

I think it's possible to store these examples in private field of pydantic model (class attribute) and pass it to Body() like:

@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: Annotated[
        Item,
        Body(
            openapi_examples=Item._openapi_examples,
        ),
    ],
):
    results = {"item_id": item_id, "item": item}
    return results

2 of 2
0

Here is docs link for @Yurii answer.

I found using sub class in the class bit nicer:

class CreateRequest(BaseModel):
    
    class Config: 
        schema_extra = {}

async def create_item(CreateRequest: Annotated[CreateRequest, Body(openapi_examples = CreateRequest.Config.schema_extra)]):
    pass

🌐
Medium
medium.com › @fberndt87 › autogenerate-pydantic-models-from-openapi-yaml-75ed38858e56
Autogenerate pydantic models from openapi.yaml | by Felix E. | Medium
November 15, 2022 - Your first Idea maybe is to generate the initial data on editor.swagger.io but the outcome of that approach is a simple Python class and you need to rewrite everything to a pydantic Model and update the request functions too.
🌐
OpenAPI Generator
openapi-generator.tech › docs › generators › python-pydantic-v1
Documentation for the python-pydantic-v1 Generator | OpenAPI Generator
December 13, 2023 - These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to configuration docs for more details
🌐
Koxudaxi
koxudaxi.github.io › datamodel-code-generator › openapi
Generate from OpenAPI - datamodel-code ... - GitHub Pages
# generated by datamodel-codegen: # filename: api.yaml # timestamp: 2020-06-02T05:28:24+00:00 from __future__ import annotations from typing import List, Optional from pydantic import AnyUrl, BaseModel, Field class Pet(BaseModel): id: int name: str tag: Optional[str] = None class Pets(BaseModel): __root__: List[Pet] class Error(BaseModel): code: int message: str class Api(BaseModel): apiKey: Optional[str] = Field( None, description='To be used as a dataset parameter value' ) apiVersionNumber: Optional[str] = Field( None, description='To be used as a version parameter value' ) apiUrl: Optional[AnyUrl] = Field( None, description="The URL describing the dataset's fields" ) apiDocumentationUrl: Optional[AnyUrl] = Field( None, description='A URL to the API console for each API' ) class Apis(BaseModel): __root__: List[Api]