FastAPI - @Schema(hidden=True) 在尝试隐藏 swagger 文档上的架构部分时不起作用

问题描述 投票:0回答:5

我试图隐藏 FastAPI 生成的 swagger 文档的整个模式部分。我已经检查了文档并尝试了这个,但架构部分仍然显示。

    @Schema(hidden=True)
    class theSchema(BaseModel):
        category: str

如何从返回的 swagger 文档中省略一个特定架构或整个架构部分。

docExpansion 似乎也不起作用。我错过了什么?

app = FastAPI(
    openapi_tags=tags_metadata,
    title="Documentation",
    description="API endpoints",
    version="0.1",
    docExpansion="None"
) 
python swagger openapi fastapi
5个回答
10
投票

swagger 有 UI 参数“defaultModelsExpandDepth”,用于控制模式部分中模型的视图。

可以在 FastApi 初始化时使用“swagger_ui_parameters”参数转发此参数。

app = FastAPI(swagger_ui_parameters={"defaultModelsExpandDepth": -1})

价值观:

  • -1:模式部分隐藏
  • 0:架构部分已关闭
  • 1:架构部分已打开(默认)

更多选项可以在这里找到:https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/


9
投票

将参数中的

include_in_schema=False
设置为
FastAPI
实例装饰器

app = FastAPI(...)

@app.get("/", include_in_schema=False)
async def root():
    ...

0
投票

不确定我是否能回答自己的问题,但如果有人想知道,这是通过将 swagger 页面加载到 iframe 中然后使用 js 隐藏该文档的 iframe 中所需的元素来解决的。


0
投票

我有类似的要求,我也想排除某些模式,包括“Enum”模式。我能够做到这一点的唯一方法是生成自定义 OpenAPI 架构,如 FastAPI 文档中所述。

首先,使用“schema_extra”pydantic 模型配置在生成的 json 中添加隐藏字段。这可以在 pydantic 的文档中找到。

class ModelA(BaseModel):
    Field1: int | None = None
    Field2: str | None = None


class Config:
    schema_extra = {"hidden": True}

然后您可以使用生成自定义 OpenAPI 架构,

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="My app",
        version="1.0",
        description="My app's description",
        routes=app.routes,
    )
    if "components" in openapi_schema:
        # I used jsonref to dereference related schemas
        # You will need to install jsonref
        dereferenced_schema = jsonref.loads(json.dumps(openapi_schema), lazy_load=False)
        openapi_schema["components"] = jsonable_encoder(dereferenced_schema["components"])
        for schema_name in openapi_schema["components"]["schemas"].copy().keys():
            schema = openapi_schema["components"]["schemas"][schema_name]
            if "enum" in schema:
                print(f"Removing {schema_name} as it is an enum")
                del openapi_schema["components"]["schemas"][schema_name]
                continue

            hide = schema.get("hidden", False)
            if hide:
                print(f"Removing {schema_name} as it is hidden")
                del openapi_schema["components"]["schemas"][schema_name]
                continue

    app.openapi_schema = openapi_schema
    return app.openapi_schema

最后,将此自定义函数分配给 FastAPI 应用程序的 openapi 函数 -

app.openapi = custom_openapi

希望这有帮助。


0
投票

@Ankit Jain:感谢您的帖子。这是一个完美的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.