The Normal Process
Understanding how FastAPI generates OpenAPI schemas helps you customize them effectively.How OpenAPI Generation Works
AFastAPI application instance has an .openapi() method that returns the OpenAPI schema:
- When the application starts, a path operation for
/openapi.jsonis registered - This endpoint returns a JSON response from the
.openapi()method - The method checks the
.openapi_schemaproperty and returns it if available - If not available, it generates the schema using
fastapi.openapi.utils.get_openapi()
The
.openapi_schema property acts as a cache to avoid regenerating the schema on every request.The get_openapi() Function
Theget_openapi() utility function accepts these parameters:
title: The OpenAPI title shown in the docsversion: Your API version (e.g.,2.5.0)openapi_version: The OpenAPI specification version (default:3.1.0)summary: A short summary of the APIdescription: Detailed API description (supports Markdown)routes: List of registered path operations fromapp.routeswebhooks: Webhook definitionstags: Tag metadata for organizing endpointsservers: Server informationterms_of_service: Terms of service URLcontact: Contact informationlicense_info: License details
Customizing the OpenAPI Schema
You can override the default OpenAPI generation to add custom extensions or modify the schema.Basic FastAPI Application
Start with a standard FastAPI application:Create a custom_openapi() Function
Define a function that generates and customizes the OpenAPI schema:The
if app.openapi_schema: check ensures the schema is only generated once and then cached for subsequent requests.Override the openapi() Method
Replace the default method with your custom function:Common Customization Examples
Adding Vendor Extensions
Many tools support vendor-specific extensions (prefixed withx-):
Modifying Security Schemes
Customize authentication documentation:Adding Custom Response Examples
Enhance API documentation with additional examples:Viewing Your Custom Schema
After customizing the OpenAPI schema:- Start your application with
uvicorn main:app --reload - Visit
/docsto see your changes in Swagger UI - Visit
/redocto see your changes in ReDoc - Access
/openapi.jsonto view the raw schema
Best Practices
- Test thoroughly: Validate your custom schema using OpenAPI validators
- Document extensions: Add comments explaining custom vendor extensions
- Preserve structure: Don’t remove required OpenAPI fields
- Use type checking: Leverage Python type hints when modifying the schema
Complete Example
Here’s a full example combining multiple customizations:Related Topics
- OpenAPI Callbacks - Document callback requests
- OpenAPI Webhooks - Document webhook endpoints
- Conditional OpenAPI - Control OpenAPI availability