如何在 FastApi 中隐藏输入参数?

如何在 OpenApi 中隐藏请求参数?我想从 OpenApi UI 中隐藏 user_agent。

我有一个简单的应用程序:

from typing import Optional
from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/items/")
async def read_items(
       user_agent: Optional[str] = Header(None), 
       size: Optional[int] = Body(None)):
    return {"User-Agent": user_agent}
stack overflow How to hide input param in FastApi?
原文答案

答案:

作者头像

version 0.73.0related PR )中的FastApi在本机上支持此功能: https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi

from typing import Optional

from fastapi import Body, FastAPI, Header

app = FastAPI()

@app.get("/items/")
async def read_items(
    user_agent: Optional[str] = Header(None, include_in_schema=False), 
    size: Optional[int] = Body(None)
):
    return {"User-Agent": user_agent}

[User-Agent header is excluded ](https://i.stack.imgur.com/wnqh9.png

作者头像

您可以 customize OpenAPI 模式来隐藏任意参数。下面的例子隐藏了 paramB

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

app = FastAPI()

@app.get("/")
def get_items(paramA: int, paramB: int):
    pass

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="Custom title",
        version="2.5.0",
        description="This is a very custom OpenAPI schema",
        routes=app.routes,
    )
    # Remove paramB
    params = openapi_schema["paths"]["/"]["get"]["parameters"]
    params = [param for param in params if param["name"] != "paramB"]
    openapi_schema["paths"]["/"]["get"]["parameters"] = params
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi