有没有办法从 FastAPI 的自动生成文档中排除 Pydantic 模型?

Is there a way to exclude Pydantic models from FastAPI's auto-generated documentation?

有没有办法让 FastAPI 应用程序不在其架构文档中显示模型?我有一些模型与其他模型略有不同,并且每个模型都会出现这种重复,模式文档非常混乱。

from pydantic import BaseModel
class A(BaseModel):
    name: str

class HasID(BaseModel):
    id_: int

class AWithID(A, HasID):
    pass

有什么方法可以不在文档中显示classAWithID吗?

这并不优雅,但您可以手动修改 auto-generated OpenAPI 架构。

请参阅 FastAPI 文档的 Extending OpenAPI 部分。

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.

根据 get_openapi() 的输出,所有模型都在 components > schemas 下定义,其中每个模型的名称都是字典键。

{
    "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": {...}
            },
            ...
        }
    }
}

因此,您可以 pop 关闭要隐藏的模型:

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