How to hide input param in FastApi?

Viewed 2548

How to hide the request param in OpenApi? I would like to hide user_agent from OpenApi UI.

I have a simple app:

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}
2 Answers

You can customize OpenAPI schema for hiding arbitrary parameters. The example below hidesparamB:

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
Related