### Install openapi-pydantic Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md Install the library using pip. This command installs the package and its dependencies. ```bash pip install openapi-pydantic ``` -------------------------------- ### Usage Example: Construct OpenAPI v3.1 from Dict Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md Demonstrates constructing an OpenAPI v3.1 schema directly from a dictionary. For Pydantic v1.x, use `parse_obj` instead of `model_validate`. ```python from openapi_pydantic import OpenAPI, PathItem, Response # 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"}}} } }, }) ``` -------------------------------- ### Quick Start: Create OpenAPI Schema Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md Demonstrates the basic usage of openapi-pydantic to create an OpenAPI schema object. It shows how to define API info and paths with operations and responses. For Pydantic v1.x, use `json` instead of `model_dump_json`. ```python from openapi_pydantic import OpenAPI, Info, PathItem, Operation, Response open_api = OpenAPI( info=Info( title="My own API", version="v0.0.1", ), paths={ "/ping": PathItem( get=Operation( responses={ "200": Response( description="pong" ) } ) ) }, ) # For Pydantic 1.x, use `json` instead of `model_dump_json` print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2)) ``` -------------------------------- ### Usage Example: Construct OpenAPI with Mixed Types Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md Illustrates creating an OpenAPI schema using a combination of Python dictionaries and Pydantic model instances. For Pydantic v1.x, use `parse_obj` instead of `model_validate`. ```python from openapi_pydantic import OpenAPI, PathItem, Response # 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")}} ) }, }) ``` -------------------------------- ### Create OpenAPI Root Document Object Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Construct a complete OpenAPI 3.1 specification using Pydantic models. This example demonstrates defining info, servers, tags, paths with operations, request bodies, parameters, and security schemes. Always serialize with `by_alias=True, exclude_none=True` for standards-compliant output. ```python from openapi_pydantic import ( OpenAPI, Info, PathItem, Operation, Response, RequestBody, MediaType, Schema, Parameter, Server, Tag, Components, SecurityScheme, SecurityRequirement ) open_api = OpenAPI( info=Info( title="Pet Store API", version="1.0.0", description="A sample Pet Store API", ), servers=[Server(url="https://api.example.com/v1")], tags=[Tag(name="pets", description="Operations about pets")], paths={ "/pets": PathItem( get=Operation( tags=["pets"], summary="List all pets", operationId="listPets", parameters=[ Parameter( name="limit", param_in="query", description="Max items to return", required=False, param_schema=Schema(type="integer"), ) ], responses={"200": Response(description="A list of pets")}, ), post=Operation( tags=["pets"], summary="Create a pet", operationId="createPet", requestBody=RequestBody( required=True, content={ "application/json": MediaType( media_type_schema=Schema( type="object", properties={"name": Schema(type="string")}, required=["name"], ) ) }, ), responses={"201": Response(description="Pet created")}, ), ), }, components=Components( securitySchemes={ "bearerAuth": SecurityScheme(type="http", scheme="bearer", bearerFormat="JWT") } ), security=[{"bearerAuth": []}], ) # Always serialize with by_alias=True, exclude_none=True print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2)) ``` -------------------------------- ### Usage Example: Parse OpenAPI from Dict Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md Shows how to construct an OpenAPI schema by parsing a Python dictionary. This method infers the schema version automatically. For Pydantic v1.x, use `parse_obj` instead of `model_validate`. ```python 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"}}} } }, }) ``` -------------------------------- ### Generate OpenAPI 3.0 Document with Pydantic Models Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Use `openapi_pydantic.v3.v3_0` for OpenAPI 3.0 compatibility. This example constructs an OpenAPI document using Pydantic models and the `PydanticSchema` utility, suitable for tools that do not support OpenAPI 3.1. ```python from openapi_pydantic.v3.v3_0 import ( OpenAPI, Info, PathItem, Operation, Response, RequestBody, MediaType, Schema ) from openapi_pydantic.v3.v3_0.util import PydanticSchema, construct_open_api_with_schema_class from pydantic import BaseModel, Field class CreateItemRequest(BaseModel): name: str = Field(description="Item name") price: float = Field(gt=0, description="Item price in USD") open_api = OpenAPI.model_validate({ "openapi": "3.0.4", "info": {"title": "Shop API", "version": "1.0.0"}, "paths": { "/items": { "post": { "requestBody": { "required": True, "content": { "application/json": { "schema": PydanticSchema(schema_class=CreateItemRequest) } }, }, "responses": {"201": {"description": "Item created"}}, } } }, }) open_api = construct_open_api_with_schema_class(open_api) print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2)) ``` -------------------------------- ### Parse OpenAPI Object with Version Detection Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Use `parse_obj` to automatically parse a raw dictionary into the correct `OpenAPI` model version (v3.1 or v3.0) based on the 'openapi' field. This example shows parsing a v3.1 specification. ```python from openapi_pydantic import parse_obj from openapi_pydantic.v3 import v3_0, v3_1 # Parses as OpenAPI v3.1 result_31 = parse_obj({ "openapi": "3.1.1", "info": {"title": "My API", "version": "1.0.0"}, "paths": { "/users/{id}": { "get": { "operationId": "getUser", "parameters": [ {"name": "id", "in": "path", "required": True, "schema": {"type": "string"}} ], "responses": { "200": {"description": "User found"}, "404": {"description": "User not found"}, } } } }, }) assert isinstance(result_31, v3_1.OpenAPI) ``` -------------------------------- ### Define OpenAPI Parameters (Path, Query, Header) Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Demonstrates defining path, query, and header parameters for an OpenAPI operation using `openapi_pydantic`. Ensure correct `name`, `param_in`, and `param_schema` are provided. ```python from openapi_pydantic import OpenAPI, PathItem, Operation, Parameter, Response, Schema from openapi_pydantic.v3.v3_1.parameter import ParameterLocation open_api = OpenAPI.model_validate({ "info": {"title": "Items API", "version": "1.0.0"}, "paths": { "/items/{itemId}": PathItem( get=Operation( operationId="getItem", parameters=[ # Path parameter Parameter( name="itemId", param_in=ParameterLocation.PATH, required=True, description="The item ID", param_schema=Schema(type="string"), ), # Query parameter Parameter( name="fields", param_in=ParameterLocation.QUERY, required=False, description="Comma-separated list of fields to include", param_schema=Schema(type="string"), style="form", explode=False, ), # Header parameter Parameter( name="X-Request-ID", param_in=ParameterLocation.HEADER, required=False, param_schema=Schema(type="string", schema_format="uuid"), ), ], responses={"200": Response(description="Item found")}, ) ) }, }) params = open_api.paths["/items/{itemId}"].get.parameters print(params[0].name) # "itemId" print(params[0].param_in.value) # "path" ``` -------------------------------- ### Constructing an OpenAPI Object Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Demonstrates how to create a root OpenAPI document object using Pydantic models, including defining info, servers, tags, paths, operations, parameters, request bodies, and security schemes. ```APIDOC ## Constructing an OpenAPI Object ### Description This example shows how to build a complete OpenAPI 3.1 document programmatically using the `OpenAPI` class and its associated Pydantic models. It includes defining API metadata, server information, tags, paths with GET and POST operations, request bodies, and security schemes. ### Method Instantiate the `OpenAPI` class with relevant Pydantic models. ### Endpoint N/A (Programmatic construction) ### Parameters - **info** (Info): Required. Information about the API. - **servers** (list[Server]): Optional. Server URLs for the API. - **tags** (list[Tag]): Optional. Tags for organizing operations. - **paths** (dict[str, PathItem]): Optional. API paths and their operations. - **components** (Components): Optional. Reusable components like security schemes and schemas. - **security** (list[dict]): Optional. Default security requirements for the API. ### Request Example ```python from openapi_pydantic import ( OpenAPI, Info, PathItem, Operation, Response, RequestBody, MediaType, Schema, Parameter, Server, Tag, Components, SecurityScheme, SecurityRequirement ) open_api = OpenAPI( info=Info( title="Pet Store API", version="1.0.0", description="A sample Pet Store API", ), servers=[Server(url="https://api.example.com/v1")], tags=[Tag(name="pets", description="Operations about pets")], paths={ "/pets": PathItem( get=Operation( tags=["pets"], summary="List all pets", operationId="listPets", parameters=[ Parameter( name="limit", param_in="query", description="Max items to return", required=False, param_schema=Schema(type="integer"), ) ], responses={"200": Response(description="A list of pets")}, ), post=Operation( tags=["pets"], summary="Create a pet", operationId="createPet", requestBody=RequestBody( required=True, content={ "application/json": MediaType( media_type_schema=Schema( type="object", properties={"name": Schema(type="string")}, required=["name"], ) ) }, ), responses={"201": Response(description="Pet created")}, ), ) }, components=Components( securitySchemes={ "bearerAuth": SecurityScheme(type="http", scheme="bearer", bearerFormat="JWT") } ), security=[{"bearerAuth": []}], ) # Serialize to JSON print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2)) ``` ### Response #### Success Response (200) Returns a JSON string representing the OpenAPI document. #### Response Example ```json { "openapi": "3.1.1", "info": {"title": "Pet Store API", "version": "1.0.0", "description": "A sample Pet Store API"}, "servers": [{"url": "https://api.example.com/v1"}], "tags": [{"name": "pets", "description": "Operations about pets"}], "paths": { "/pets": { "get": {...}, "post": {...} } }, "components": { "securitySchemes": { "bearerAuth": {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"} } }, "security": [{"bearerAuth": []}] } ``` ``` -------------------------------- ### Parameter Definition Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Demonstrates how to define various types of parameters (path, query, header) for an OpenAPI operation using the Parameter model. ```APIDOC ## `Parameter` — Path, Query, Header, and Cookie Parameters `Parameter` describes a single operation parameter identified by a `name` and `param_in` (alias for `in`) location. The `schema` field is aliased as `param_schema` in Python. ```python from openapi_pydantic import OpenAPI, PathItem, Operation, Parameter, Response, Schema from openapi_pydantic.v3.v3_1.parameter import ParameterLocation open_api = OpenAPI.model_validate({ "info": {"title": "Items API", "version": "1.0.0"}, "paths": { "/items/{itemId}": PathItem( get=Operation( operationId="getItem", parameters=[ # Path parameter Parameter( name="itemId", param_in=ParameterLocation.PATH, required=True, description="The item ID", param_schema=Schema(type="string"), ), # Query parameter Parameter( name="fields", param_in=ParameterLocation.QUERY, required=False, description="Comma-separated list of fields to include", param_schema=Schema(type="string"), style="form", explode=False, ), # Header parameter Parameter( name="X-Request-ID", param_in=ParameterLocation.HEADER, required=False, param_schema=Schema(type="string", schema_format="uuid"), ), ], responses={"200": Response(description="Item found")}, ) ) } }) params = open_api.paths["/items/{itemId}"].get.parameters print(params[0].name) # "itemId" print(params[0].param_in.value) # "path" ``` ``` -------------------------------- ### Define Reusable OpenAPI Components (Schemas, Responses, RequestBodies) Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Illustrates defining reusable components like schemas, responses, and request bodies within an OpenAPI Pydantic model. Use `$ref` to reference these components in paths. ```python from openapi_pydantic import ( OpenAPI, Components, Schema, Response, Parameter, RequestBody, MediaType, Reference ) open_api = OpenAPI.model_validate({ "info": {"title": "Reusable Components API", "version": "1.0.0"}, "paths": { "/orders": { "post": { "requestBody": {"$ref": "#/components/requestBodies/OrderBody"}, "responses": { "201": {"$ref": "#/components/responses/CreatedResponse"}, "400": {"$ref": "#/components/responses/BadRequest"}, }, } } }, "components": { "schemas": { "Order": { "type": "object", "properties": { "id": {"type": "string"}, "item": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}, }, "required": ["item", "qty"], }, "Error": { "type": "object", "properties": { "code": {"type": "integer"}, "message": {"type": "string"}, }, }, }, "responses": { "CreatedResponse": { "description": "Resource created", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Order"} } }, }, "BadRequest": { "description": "Invalid input", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Error"} } }, }, }, "requestBodies": { "OrderBody": { "required": True, "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Order"} } } } }, }, }) print(list(open_api.components.schemas.keys())) # ['Order', 'Error'] print(list(open_api.components.responses.keys())) # ['CreatedResponse', 'BadRequest'] ``` -------------------------------- ### Import OpenAPI 3.0 Components Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md Use these imports to leverage OpenAPI 3.0.x compatibility, which may be required for certain UI renderings like Swagger. ```python from openapi_pydantic.v3.v3_0 import OpenAPI, ... from openapi_pydantic.v3.v3_0.util import PydanticSchema, construct_open_api_with_schema_class ``` -------------------------------- ### Components for Reusable Elements Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Illustrates how to define reusable components, including schemas, responses, and request bodies, within an OpenAPI Pydantic model. ```APIDOC ## `Components` — Reusable Schema Elements `Components` holds reusable objects for schemas, responses, parameters, examples, request bodies, headers, security schemes, links, and callbacks. All fields are optional dicts keyed by string names. ```python from openapi_pydantic import ( OpenAPI, Components, Schema, Response, Parameter, RequestBody, MediaType, Reference ) open_api = OpenAPI.model_validate({ "info": {"title": "Reusable Components API", "version": "1.0.0"}, "paths": { "/orders": { "post": { "requestBody": {"$ref": "#/components/requestBodies/OrderBody"}, "responses": { "201": {"$ref": "#/components/responses/CreatedResponse"}, "400": {"$ref": "#/components/responses/BadRequest"}, }, } } }, "components": { "schemas": { "Order": { "type": "object", "properties": { "id": {"type": "string"}, "item": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}, }, "required": ["item", "qty"], }, "Error": { "type": "object", "properties": { "code": {"type": "integer"}, "message": {"type": "string"}, }, }, }, "responses": { "CreatedResponse": { "description": "Resource created", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Order"} } }, }, "BadRequest": { "description": "Invalid input", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Error"} } }, }, }, "requestBodies": { "OrderBody": { "required": True, "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Order"} } }, } }, }, }) print(list(open_api.components.schemas.keys())) # ['Order', 'Error'] print(list(open_api.components.responses.keys())) # ['CreatedResponse', 'BadRequest'] ``` ``` -------------------------------- ### SecurityScheme Class Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt The `SecurityScheme` class defines authentication mechanisms. It supports various types like `apiKey`, `http`, `mutualTLS`, `oauth2`, and `openIdConnect`, with specific fields for configuration. ```APIDOC ## `SecurityScheme` — Security Definitions `SecurityScheme` defines an authentication mechanism. Supported types are `apiKey`, `http`, `mutualTLS`, `oauth2`, and `openIdConnect`. The `in` field uses the alias `security_scheme_in` in Python. ```python from openapi_pydantic import OpenAPI, Components, SecurityScheme, OAuthFlows, OAuthFlow open_api = OpenAPI.model_validate({ "info": {"title": "Secure API", "version": "1.0.0"}, "paths": {}, "components": { "securitySchemes": { # API Key in header "ApiKeyAuth": { "type": "apiKey", "name": "X-API-Key", "in": "header", }, # HTTP Bearer JWT "BearerAuth": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT", }, # OAuth2 Authorization Code "OAuth2": { "type": "oauth2", "flows": { "authorizationCode": { "authorizationUrl": "https://auth.example.com/oauth/authorize", "tokenUrl": "https://auth.example.com/oauth/token", "scopes": { "read:users": "Read user data", "write:users": "Write user data", }, } }, }, } }, "security": [{"BearerAuth": []}], }) scheme = open_api.components.securitySchemes["OAuth2"] print(scheme.type) # "oauth2" print(scheme.flows.authorizationCode.tokenUrl) # "https://auth.example.com/oauth/token" ``` ``` -------------------------------- ### Construct OpenAPI with Explicit Schema Classes Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Use `construct_open_api_with_schema_class` to explicitly provide schema classes, disable automatic scanning for performance, and control alias serialization. This is useful when schema classes are not directly referenced by Pydantic models. ```python from pydantic import BaseModel from openapi_pydantic import OpenAPI from openapi_pydantic.util import construct_open_api_with_schema_class class ErrorResponse(BaseModel): code: int message: str class PaginationMeta(BaseModel): page: int per_page: int total: int open_api = OpenAPI.model_validate({ "info": {"title": "My API", "version": "1.0.0"}, "paths": {}, }) # Explicitly pass schema classes that are not referenced via PydanticSchema open_api = construct_open_api_with_schema_class( open_api, schema_classes=[ErrorResponse, PaginationMeta], # Injected directly into components/schemas scan_for_pydantic_schema_reference=False, # Skip traversal scan (faster) by_alias=True, # Use field aliases in generated schemas ) print(list(open_api.components.schemas.keys())) # ['ErrorResponse', 'PaginationMeta'] ``` -------------------------------- ### construct_open_api_with_schema_class Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt This function constructs an OpenAPI object with schema classes. It allows explicit passing of schema classes, disabling automatic scanning for faster performance, and controlling alias serialization. ```APIDOC ## `construct_open_api_with_schema_class` — Advanced Options `construct_open_api_with_schema_class` accepts optional parameters to explicitly supply additional schema classes, disable automatic scanning, and control alias serialization. ```python from pydantic import BaseModel from openapi_pydantic import OpenAPI from openapi_pydantic.util import construct_open_api_with_schema_class class ErrorResponse(BaseModel): code: int message: str class PaginationMeta(BaseModel): page: int per_page: int total: int open_api = OpenAPI.model_validate({ "info": {"title": "My API", "version": "1.0.0"}, "paths": {}, }) # Explicitly pass schema classes that are not referenced via PydanticSchema open_api = construct_open_api_with_schema_class( open_api, schema_classes=[ErrorResponse, PaginationMeta], # Injected directly into components/schemas scan_for_pydantic_schema_reference=False, # Skip traversal scan (faster) by_alias=True, # Use field aliases in generated schemas ) print(list(open_api.components.schemas.keys())) # ['ErrorResponse', 'PaginationMeta'] ``` ``` -------------------------------- ### Parsing OpenAPI Documents Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Explains how to use the `parse_obj` function to automatically parse a raw dictionary into the correct typed `OpenAPI` model based on the OpenAPI version specified in the document. ```APIDOC ## `parse_obj` — Auto-Versioned Parsing ### Description The `parse_obj` function inspects the `"openapi"` field of a raw dictionary to determine the OpenAPI version and returns the corresponding typed `OpenAPI` model instance (`OpenAPIv3_1` for 3.1.x or `OpenAPIv3_0` for 3.0.x). ### Method Call the `parse_obj` function with a dictionary representing an OpenAPI document. ### Endpoint N/A (Function call) ### Parameters - **data** (dict): A dictionary containing the OpenAPI document structure. ### Request Example ```python from openapi_pydantic import parse_obj from openapi_pydantic.v3 import v3_0, v3_1 # Parses as OpenAPI v3.1 result_31 = parse_obj({ "openapi": "3.1.1", "info": {"title": "My API", "version": "1.0.0"}, "paths": { "/users/{id}": { "get": { "operationId": "getUser", "parameters": [ {"name": "id", "in": "path", "required": True, "schema": {"type": "string"}} ], "responses": { "200": {"description": "User found"}, "404": {"description": "User not found"}, } } } }, }) assert isinstance(result_31, v3_1.OpenAPI) # Example for OpenAPI v3.0 (assuming a v3.0 structure) # result_30 = parse_obj({ # "openapi": "3.0.0", # "info": {"title": "My API v3.0", "version": "1.0.0"}, # "paths": { ... } # }) # assert isinstance(result_30, v3_0.OpenAPI) ``` ### Response #### Success Response (200) An instance of `OpenAPIv3_1` or `OpenAPIv3_0` depending on the input document's `openapi` version field. #### Response Example ```python # For OpenAPI v3.1 input: # # For OpenAPI v3.0 input: # ``` ``` -------------------------------- ### Construct OpenAPI with Pydantic Schemas Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md Define API paths and operations using Pydantic models for request and response schemas. Ensure correct Pydantic version usage for `model_validate` or `parse_obj`. ```python from pydantic import BaseModel, Field from openapi_pydantic import OpenAPI from openapi_pydantic.util import PydanticSchema, construct_open_api_with_schema_class def construct_base_open_api() -> OpenAPI: # For Pydantic 1.x, use `parse_obj` instead of `model_validate` return OpenAPI.model_validate({ "info": {"title": "My own API", "version": "v0.0.1"}, "paths": { "/ping": { "post": { "requestBody": {"content": {"application/json": { "schema": PydanticSchema(schema_class=PingRequest) }}}, "responses": {"200": { "description": "pong", "content": {"application/json": { "schema": PydanticSchema(schema_class=PingResponse) }}, }}, } } }, }) class PingRequest(BaseModel): """Ping Request""" req_foo: str = Field(description="foo value of the request") req_bar: str = Field(description="bar value of the request") class PingResponse(BaseModel): """Ping response""" resp_foo: str = Field(description="foo value of the response") resp_bar: str = Field(description="bar value of the response") open_api = construct_base_open_api() open_api = construct_open_api_with_schema_class(open_api) # print the result openapi.json # For Pydantic 1.x, use `json` instead of `model_dump_json` print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2)) ``` -------------------------------- ### Integrate Pydantic Models with OpenAPI Schemas Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Uses `PydanticSchema` as a placeholder for Pydantic `BaseModel` classes within an OpenAPI object. `construct_open_api_with_schema_class` resolves these placeholders to `$ref` and populates `components/schemas`. ```python from pydantic import BaseModel, Field from openapi_pydantic import OpenAPI from openapi_pydantic.util import PydanticSchema, construct_open_api_with_schema_class class CreateUserRequest(BaseModel): """User creation payload.""" username: str = Field(description="Unique username") email: str = Field(description="User email address") age: int = Field(ge=0, description="Age in years") class UserResponse(BaseModel): """User resource.""" id: str = Field(description="User UUID") username: str = Field(description="Unique username") email: str = Field(description="User email address") # Build the OpenAPI object using PydanticSchema placeholders open_api = OpenAPI.model_validate({ "info": {"title": "User API", "version": "1.0.0"}, "paths": { "/users": { "post": { "summary": "Create a user", "requestBody": { "required": True, "content": { "application/json": { "schema": PydanticSchema(schema_class=CreateUserRequest) } }, }, "responses": { "201": { "description": "User created", "content": { "application/json": { "schema": PydanticSchema(schema_class=UserResponse) } }, } }, } } }, }) # Resolve PydanticSchema → $ref and populate components/schemas open_api = construct_open_api_with_schema_class(open_api) print(open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2)) ``` -------------------------------- ### Serialize OpenAPI Documents with Aliases and None Exclusion Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Always serialize OpenAPI objects using `by_alias=True` and `exclude_none=True` for spec-compliant output. This ensures that fields with Python-safe aliases (like `schema`, `in`, `not`, `$ref`) are correctly represented in the final JSON. ```python from openapi_pydantic import OpenAPI, Info, PathItem, Operation, Response from openapi_pydantic.compat import PYDANTIC_V2 open_api = OpenAPI( info=Info(title="My API", version="1.0.0"), paths={"/health": PathItem(get=Operation(responses={"200": Response(description="OK")}))}, ) if PYDANTIC_V2: # Pydantic 2: use model_dump / model_dump_json json_str = open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2) data_dict = open_api.model_dump(by_alias=True, exclude_none=True) else: # Pydantic 1: use json / dict json_str = open_api.json(by_alias=True, exclude_none=True, indent=2) data_dict = open_api.dict(by_alias=True, exclude_none=True) print(json_str) ``` ```python # Note: without by_alias=True, aliased fields appear wrong bad_output = open_api.model_dump_json(indent=2) # "$ref" becomes "ref", "in" becomes "param_in", etc. ``` -------------------------------- ### Define Security Schemes for OpenAPI Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Use `SecurityScheme` to define authentication mechanisms like API keys, HTTP bearer tokens, and OAuth2 flows. The `in` field for API keys is aliased to `security_scheme_in` in Python. This allows specifying various security definitions within the OpenAPI components. ```python from openapi_pydantic import OpenAPI, Components, SecurityScheme, OAuthFlows, OAuthFlow open_api = OpenAPI.model_validate({ "info": {"title": "Secure API", "version": "1.0.0"}, "paths": {}, "components": { "securitySchemes": { # API Key in header "ApiKeyAuth": { "type": "apiKey", "name": "X-API-Key", "in": "header", }, # HTTP Bearer JWT "BearerAuth": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT", }, # OAuth2 Authorization Code "OAuth2": { "type": "oauth2", "flows": { "authorizationCode": { "authorizationUrl": "https://auth.example.com/oauth/authorize", "tokenUrl": "https://auth.example.com/oauth/token", "scopes": { "read:users": "Read user data", "write:users": "Write user data", }, } }, }, } }, "security": [{"BearerAuth": []}], }) scheme = open_api.components.securitySchemes["OAuth2"] print(scheme.type) # "oauth2" print(scheme.flows.authorizationCode.tokenUrl) # "https://auth.example.com/oauth/token" ``` -------------------------------- ### OpenAPI Model Dumping Options Source: https://github.com/mike-oakley/openapi-pydantic/blob/main/README.md When dumping Pydantic models to JSON or dict for OpenAPI compatibility, always use `by_alias=True, exclude_none=True`. This ensures correct field aliasing and excludes fields with null values. ```python # OK (Pydantic 2) open_api.model_dump_json(by_alias=True, exclude_none=True, indent=2) # OK (Pydantic 1) open_api.json(by_alias=True, exclude_none=True, indent=2) # Not good open_api.model_dump_json(indent=2) open_api.json(indent=2) ``` -------------------------------- ### Schema Class Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt The `Schema` class is the core for describing data structures, supporting JSON Schema Draft 2020-12 and OpenAPI extensions. It handles conflicts with Python keywords using aliases. ```APIDOC ## `Schema` — JSON Schema Object `Schema` is the core data-typing class for describing request/response body structures, supporting all JSON Schema Draft 2020-12 keywords plus OpenAPI extensions like `discriminator`, `xml`, and `externalDocs`. Fields that conflict with Python keywords use aliases (`format` → `schema_format`, `not` → `schema_not`). ```python from openapi_pydantic import Schema, Reference from openapi_pydantic.v3.v3_1.datatype import DataType # A complex nested schema using composition address_schema = Schema( type=DataType.OBJECT, properties={ "street": Schema(type=DataType.STRING), "city": Schema(type=DataType.STRING), "zip": Schema(type=DataType.STRING, pattern=r"^\d{5}$"), }, required=["street", "city"], ) user_schema = Schema( type=DataType.OBJECT, properties={ "id": Schema(type=DataType.INTEGER, readOnly=True), "name": Schema(type=DataType.STRING, minLength=1, maxLength=100), "email": Schema(type=DataType.STRING, schema_format="email"), "role": Schema( type=DataType.STRING, enum=["admin", "user", "guest"], default="user", ), "address": address_schema, "tags": Schema( type=DataType.ARRAY, items=Schema(type=DataType.STRING), uniqueItems=True, ), }, required=["id", "name", "email"], ) # allOf composition with $ref pet_schema = Schema( allOf=[ Reference(**{"$ref": "#/components/schemas/BasePet"}), Schema( type=DataType.OBJECT, properties={"huntingSkill": Schema(type=DataType.STRING, default="lazy")}, required=["huntingSkill"], ), ] ) # Serialize for use in components from openapi_pydantic.compat import PYDANTIC_V2 dump = user_schema.model_dump if PYDANTIC_V2 else user_schema.dict print(dump(by_alias=True, exclude_none=True)) ``` ``` -------------------------------- ### Parse OpenAPI v3.0 Specification Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Parses a dictionary conforming to the OpenAPI v3.0 specification into a typed OpenAPI object. Asserts the type of the parsed object. ```python result_30 = parse_obj({ "openapi": "3.0.4", "info": {"title": "Legacy API", "version": "0.9.0"}, "paths": {"/": {}}, }) assert isinstance(result_30, v3_0.OpenAPI) ``` -------------------------------- ### Define Complex JSON Schema with openapi_pydantic.Schema Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt The `Schema` class supports JSON Schema Draft 2020-12 keywords and OpenAPI extensions. Use it to define complex nested structures, compositions with `$ref`, and various data types with constraints like patterns, lengths, and enums. Fields conflicting with Python keywords are aliased. ```python from openapi_pydantic import Schema, Reference from openapi_pydantic.v3.v3_1.datatype import DataType # A complex nested schema using composition address_schema = Schema( type=DataType.OBJECT, properties={ "street": Schema(type=DataType.STRING), "city": Schema(type=DataType.STRING), "zip": Schema(type=DataType.STRING, pattern=r"^\d{5}$"), }, required=["street", "city"], ) user_schema = Schema( type=DataType.OBJECT, properties={ "id": Schema(type=DataType.INTEGER, readOnly=True), "name": Schema(type=DataType.STRING, minLength=1, maxLength=100), "email": Schema(type=DataType.STRING, schema_format="email"), "role": Schema( type=DataType.STRING, enum=["admin", "user", "guest"], default="user", ), "address": address_schema, "tags": Schema( type=DataType.ARRAY, items=Schema(type=DataType.STRING), uniqueItems=True, ), }, required=["id", "name", "email"], ) # allOf composition with $ref pet_schema = Schema( allOf=[ Reference(**{"$ref": "#/components/schemas/BasePet"}), Schema( type=DataType.OBJECT, properties={"huntingSkill": Schema(type=DataType.STRING, default="lazy")}, required=["huntingSkill"], ), ] ) # Serialize for use in components from openapi_pydantic.compat import PYDANTIC_V2 dump = user_schema.model_dump if PYDANTIC_V2 else user_schema.dict print(dump(by_alias=True, exclude_none=True)) ``` -------------------------------- ### Construct OpenAPI Object from Dict (Pydantic 2) Source: https://context7.com/mike-oakley/openapi-pydantic/llms.txt Validates and coerces a raw dictionary into a typed OpenAPI object using `model_validate`. Supports nested dictionaries and mixed object/dictionary inputs. ```python from openapi_pydantic import OpenAPI, PathItem, Response # From a plain dict open_api = OpenAPI.model_validate({ "info": {"title": "My own API", "version": "v0.0.1"}, "paths": { "/ping": { "get": {"responses": {"200": {"description": "pong"}}} } }, }) # Mixed: some fields as objects, others as dicts open_api_mixed = OpenAPI.model_validate({ "info": {"title": "My own API", "version": "v0.0.1"}, "paths": { "/ping": PathItem( get={"responses": {"200": Response(description="pong")}} ) }, }) assert open_api == open_api_mixed print(open_api.openapi) # "3.1.1" print(open_api.paths["/ping"].get.responses["200"].description) # "pong" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.