Performance: OpenAPI schema customization
This affects the initial page load speed of API documentation and the bundle size of the OpenAPI schema served to clients.
from fastapi import FastAPI from fastapi.openapi.utils import get_openapi app = FastAPI() # Custom OpenAPI schema to reduce size def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="Custom API", version="1.0.0", routes=app.routes, ) # Remove unused schemas or paths here openapi_schema['paths'] = {k: v for k, v in openapi_schema['paths'].items() if k == '/items/'} app.openapi_schema = openapi_schema return app.openapi_schema app.openapi = custom_openapi @app.get('/items/') async def read_items(): return [{'item_id': 'foo'}]
from fastapi import FastAPI app = FastAPI() # No schema customization, default large schema generated @app.get('/items/') async def read_items(): return [{'item_id': 'foo'}]
| Pattern | Payload Size | Network Impact | Parsing Cost | Verdict |
|---|---|---|---|---|
| Default OpenAPI schema | 150-200kb | High network load | High CPU parsing | [X] Bad |
| Customized minimal schema | 20-50kb | Low network load | Low CPU parsing | [OK] Good |
from fastapi import FastAPI
app = FastAPI(title="Test API")
@app.get("/items/")
async def read_items():
return [{"item_id": "foo"}]app = FastAPI(docs_url=None)
@app.get("/users")
async def get_users():
return [{"name": "Alice"}]Pass the test and this pattern moves unknown