Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional query parameters in FastAPI

I don't understand optional query parameters in FastAPI. How is it different from default query parameters with a default value of None?

What is the difference between arg1 and arg2 in the example below where arg2 is made an optional query parameter as described in the above link?

@app.get("/info/")
async def info(arg1: int = None, arg2: int | None = None):
    return {"arg1": arg1, "arg2": arg2}
like image 822
ksrini Avatar asked Sep 09 '25 19:09

ksrini


2 Answers

This is covered in the FastAPI reference manual, albeit just as a small note:

async def read_items(q: Optional[str] = None):

FastAPI will know that the value of q is not required because of the default value = None.

The Optional in Optional[str] is not used by FastAPI, but will allow your editor to give you better support and detect errors.

(Optional[str] is the same as str | None pre 3.10 for other readers)

Since your editor might not be aware of the context in which the parameter is populated and used by FastAPI, it might have trouble understanding the actual signature of the function when the parameter is not marked as Optional. You may or may not care about this distinction.

like image 176
MatsLindh Avatar answered Sep 12 '25 11:09

MatsLindh


In addition to the answer by @MatsLindh, you can also use the fastapi.Query class with a default parameter set.

For example:

async def get_companies(company_id: int = Query(default=None, alias="id"), limit: int = Query(default=15), page: int = Query(default=1)):

defines a function get_companies, with an optional company_id (parsed in the request arguments as id), an optional limit, as well as an optional page. To mark the argument as required, you can remove the default= param.

like image 41
9 Guy Avatar answered Sep 12 '25 10:09

9 Guy