Registry / web-framework / fastapi-filter

fastapi-filter

JSON →
library3.0.0pypypi✓ verified 91d ago

fastapi-filter is a FastAPI extension that provides a flexible way to add filtering capabilities to your API endpoints. It integrates seamlessly with popular ORMs/ODMs like SQLAlchemy, MongoEngine, and Beanie. The current version is 2.0.1 and it maintains an active release cadence, frequently updating to support the latest versions of FastAPI, Pydantic, and its database backend dependencies.

pip install fastapi-filter
INSTALL
IMPORT
SIG · FASTAPI-FILTER
F
fastapi-filter
web-frameworkpythonv3.0.0
Install
4.9s avg
Import
1242ms
Disk
55MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v3.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.980 runs
installs and imports cleanly · install 0.0s · import 1.289s · 56.5MB
glibc
py 3.10–3.980 runs
installs and imports cleanly · install 4.9s · import 1.195s · 54MB
55MB installed
● package 55MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

FilterDepends
✓ from fastapi_filter import FilterDepends
Filter (for SQLAlchemy)
✓ from fastapi_filter.contrib.sqlalchemy import Filter
✗ from fastapi_filter import Filter
The base `Filter` class must be imported from the specific backend contrib module (e.g., `sqlalchemy`, `mongoengine`, `beanie`), not directly from `fastapi_filter`.
Filter (for MongoEngine)
✓ from fastapi_filter.contrib.mongoengine import Filter
✗ from fastapi_filter import Filter
The base `Filter` class must be imported from the specific backend contrib module (e.g., `sqlalchemy`, `mongoengine`, `beanie`), not directly from `fastapi_filter`.
Filter (for Beanie)
✓ from fastapi_filter.contrib.beanie import Filter
✗ from fastapi_filter import Filter
The base `Filter` class must be imported from the specific backend contrib module (e.g., `sqlalchemy`, `mongoengine`, `beanie`), not directly from `fastapi_filter`.

This quickstart demonstrates how to set up `fastapi-filter` with SQLAlchemy. It defines an `Item` model, an `ItemFilter` schema using `FilterDepends`, and an endpoint that applies the filters to database queries. Remember to install `fastapi-filter[sqlalchemy]` and other necessary dependencies.

from fastapi import FastAPI, Depends from typing import Optional from pydantic import Field from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import declarative_base, sessionmaker, Session from fastapi_filter.contrib.sqlalchemy import Filter, FilterDepends # 1. Database setup (in-memory SQLite for example) SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() class Item(Base): __tablename__ = "items" id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) description = Column(String) Base.metadata.create_all(bind=engine) # Dependency to get DB session def get_db(): db = SessionLocal() try: yield db finally: db.close() # 2. Define your Filter schema class ItemFilter(Filter): name: Optional[str] = Field(None, description="Filter by item name") id__gt: Optional[int] = Field(None, alias="id_gt", description="Filter by ID greater than") class Constants(Filter.Constants): model = Item # Associate filter with your SQLAlchemy model search_field_name = "name" # Example search field # 3. FastAPI application app = FastAPI() @app.on_event("startup") async def startup_event(): db = SessionLocal() # Populate data if empty for demonstration if not db.query(Item).first(): db.add(Item(name="First Item", description="Description of first item")) db.add(Item(name="Second Item", description="Description of second item")) db.commit() db.close() @app.get("/items/") async def read_items( item_filter: ItemFilter = FilterDepends(ItemFilter), db: Session = Depends(get_db) ): query = item_filter.filter(db.query(Item)) items = query.all() return items # To run this example: # 1. pip install fastapi uvicorn sqlalchemy fastapi-filter[sqlalchemy] # 2. Save the code as main.py # 3. Run from your terminal: uvicorn main:app --reload # 4. Access in browser/curl: # http://127.0.0.1:8000/items/ # http://127.0.0.1:8000/items/?name=First%20Item # http://127.0.0.1:8000/items/?id_gt=1
Debug
Known issues
breakingPython 3.8 support was dropped in `v2.0.0`.
fix
Upgrade your Python environment to 3.9 or higher. If you must use Python 3.8, pin `fastapi-filter` to `<2.0.0` (e.g., `~1.1`).
affects: >=2.0.0
breaking`fastapi-filter` `v1.0.0` introduced breaking changes to support FastAPI >= 0.100.0 and Pydantic >= 2.0.0.
fix
Ensure your FastAPI and Pydantic versions are up-to-date. Review the `fastapi-filter` examples for updated filter syntax, especially regarding Pydantic V2 changes (e.g., `FieldValidationInfo` deprecation warnings were fixed in v1.1.0).
affects: >=1.0.0
breakingThe behavior of `like` and `ilike` operators changed in `v0.6.0`. The wildcard character (`%`) is no longer automatically added by the filter.
fix
You must now explicitly include the wildcard character (`%` or its URL-encoded equivalent `%25`) in your query parameters. For example, instead of `/items?name__like=test`, use `/items?name__like=%25test%25`.
affects: >=0.6.0
gotchaFilter `Constants` class requires the `model` attribute to be set to your ORM/ODM model.
fix
Always define an inner `Constants` class within your `Filter` schema and set `model = YourORMModel` (e.g., `class Constants(Filter.Constants): model = Item`).
affects: All versions
Errors
Common errors & fixes
RuntimeError: 'MyFilterSchema' does not have a `model` defined in its `Constants` inner class.
The `model` attribute in your `Filter.Constants` inner class is either missing or incorrectly referencing your ORM/ODM model.
fix
Ensure your filter schema has `class Constants(Filter.Constants): model = YourORMModel` where `YourORMModel` is your SQLAlchemy, MongoEngine, or Beanie model.
ModuleNotFoundError: No module named 'fastapi_filter.contrib.sqlalchemy' (or .mongoengine, .beanie)
You are trying to import a backend-specific `Filter` class, but the corresponding extra dependency for that backend was not installed.
fix
Install the required extra: `pip install fastapi-filter[sqlalchemy]` (or `[mongoengine]`, `[beanie]`) depending on the backend you intend to use.
Filter with `like` or `ilike` operators returns no results or unexpected results when using `fastapi-filter` v0.6.0 or later.
Since version 0.6.0, `fastapi-filter` no longer automatically adds the `%` wildcard character to `like` and `ilike` queries.
fix
Manually add the wildcard character to your query string parameters. For example, for a filter `name__like='test'`, your query parameter should be `?name__like=%25test%25` (URL-encoded `%test%`).
Upgrade
Version history
3.0.0latest on PyPI · released Jun 3, 2026
Audit
Dependencies
fastapirequiredRequired for FastAPI application integration.
pydanticrequiredRequired for defining filter schemas and data validation.
sqlalchemyoptionalOptional, for SQLAlchemy ORM integration.
mongoengineoptionalOptional, for MongoEngine ODM integration.
beanieoptionalOptional, for Beanie ODM integration.
Agent activity
11 hits · last 30 days
node
10
Resources
fastapi-filter — pip install fastapi-filter · libregistry