8

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}
Chris
  • 18,724
  • 6
  • 46
  • 80
ksrini
  • 1,412
  • 2
  • 19
  • 33
  • afaik, there is no difference between them – JPG Feb 25 '22 at 16:04
  • Please have a look at [this answer](https://stackoverflow.com/a/73261442/17865804) and [this answer](https://stackoverflow.com/a/72289969/17865804) for more details and examples. – Chris Feb 16 '23 at 06:30

4 Answers4

15

This is covered in the 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.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
0

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.

9 Guy
  • 176
  • 3
  • 14
0

Before 3.10 python, is:

from typing import Union

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

referencia https://fastapi.tiangolo.com/tutorial/query-params/#optional-parameters

Sham Fiorin
  • 403
  • 4
  • 16
-3

It depends on the way you see it, but my philosophy is:

Optional parameters are a bigger set that includes query parameters.

That is, query parameters take an input that is a value, while optional parameters are query parameters that can have no value (i.e. None).

lsabi
  • 3,641
  • 1
  • 14
  • 26