Dynamic Filtering and Sorting Parameters
Build reusable query-parameter models for filtering, sorting, and field selection with validation.
Why Dynamic Query Parameters?
Real-world list endpoints rarely return everything. Clients want to filter (only active users), sort (newest first), and select fields (just id and name). Hardcoding every combination explodes your route count.
The clean approach is to model these query parameters as reusable, validated objects that you inject into many endpoints. In this lesson we build:
- A filter model that turns query params into safe constraints
- A sort parser with an allow-list of fields and directions
- A field selection mechanism to trim response payloads
Everything is driven by FastAPI dependencies so it stays DRY and testable.
Collecting Filters with a Dependency Class
A class with __init__ taking Query parameters becomes a reusable dependency. FastAPI reads each parameter from the URL and documents it in OpenAPI automatically.
Use Optional[...] = None so filters are opt-in: a missing param means "don't filter on this column".
from typing import Optional
from fastapi import Query
class UserFilterParams:
def __init__(
self,
status: Optional[str] = Query(None, description="active | inactive"),
min_age: Optional[int] = Query(None, ge=0, le=150),
search: Optional[str] = Query(None, min_length=2, max_length=50),
):
self.status = status
self.min_age = min_age
self.search = search
# Usage:
# @app.get('/users')
# def list_users(filters: UserFilterParams = Depends()):
# ...All lessons in this course
- URL, Header and Media-Type Versioning
- Cursor vs Offset Pagination at Scale
- Dynamic Filtering and Sorting Parameters
- Designing Stable Response Envelopes