'Is there a way to exclude Pydantic models from FastAPI's auto-generated documentation?
Is there a way for a FastAPI application to not display a model in its schema documentation? I have some models which are slight variations of others, and with this duplication occurring for each model, the schema documentation is quite cluttered.
from pydantic import BaseModel
class A(BaseModel):
name: str
class HasID(BaseModel):
id_: int
class AWithID(A, HasID):
pass
Is there some way not to display class AWithID
in the documentation?
Solution 1:[1]
It's not elegant, but you can manually modify the auto-generated OpenAPI schema.
See the Extending OpenAPI section of the FastAPI docs.
A
FastAPI
application (instance) has an.openapi()
method that is expected to return the OpenAPI schema.As part of the application object creation, a path operation for
/openapi.json
(or for whatever you set your openapi_url) is registered.It just returns a JSON response with the result of the application's
.openapi()
method.By default, what the method
.openapi()
does is check the property.openapi_schema
to see if it has contents and return them.If it doesn't, it generates them using the utility function at
fastapi.openapi.utils.get_openapi
.
From the output of get_openapi()
, all the models are defined under components
> schemas
, where each model's name is the dictionary key.
{
"openapi": "3.0.2",
"info": {...},
"paths": {...},
"components": {
"schemas": {
"A": {
"title": "A",
"required": [...],
"type": "object",
"properties": {...}
},
"AWithID": {
"title": "AWithID",
"required": [...],
"type": "object",
"properties": {...}
},
"HasID": {
"title": "HasID",
"required": [...],
"type": "object",
"properties": {...}
},
...
}
}
}
So, you can just pop
off the models you want to hide:
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
app = FastAPI()
# Define routes before customizing the OpenAPI schema
# ...
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(title="My App", version="1.0.0", routes=app.routes)
openapi_schema["components"]["schemas"].pop("AWithID", None)
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |