First Steps¶
Here is a minimal example of using fastapi-filters to add filtering to a FastAPI endpoint:
from fastapi import Depends, FastAPI
from fastapi_filters import FilterField, FilterSet
app = FastAPI()
class UserFilters(FilterSet):
name: FilterField[str]
age: FilterField[int]
@app.get("/users")
async def get_users(filters: UserFilters = Depends()):
return {"filters": filters.filter_values}
Steps:
- Import
FilterSetandFilterFieldfromfastapi_filters. - Create a class that inherits from
FilterSetand declare filter fields usingFilterField[<type>]annotations. - Add the filter set as a parameter to your endpoint with
= Depends()-- FastAPI resolves it via dependency injection.
When a request is made to /users:
- Query parameters are parsed based on the declared fields and their types.
- For example,
GET /users?name[eq]=John&age[gt]=25filters by name equal to "John" and age greater than 25. - If no filter parameters are provided,
filters.filter_valuesreturns an empty dict.
How It Works¶
FilterSet integrates directly with FastAPI's dependency injection system. When you declare
filters: UserFilters as an endpoint parameter, the library:
- Generates query parameters for each field based on its type (e.g.,
strgetseq,ne,like,ilike, etc.). - Parses incoming query parameters using bracket notation:
field[operator]=value. - Builds a
FilterSetinstance with the parsed values, accessible viafilter_values.
Tip
FilterSet is the recommended way to define filters. It provides a clean, declarative syntax,
supports operator overloading for programmatic filter construction, and works seamlessly with
all database integrations.
What's Next?¶
The following pages walk through the core building blocks:
| Page | What you'll learn |
|---|---|
| FilterSet | Full FilterSet API -- inheritance, hooks, subset(), extract(), from_ops() |
| FilterField | Customizing fields -- explicit operators, aliases, internal fields, per-operator types |
| Operators | All available operators and how they are auto-generated per type |
| Programmatic Filters | Building FilterOp objects with Python operators (>, ==, >>) |
| Sorting | Adding sort support to your endpoints |
| OpenAPI Docs | Fixing Swagger UI for CSV list parameters |