Pydantic OpenAPI Schema Implementation
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
- breaking Version 0.5.0 introduced significant changes to the internal structure, particularly for supporting multiple OpenAPI specification versions (3.0.4 and 3.1.1). Import paths for specific OpenAPI versions, such as `v3_0`, were adjusted. This might break existing code that used hardcoded version imports.
- breaking Version 0.4.0 included a fix to ensure `Header` objects generate valid OpenAPI specifications. While a 'fix', if your application relied on or processed the previously invalid output, this change could alter behavior or break downstream consumers of your generated spec.
- gotcha The library supports both Pydantic v1 (1.8+) and v2. However, there are API differences between Pydantic versions. For instance, Pydantic v1 uses `.json()` for serialization, while Pydantic v2 uses `.model_dump_json()`. Similarly, `parse_obj` (v1) and `model_validate` (v2) have different usages.
- gotcha While `openapi-pydantic` supports OpenAPI 3.1.1 by default, some older UI rendering tools (e.g., specific versions of Swagger UI) may not fully support OpenAPI 3.1.x. If you encounter rendering issues with your generated spec, it might be due to tool compatibility.
Install
-
pip install openapi-pydantic
Imports
- OpenAPI
from openapi_pydantic import OpenAPI
- Info
from openapi_pydantic import Info
- PathItem
from openapi_pydantic import PathItem
- Operation
from openapi_pydantic import Operation
- Response
from openapi_pydantic import Response
Quickstart
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))