d33tah
d33tah

Reputation: 11561

How to add documentation for required query parameters?

I'm trying to create a fastapi API endpoint that relies on HTTP GET parameters, has them documented and uses fastapi's validation capabilities. Consider the following minimal example:

import fastapi

app = fastapi.FastAPI(
)

@app.get("/endpoint")
def example_endpoint(
    par1: int = fastapi.Query(
        None,
        description="example documentation1",
    ),

    par2: int = fastapi.Query(
        None,
        description="example documentation2",
    ),
):
    return {"test": par1 + par2}

This has the documentation support and works over HTTP GET parameters, but doesn't validate them - http://localhost:8000/endpoint?par1=2&par2=3 works fine, but http://localhost:8000/endpoint crashes with an internal server error, instead of notifying the user that a parameter was expected. Is there a way to make par1 and par2 required and keep the documentation feature?

Upvotes: 6

Views: 2121

Answers (1)

Yagiz Degirmenci
Yagiz Degirmenci

Reputation: 20618

You can use Ellipsis, If you hadn't seen that ... before: it is a special single value that makes query required

from fastapi import Query

Query(...,description="example documentation1")

So in your case answer below can do the job

@app.get("/endpoint")
def example_endpoint(
    par1: int = fastapi.Query(..., description="example documentation1",),
    par2: int = fastapi.Query(..., description="example documentation2",),
):

    if par1 and par2:
        return {"test": par1 + par2}

    raise ValueError("Missing query parameters")

Also you can use example=1

Query(..., description="example documentation2", example=1)

Upvotes: 11

Related Questions