Pydantic OpenAPI Schema Implementation

0.5.1 · active · verified Sun Mar 29

openapi-pydantic provides a type-safe and modern implementation of OpenAPI schemas using Pydantic models, currently at version 0.5.1. It facilitates the generation of OpenAPI documents by defining API structures with Python classes, and is actively maintained with updates to support new OpenAPI and Pydantic versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic OpenAPI document by defining an `OpenAPI` object, including `Info`, `PathItem`, `Operation`, and `Response` objects. It also shows how to integrate a custom Pydantic `BaseModel` (`Item`) into the OpenAPI schema components, leveraging Pydantic's `model_json_schema()` for automatic schema generation. The final output is a JSON string representing the OpenAPI specification.

from openapi_pydantic import OpenAPI, Info, PathItem, Operation, Response
from pydantic import BaseModel, Field # Ensure pydantic is installed

# Define a simple Pydantic model for a schema component
class Item(BaseModel):
    id: int = Field(..., description="Unique ID of the item")
    name: str = Field(..., description="Name of the item")

# Construct OpenAPI object using imported classes
open_api = OpenAPI(
    info=Info(
        title="My Awesome API",
        version="v1.0.0",
        description="A simple API generated with openapi-pydantic."
    ),
    paths={
        "/items": PathItem(
            get=Operation(
                summary="Retrieve all items",
                responses={
                    "200": Response(
                        description="A list of items",
                        content={
                            "application/json": {
                                "schema": {"type": "array", "items": {"$ref": "#/components/schemas/Item"}}
                            }
                        }
                    )
                }
            )
        )
    },
    components={
        "schemas": {
            "Item": Item.model_json_schema() # Use Pydantic's schema generation
        }
    }
)

# For Pydantic v2, use model_dump_json. For Pydantic v1, use .json()
print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2))

view raw JSON →