Jared DuPont
Jared DuPont

Reputation: 147

Override the automatically generated parameters in FastAPI

I am writing FastAPI program that is just a bunch of @app.get endpoints for querying data. There are many, many different query arguments they could use that are automatically generated from a config file, for example the @app.get("/ADJUST_COLOR/") endpoint could look something like /ADJUST_COLOR/?RED_darker=10&BLUE_lighter=43&GREEN_inverse=true where all those parameters are generated from a list of colors and a list of operations to perform on those colors (This is only an example, not what I am actually doing).
The way I am doing that is to take in the request object like this:

@app.get("/ADJUST_COLOR/")
def query_COLORS( request: Request ):
    return look_through_parameters(request.query_params) 

But the problem is that the automatically generated swagger UI does not show any useful data:

Since I am parsing the request manually there are no parameters generated. But since I have a full list of the parameters I am expecting then I should be able to generate my own documentation and have the UI show it.

I have looked through these two documents: https://fastapi.tiangolo.com/tutorial/path-operation-configuration/
And https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/

But I was not able to figure out if it was possible or not

Upvotes: 2

Views: 2335

Answers (1)

Ben
Ben

Reputation: 2057

You can define custom api schema in your route via openapi_extra (this is a recent feature of FastAPI, 0.68 will work but I'm not sure the exact earliest version that supports this):

@app.get("/ADJUST_COLOR/", openapi_extra={
    "parameters": [
        {
            "in": "query",
            "name": "RED_darker",
            "schema": {
                "type": "integer"
            },
            "description": "The level of RED_darker"
        },
        {
            "in": "query",
            "name": "BLUE_lighter",
            "schema": {
                "type": "integer"
            },
            "description": "The level of BLUE_lighter"
        },
        {
            "in": "query",
            "name": "GREEN_inverse",
            "schema": {
                "type": "boolean"
            },
            "description": "is GREEN_inverse?"
        },
    ]
})
async def query_COLORS(request: Request):
    return look_through_parameters(request.query_params)

Which is rendered like this in your api /docs: enter image description here

Upvotes: 1

Related Questions