Full answer
Naively interpolating order_by(text(sort)) lets clients inject SQL or sort by columns that are unindexed, private (password_hash) or expensive.
Design:
- Define the public contract:
sortfieldsname,score,joined, with-prefix for descending and comma-separated for multiple keys. Default sort is deterministic (includeidas a tie-breaker, otherwise paginated results can repeat or skip rows). - Map public names to column objects:
SORTABLE = {"name": Student.name, "score": Student.score}. - A dependency parses and validates:
def sort_params(sort: Annotated[str, Query(pattern=r"^-?\w+(,-?\w+)*$", max_length=50)] = "name") -> list[ColumnElement]:
clauses = []
for part in sort.split(","):
desc = part.startswith("-")
name = part.lstrip("-")
if name not in SORTABLE:
raise HTTPException(422, f"Cannot sort by {name!r}. Allowed: {sorted(SORTABLE)}")
clauses.append(SORTABLE[name].desc() if desc else SORTABLE[name].asc())
return clauses- The endpoint applies
select(Student).order_by(*clauses, Student.id).
Filters: group them in a Pydantic model used as Annotated[StudentFilters, Query()] (FastAPI 0.115+) with typed fields (min_score: int | None, grade: Literal["A", "B", "C"] | None, name_contains: str | None) and apply each non-None field as a condition. extra="forbid" on the model rejects unknown parameters, but it applies to every query parameter of that endpoint, so sort and pagination must then be fields of the same model; without it, unknown parameters are silently ignored.
Performance and safety:
- Sortable and filterable columns should be indexed (composite indexes for common combinations), or the database sorts large tables on every request.
- Cap page size and total number of sort keys.
- Escape LIKE wildcards in user text (
%and_) if you buildilikepatterns. - Document allowed fields in the parameter description or as an enum for clients.
- Use keyset pagination with the same sort keys for large tables.
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel
from sqlalchemy import ColumnElement, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase):
pass
class Student(Base):
__tablename__ = "student"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
score: Mapped[int]
password_hash: Mapped[str] = mapped_column(default="x")
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
with Session(engine) as s:
s.add_all([Student(name=n, score=v) for n, v in [("Asha", 91), ("Ravi", 58), ("Kiran", 74), ("Meera", 74)]])
s.commit()
SORTABLE = {"name": Student.name, "score": Student.score}
app = FastAPI()
def sort_params(sort: Annotated[str, Query(pattern=r"^-?\w+(,-?\w+)*$", max_length=50)] = "name") -> list[ColumnElement]:
clauses = []
for part in sort.split(","):
name = part.lstrip("-")
if name not in SORTABLE:
raise HTTPException(status_code=422, detail=f"Cannot sort by {name!r}. Allowed: {sorted(SORTABLE)}")
clauses.append(SORTABLE[name].desc() if part.startswith("-") else SORTABLE[name].asc())
return clauses
class Filters(BaseModel):
min_score: int | None = None
name_contains: str | None = None
@app.get("/students")
def students(order: Annotated[list[ColumnElement], Depends(sort_params)], f: Annotated[Filters, Query()]):
stmt = select(Student.name, Student.score)
if f.min_score is not None:
stmt = stmt.where(Student.score >= f.min_score)
if f.name_contains:
escaped = f.name_contains.replace("%", r"\%").replace("_", r"\_")
stmt = stmt.where(Student.name.ilike(f"%{escaped}%", escape="\\"))
with Session(engine) as db:
return [{"name": n, "score": v} for n, v in db.execute(stmt.order_by(*order, Student.id))]
c = TestClient(app)
print(c.get("/students?sort=-score,name").json())
print(c.get("/students?sort=name&min_score=70&name_contains=ra").json())
print(c.get("/students?sort=password_hash").status_code, c.get("/students?sort=name;DROP TABLE student").status_code)
print(c.get("/students?min_score=1&bogus=1").status_code, "(unknown filters are ignored unless the model forbids extras)")
print(c.get("/students?min_score=abc").json()["detail"][0]["type"])
Standalone script. Run it with `python file.py`; it uses an in-memory SQLite database and TestClient. Grouping query parameters in a Pydantic model needs FastAPI 0.115 or later. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): [{'name': 'Asha', 'score': 91}, {'name': 'Kiran', 'score': 74}, {'name': 'Meera', 'score': 74}, {'name': 'Ravi', 'score': 58}] [{'name': 'Kiran', 'score': 74}, {'name': 'Meera', 'score': 74}] 422 422 200 (unknown filters are ignored unless the model forbids extras) int_parsing
Key points
- Whitelist maps public names to real column objects
- Never pass user strings to order_by(text(...))
- Add id as a tie-breaker for stable pagination
- Group filters in a typed Pydantic query model
- Index sortable columns; cap page and key counts
Common mistakes
- Passing user strings into order_by(text(...))
- Allowing sort by unindexed or private columns
- Omitting a unique tie-breaker so pages repeat or skip rows
- Not escaping LIKE wildcards in user search text
- Unbounded numbers of sort keys or page sizes
Follow-ups
- How would you combine this with keyset pagination?
- How do you expose allowed sort fields in OpenAPI?
- How would you filter on related tables safely?
Tips
- Describe the whitelist mapping
- Mention the tie-breaker
- Say index the sort columns