🍋Unit 7: Query Parameters
Introduction
Query parameters are a fundamental aspect of web development, enabling the passing of optional or required information in GET requests to the server. They are appended to the URL following a ?
symbol and can be used to filter results, specify the nature of a request, or provide additional data without changing the route of the request.
Query parameters
To define query parameters in FastAPI, you simply declare them as function arguments in your path operation functions. FastAPI automatically recognizes them as query parameters if they are not part of the path parameters. This is elegantly handled with Python's type hints, allowing developers to specify the data type of each query parameter, which FastAPI uses to validate incoming requests.
To evaluate the above program, you can visit the following two URLs:
http://127.0.0.1:8000/items/
http://127.0.0.1:8000/items/?skip=0&limit=2
For the first URL, the program will automatically set skip=0
and limit=100
because we've defined these default values in the parameters of the read_item()
function. For the second URL, the result is as follows, due to the query parameters being set to skip=0
and limit=100
.
Optional parameters
FastAPI can distinguish the path parameters and query parameters in the same function, such as follows:
In the above program, q
is an optional query parameter by setting their default to None
.
Query parameter type conversion
Let's take a look at the following program:
The following URLs will result in the same output:
http://127.0.0.1:8000/items/foo?short=1
http://127.0.0.1:8000/items/foo?short=True
http://127.0.0.1:8000/items/foo?short=true
http://127.0.0.1:8000/items/foo?short=on
http://127.0.0.1:8000/items/foo?short=yes
Multiple path and query parameters
You can declare multiple path parameters and query parameters at the same time, FastAPI knows which is which.
Required query parameters
When you declare a default value for non-path parameters such as query parameters, then it is not required. If you don't want to add a specific value but just make it optional, set the default as None
. But when you want to make a query parameter required, you can just not declare any default value.
When you visit http://127.0.0.1:8000/items/foo
, you will encounter the following error due to the missing short
parameter in the URL.
API Docs
Once again, FastAPI can generate API Docs in both Swagger and ReDoc which are available at the following URLs:
Summary
Query parameters in FastAPI are a powerful and flexible way to add functionality to your API endpoints. By leveraging Python type hints and FastAPI's intuitive design, developers can easily define, validate, and document query parameters, resulting in robust, efficient, and easy-to-use APIs.
Last updated