FastAPI by Example: Query Parameter Models
Query parameters are the key-value pairs that appear after the `?` in a URL. This code example shows how to define optional and required query parameters with default values.
Code
from fastapi import FastAPI, Query
from typing import List, Union
app = FastAPI()
@app.get("/items/")
async def read_items(
q: Union[str, None] = Query(
default=None,
min_length=3,
max_length=50,
description="Search query string"
),
skip: int = 0,
limit: int = 10,
tags: List[str] = Query(default=[])
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
# URL Examples:
# /items/
# /items/?q=python&limit=5
# /items/?tags=a&tags=bExplanation
Query parameters are defined as function arguments that are not part of the path operation's route path. FastAPI automatically distinguishes these from path parameters and uses Python type hints to validate the incoming data. When a client sends a request, the framework parses the query string and converts values to the specified types, such as integers or booleans. If a parameter is declared with a default value, it becomes optional, whereas parameters without defaults are treated as required.
The Query class provides a mechanism to enforce additional validation rules on these parameters. Developers can specify constraints like minimum and maximum string lengths, or use regular expressions to validate the format of the input. This validation occurs before the request reaches the business logic, ensuring that the application only processes data that meets the defined criteria.
Handling lists of query parameters is supported by defining the parameter type as a list. This allows clients to pass multiple values for the same key, which FastAPI aggregates into a Python list. This feature is particularly useful for filtering or tagging systems where a resource might be associated with multiple attributes.
Code Breakdown
Union[str, None] = None declares an optional parameter that defaults to None.min_length=3 enforces that the query string must be at least 3 characters long.List[str] collects multiple values for the same key into a single list.if q: checks if the optional parameter was provided before using it.
