6

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?

1 Answer 1

11

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)
Sign up to request clarification or add additional context in comments.

3 Comments

What is the example=1 in Query(...) ?
It's a great question. Simply it adds example value like default, that query will be 1 if it's empty, kinda like when you open the Body of an POST endpoint there will be the same example values by default, for str there will be "string", for int there will be 0 etc.
But it's just an example when you send a request to the /endpoint without any query parameter's you 'll be still getting an error {"detail":[{"loc":["query","par1"],"msg":"field required","type":"value_error.missing"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.