Registry / serialization / openapi-pydantic

openapi-pydantic

JSON →
library0.5.1pypypi✓ verified 25d ago

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.

pip install openapi-pydantic
INSTALL
IMPORT
SIG · OPENAPI-PYDANTIC
O
openapi-pydantic
serializationpythonv0.5.1
Install
3.4s avg
Import
844ms
Disk
27MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.5.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.872s · 28.6MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.4s · import 0.816s · 28MB
27MB installed
● package 27MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OpenAPI
from openapi_pydantic import OpenAPI
from openapi_pydantic.v3.v3_0 import OpenAPI
For the latest OpenAPI 3.1.1 (default), import directly. For OpenAPI 3.0.x, use `from openapi_pydantic.v3.v3_0 import OpenAPI` due to structural changes in v0.5.0 to accommodate different OAS versions.
Info
from openapi_pydantic import Info
PathItem
from openapi_pydantic import PathItem
Operation
from openapi_pydantic import Operation
Response
from openapi_pydantic import Response

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))
Debug
Known issues
breakingVersion 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.
fix
Review your import statements. For OpenAPI 3.1.1 (default), import directly from `openapi_pydantic`. For OpenAPI 3.0.x, use `from openapi_pydantic.v3.v3_0 import OpenAPI, ...`.
affects: >=0.5.0
breakingVersion 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.
fix
Test your generated OpenAPI documents and any consuming clients after upgrading to ensure compatibility with the now-valid `Header` object definitions.
affects: >=0.4.0
gotchaThe 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.
fix
When writing code that needs to be compatible with both Pydantic versions or when migrating, be mindful of these method name changes. Use `model_dump_json()` and `model_validate()` for Pydantic v2, or check `pydantic.VERSION` for conditional logic if strict compatibility is required.
affects: All versions supporting both Pydantic v1 and v2
gotchaWhile `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.
fix
If experiencing rendering issues, consider explicitly generating an OpenAPI 3.0.x spec by importing from `openapi_pydantic.v3.v3_0` and specifying the version in the `OpenAPI` object's `openapi` field. Alternatively, ensure your rendering tool is updated to a version that supports OpenAPI 3.1.x.
affects: All versions
Errors
Common errors & fixes
AttributeError: 'SomeModel' object has no attribute 'dict'
Pydantic V2, which openapi-pydantic supports, renamed several methods from Pydantic V1. The `.dict()` and `.json()` methods were replaced with `.model_dump()` and `.model_dump_json()` respectively.
fix
Replace `.dict()` with `.model_dump()` and `.json()` with `.model_dump_json()` when working with Pydantic V2 models. For example, `my_model.model_dump()`.
ModuleNotFoundError: No module named 'pydantic_core._pydantic_core'
This error occurs when the core Rust component of Pydantic V2 (`pydantic-core`) is not correctly installed or cannot be found by Pydantic. This can happen due to environment issues, incomplete installation, or incompatible Python versions.
fix
Ensure Pydantic and pydantic-core are properly installed and compatible with your Python version. A common fix is to reinstall them in a clean virtual environment: `pip uninstall pydantic pydantic-core && pip install pydantic`.
Generated OpenAPI schema does not conform to specification (e.g., incorrect aliases or null values included)
When converting an openapi-pydantic model (which is a Pydantic BaseModel) to a dictionary or JSON string for an OpenAPI specification, omitting `by_alias=True` and `exclude_none=True` from `model_dump()` or `model_dump_json()` can lead to an invalid or non-compliant OpenAPI document. Pydantic uses aliases for OpenAPI field names, and `null` values might not be desired in the final spec.
fix
Always include `by_alias=True` and `exclude_none=True` when calling `model_dump()` or `model_dump_json()` on your openapi-pydantic models: `my_openapi_model.model_dump(by_alias=True, exclude_none=True)`.
pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for ...
This error often arises in projects that mix Pydantic V1 and Pydantic V2 models, especially when generating OpenAPI schemas. Pydantic V1 and V2 handle JSON Schema generation differently (e.g., supporting OpenAPI 3.0 vs 3.1), leading to conflicts when both are present and schema introspection occurs.
fix
Consistently use either Pydantic V1 or Pydantic V2 throughout your application's models that contribute to the OpenAPI schema. If a full migration is not immediately possible, explicitly import and use Pydantic V1 models via `from pydantic import v1 as pydantic_v1` for legacy code, keeping them separate from Pydantic V2 models.
Upgrade
Version history
0.5.1latest on PyPI · released Jan 8, 2025
Audit
Dependencies
pydanticrequiredCore dependency for data validation and schema definition. Supports Pydantic 1.8+ and 2.x.
Agent activity
7 hits · last 30 days
node
6
Resources
openapi-pydantic — pip install openapi-pydantic · libregistry