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