Understand optional query parameters in FastAPI

David Y.

The Problem

FastAPI allows developers to set default values for query parameters. It also allows parameters to be declared as optional. But what is the difference between an optional parameter and a parameter that has None as its default value? Consider the following code:

@app.get("/example-route/") async def example_route(p1: str = None, p2: str | None = None): return {"p1": p1, "p2": p2}

What is the difference between p1 and p2? Is one preferable to the other?

The Solution

The only difference between p1 and p2 is that the latter uses a more complex type hint. Type hints are an optional Python syntax feature that can be used to indicate what data type a given function parameter expects. Python is a dynamically typed language, so these type hints are not enforced as they might be in a statically typed language like C or Java – they merely act as a guide for developers and an aid for tooling such as auto-completion in code editors.

In the code above, we can see that p1 is expected to be a string (str), whereas p2 is expected to be either a string or None. However, because Python does not enforce type hints, we can set p1 to None, which is not a value of type str. We can also set p2 to None, but its type hint includes this possibility, making it the more accurate of the two. This could be useful for editors and other tooling that interacts with our code, as well as for other developers. Therefore, this approach is preferable in most circumstances, but not strictly necessary for our code to function.

Note that the type hint str | None can also be written as Optional[None] or Union[str, None] if these classes are imported from the built-in typing module.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.