{"id":8149,"library":"fastapi-filter","title":"FastAPI Filter","description":"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.","status":"active","version":"2.0.1","language":"en","source_language":"en","source_url":"https://github.com/arthurio/fastapi-filter","tags":["fastapi","filter","query","database","orm","odm","sqlalchemy","mongoengine","beanie"],"install":[{"cmd":"pip install fastapi-filter","lang":"bash","label":"Core library"},{"cmd":"pip install fastapi-filter[sqlalchemy]","lang":"bash","label":"For SQLAlchemy support"},{"cmd":"pip install fastapi-filter[mongoengine]","lang":"bash","label":"For MongoEngine support"},{"cmd":"pip install fastapi-filter[beanie]","lang":"bash","label":"For Beanie support"}],"dependencies":[{"reason":"Required for FastAPI application integration.","package":"fastapi"},{"reason":"Required for defining filter schemas and data validation.","package":"pydantic"},{"reason":"Optional, for SQLAlchemy ORM integration.","package":"sqlalchemy","optional":true},{"reason":"Optional, for MongoEngine ODM integration.","package":"mongoengine","optional":true},{"reason":"Optional, for Beanie ODM integration.","package":"beanie","optional":true}],"imports":[{"symbol":"FilterDepends","correct":"from fastapi_filter import FilterDepends"},{"note":"The base `Filter` class must be imported from the specific backend contrib module (e.g., `sqlalchemy`, `mongoengine`, `beanie`), not directly from `fastapi_filter`.","wrong":"from fastapi_filter import Filter","symbol":"Filter (for SQLAlchemy)","correct":"from fastapi_filter.contrib.sqlalchemy import Filter"},{"note":"The base `Filter` class must be imported from the specific backend contrib module (e.g., `sqlalchemy`, `mongoengine`, `beanie`), not directly from `fastapi_filter`.","wrong":"from fastapi_filter import Filter","symbol":"Filter (for MongoEngine)","correct":"from fastapi_filter.contrib.mongoengine import Filter"},{"note":"The base `Filter` class must be imported from the specific backend contrib module (e.g., `sqlalchemy`, `mongoengine`, `beanie`), not directly from `fastapi_filter`.","wrong":"from fastapi_filter import Filter","symbol":"Filter (for Beanie)","correct":"from fastapi_filter.contrib.beanie import Filter"}],"quickstart":{"code":"from fastapi import FastAPI, Depends\nfrom typing import Optional\nfrom pydantic import Field\nfrom sqlalchemy import create_engine, Column, Integer, String\nfrom sqlalchemy.orm import declarative_base, sessionmaker, Session\nfrom fastapi_filter.contrib.sqlalchemy import Filter, FilterDepends\n\n# 1. Database setup (in-memory SQLite for example)\nSQLALCHEMY_DATABASE_URL = \"sqlite:///./sql_app.db\"\nengine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={\"check_same_thread\": False})\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\nBase = declarative_base()\n\nclass Item(Base):\n    __tablename__ = \"items\"\n    id = Column(Integer, primary_key=True, index=True)\n    name = Column(String, index=True)\n    description = Column(String)\n\nBase.metadata.create_all(bind=engine)\n\n# Dependency to get DB session\ndef get_db():\n    db = SessionLocal()\n    try:\n        yield db\n    finally:\n        db.close()\n\n# 2. Define your Filter schema\nclass ItemFilter(Filter):\n    name: Optional[str] = Field(None, description=\"Filter by item name\")\n    id__gt: Optional[int] = Field(None, alias=\"id_gt\", description=\"Filter by ID greater than\")\n    \n    class Constants(Filter.Constants):\n        model = Item # Associate filter with your SQLAlchemy model\n        search_field_name = \"name\" # Example search field\n\n# 3. FastAPI application\napp = FastAPI()\n\n@app.on_event(\"startup\")\nasync def startup_event():\n    db = SessionLocal()\n    # Populate data if empty for demonstration\n    if not db.query(Item).first():\n        db.add(Item(name=\"First Item\", description=\"Description of first item\"))\n        db.add(Item(name=\"Second Item\", description=\"Description of second item\"))\n        db.commit()\n    db.close()\n\n@app.get(\"/items/\")\nasync def read_items(\n    item_filter: ItemFilter = FilterDepends(ItemFilter),\n    db: Session = Depends(get_db)\n):\n    query = item_filter.filter(db.query(Item))\n    items = query.all()\n    return items\n\n# To run this example:\n# 1. pip install fastapi uvicorn sqlalchemy fastapi-filter[sqlalchemy]\n# 2. Save the code as main.py\n# 3. Run from your terminal: uvicorn main:app --reload\n# 4. Access in browser/curl:\n#    http://127.0.0.1:8000/items/\n#    http://127.0.0.1:8000/items/?name=First%20Item\n#    http://127.0.0.1:8000/items/?id_gt=1","lang":"python","description":"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."},"warnings":[{"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`).","message":"Python 3.8 support was dropped in `v2.0.0`.","severity":"breaking","affected_versions":">=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).","message":"`fastapi-filter` `v1.0.0` introduced breaking changes to support FastAPI >= 0.100.0 and Pydantic >= 2.0.0.","severity":"breaking","affected_versions":">=1.0.0"},{"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`.","message":"The behavior of `like` and `ilike` operators changed in `v0.6.0`. The wildcard character (`%`) is no longer automatically added by the filter.","severity":"breaking","affected_versions":">=0.6.0"},{"fix":"Always define an inner `Constants` class within your `Filter` schema and set `model = YourORMModel` (e.g., `class Constants(Filter.Constants): model = Item`).","message":"Filter `Constants` class requires the `model` attribute to be set to your ORM/ODM model.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure your filter schema has `class Constants(Filter.Constants): model = YourORMModel` where `YourORMModel` is your SQLAlchemy, MongoEngine, or Beanie model.","cause":"The `model` attribute in your `Filter.Constants` inner class is either missing or incorrectly referencing your ORM/ODM model.","error":"RuntimeError: 'MyFilterSchema' does not have a `model` defined in its `Constants` inner class."},{"fix":"Install the required extra: `pip install fastapi-filter[sqlalchemy]` (or `[mongoengine]`, `[beanie]`) depending on the backend you intend to use.","cause":"You are trying to import a backend-specific `Filter` class, but the corresponding extra dependency for that backend was not installed.","error":"ModuleNotFoundError: No module named 'fastapi_filter.contrib.sqlalchemy' (or .mongoengine, .beanie)"},{"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%`).","cause":"Since version 0.6.0, `fastapi-filter` no longer automatically adds the `%` wildcard character to `like` and `ilike` queries.","error":"Filter with `like` or `ilike` operators returns no results or unexpected results when using `fastapi-filter` v0.6.0 or later."}]}