🍐Unit 9: Query Parameters and Validations
Introduction
In FastAPI, query parameters and string validations are powerful features that allow developers to specify the type of data expected from the client in the URL's query string. FastAPI automatically handles validation, serialization, and documentation for these parameters.
Query Parameters
Query parameters are the key-value pairs appended to the URL after the ?
symbol. In FastAPI, you define these parameters as function arguments in your path operation function. FastAPI automatically interprets them as query parameters.
Let's take a quick look of using query parameter in FastAPI:
The read_items
function can be accessible at http://127.0.0.1:8000/items/?q=update-items
where update-item
is value of q
(query) parameter.
Additional validation
We're going to update the above program to validate the length of the given q
parameter doesn't exceed 50 characters. To achieve this, we import:
Query
fromfastapi
Annotated
fromtyping
(or fromtyping_extensions
in Python below 3.9)
The statement q: Annotated[str | None, Query(max_length=50)] = None
can be broken into three steps:
Define the type hint as
q: str | None
Wrap the type hint with
Annotated
, so it becomesAnnotated[str | None]
Add
Query
toAnnotated
in theq
parameter, it finally becomesq: Annotated[str | None, Query(max_length=50)] = None
Both of step (1) and (2) mean the same thing, q
is a parameter that can be a str
or None
, and by default, it is None
.
With the validation we just defined above, FastAPI can now:
Validate the data making sure that the max length is 50 characters
Show a clear error for the client when the data is not valid
Document the parameter in the OpenAPI schema path operation
In the above, if the given q
parameter exceeds 50 characters, FastAPI will response an error like this:
Add more validations
For example, we can add min_length
to the Query
, as follows:
Using regular expression
We can also take advantage of regular expression to validate given query parameters.
A regular expression (ReGex) is a sequence of characters that forms a search pattern, primarily used for string searching and manipulation. It can be used to find, match, or replace text in strings. Regular expressions provide a concise and flexible means to "match" (specify and recognize) strings of text, such as particular characters, words, or patterns of characters. They are commonly used in text processing and data validation tasks, allowing complex criteria for string matching to be defined with a short and expressive syntax.
This specific regular expression pattern checks that the received parameter value:
^
starts with the following characters, doesn't have any characters beforeFixedQuery
has the exact valueFixedQuery
(case-sensitive)$
ends there, doesn't have any more characters afterFixedQuery
If a request q
doesn't pass the regular expression validation, such as q=fixedquery
, FastAPI will response an error like this:
Default value
Instead of using None
default value, you can use another value as a default value by changing the None
value in the parameter definition statement, as follows:
Query parameter as a list
You can obtain multiple values for a given q
parameter by defining it as a list
, as follows:
Then, the API endpoint is:
And the reponse will be:
Exclude from the generated OpenAPI schema
To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter include_in_schema
of Query
to False
:
Summary
FastAPI's query parameters and string validations are integral features that simplify the development of robust and well-documented APIs. By leveraging type annotations and FastAPI's Query class, you can easily validate incoming data, enforce business rules, and automatically generate OpenAPI documentation for your endpoints.
Last updated