Query parameters are optional or required key-value pairs appended to the end of a URL
/items?skip=0typically used for filtering, sorting or pagination.In FastAPI, any function parameter that is not declared inside the URL path is automatically treated as a query parameter and we validate them using Python type hints alongside the Query() function or Pydantic models.
# Basic Query Parameters (Required, Optional and Default)
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(
category: str, # Required (no default value)
skip: int = 0, # Optional with a default value
search: str | None = None # Optional, defaults to None
):
return {"category": category, "skip": skip, "search": search}
# Adding Validation Rules with Query()
# To enforce constraints beyond basic data types—such as string length, regex patterns, or numeric limits.
from typing import Annotated
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/products/")
async def search_products(
q: Annotated[str | None, Query(min_length=3, max_length=50] = None,
limit: Annotated[int, Query(gt=0, le=100)] = 20,
tags: Annotated[list[str] | None, Query()] = None
):
return {"q": q, "limit": limit, "tags": tags}
# String Constraints. Parameters like min_length, max_length, and pattern (regex) restrict what text is allowed.
# Numeric Constraints. Rules like gt (greater than), ge (greater than or equal), lt (less than), and le (less than or equal) restrict number ranges.
# Multiple Values (Lists). Typing a parameter as list[str] with Query() lets clients pass repeated keys in the URL, such as /products/?tags=sale&tags=new.# Grouping Query Parameters with a Pydantic Model
# When an endpoint has many related filter or pagination parameters, you can group them into a reusable Pydantic BaseModel using Query()
from typing import Annotated, Literal
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
app = FastAPI()
class FilterParams(BaseModel):
limit: int = Field(10, gt=0, le=100)
offset: int = Field(0, ge=0)
order_by: Literal["created_at", "updated_at"] = "created_at"
@app.get("/articles/")
async def get_articles(filter_query: Annotated[FilterParams, Query()]):
return filter_query