Search code examples
pythonfastapioptional-parameters

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}

Solution

  • 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.