Every FastAPI project I start has the same first afternoon. A model, a create schema, an update schema, a read schema, and then five endpoints that all look alike: list, get one, create, update, delete. Add pagination, sorting and a couple of filters, and that afternoon becomes a day. That repeated day is exactly what FastCRUD sets out to remove.
It promises to turn that day into one function call, and for the most part it does. I built a small board-game catalogue with it and then poked at every endpoint it generated. The happy path works well. However, the defaults let anyone write, silently ignore filters you did not declare, return a 500 for a typo in a sort field, and let a PATCH save data your create schema would reject. Here is the app, what each of those looks like, and the small fixes I now add every time.
What FastCRUD gives you
FastCRUD is a library for FastAPI and async SQLAlchemy. Its crud_router function takes a model and your Pydantic schemas, and returns a normal FastAPI router. I used Python 3.12 with FastCRUD 0.23.0, FastAPI 0.165, SQLAlchemy 2.1 and Pydantic 2.14. First, the install:
pip install fastcrud "sqlalchemy[asyncio]" aiosqlite uvicorn
The [asyncio] extra matters. With plain sqlalchemy 2.1, my first import failed with “The SQLAlchemy asyncio module requires that the Python ‘greenlet’ library is installed”, because the async engine needs greenlet and SQLAlchemy 2.1 doesn’t install it for you.
A FastCRUD app in one file
The example is a catalogue of board games, each with an optional designer. Here are the models, with one rule that matters later: a game’s maximum player count can’t be below its minimum.
class Designer(Base):
__tablename__ = "designers"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
games: Mapped[list["Game"]] = relationship(back_populates="designer")
class Game(Base):
__tablename__ = "games"
__table_args__ = (CheckConstraint("max_players >= min_players", name="players_in_order"),)
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(100))
year: Mapped[int]
min_players: Mapped[int]
max_players: Mapped[int]
designer_id: Mapped[int | None] = mapped_column(ForeignKey("designers.id"))
designer: Mapped[Designer | None] = relationship(back_populates="games")
The schemas are ordinary Pydantic models. The create schema checks the player rule; the update schema has every field optional, because PATCH sends only what changes:
class GameCreate(BaseModel):
title: str = Field(min_length=1, max_length=100)
year: int = Field(ge=1900, le=2100)
min_players: int = Field(ge=1)
max_players: int = Field(ge=1)
designer_id: int | None = None
@model_validator(mode="after")
def players_in_order(self):
if self.max_players < self.min_players:
raise ValueError("max_players must be at least min_players")
return self
class GameUpdate(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=100)
year: int | None = Field(default=None, ge=1900, le=2100)
min_players: int | None = Field(default=None, ge=1)
max_players: int | None = Field(default=None, ge=1)
designer_id: int | None = None
class GameRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
title: str
year: int
min_players: int
max_players: int
designer_id: int | None
And then the part FastCRUD replaces, the whole set of endpoints:
app.include_router(crud_router(
session=get_session,
model=Game,
create_schema=GameCreate,
update_schema=GameUpdate,
select_schema=GameRead,
path="/games",
tags=["Games"],
filter_config=FilterConfig(title=None, title__ilike=None, year=None,
year__gte=None, designer_id=None),
))
That one call generated these routes, all visible in /docs:
POST /games
GET /games offset, limit, page, itemsPerPage, sort, title, title__ilike, year, year__gte, designer_id
GET /games/{id}
PATCH /games/{id}
DELETE /games/{id}
Sorting, paging and filters that work
I loaded six games and tried the list endpoint. Sorting takes a comma-separated list, with a minus sign for descending order. As a result, ?sort=-year,title returned Mariposas (2020), Wingspan (2019) and Azul (2017) first, exactly as expected.
Paging comes in two styles. With page and itemsPerPage you also get the metadata a front end needs:
GET /games?page=2&itemsPerPage=2
{"data": [{"id": 3, "title": "Wingspan", ...}, {"id": 4, "title": "Patchwork", ...}],
"total_count": 6, "has_more": true, "page": 2, "items_per_page": 2}
Filters use the names you declare in FilterConfig, with Django-style operators. For example, ?year__gte=2017 returned three games, and ?title__ilike=%ca% found Caverna. A request that mixes both paging styles gets a clear 400 explaining the conflict, and ?year=abc gets a normal 422. So far, so good.
FastCRUD saves the boring day. What it doesn’t do is make the decisions you would have made during that day.
Seven FastCRUD defaults I change
Then I tried the requests a real client, or a careless one, would send. Each of the following is what the app above actually returned.
1. Every write endpoint is open
Out of the box, POST, PATCH and DELETE need nothing. In my test, a plain DELETE /games/6 with no headers returned {"message": "Item deleted successfully"}. FastCRUD has a hook for this: create_deps, update_deps and delete_deps. One detail tripped me up: they take plain functions, not Depends(...). Passing [Depends(require_editor)] fails at start-up with “All dependencies must be callable”.
def require_editor(x_api_key: str | None = Header(default=None)):
if x_api_key != os.environ["EDITOR_KEY"]:
raise HTTPException(status_code=401, detail="Not allowed")
protect = dict(create_deps=[require_editor], update_deps=[require_editor],
delete_deps=[require_editor])
app.include_router(crud_router(..., **protect))
Use your real authentication here, of course, such as a JWT check. The point is that read and write access are separate settings, and the default for writes is open.
2. Filters you did not declare are silently ignored
I had declared year__gte but not year__gt. So ?year__gt=2015 returned all six games, including Agricola from 2007, with a 200 and no warning. A client who mistypes a filter gets the whole table back and may never notice. Therefore, declare every operator your clients use, and tell them which ones exist; the generated OpenAPI docs list them.
3. A limit without an offset does nothing
?limit=2 on its own returned all six rows. The limit only applies when offset is sent too, so ?offset=0&limit=2 returned two. Without either, the list endpoint falls back to 100 rows.
4. There is no cap on page size
Meanwhile, ?offset=0&limit=100000 and ?itemsPerPage=100000 were both accepted. On a large table, that is one request away from a very slow query. I added a small middleware that rejects page sizes above 100:
@app.middleware("http")
async def cap_page_size(request: Request, call_next):
for name in ("limit", "itemsPerPage"):
value = request.query_params.get(name)
if value and value.isdigit() and int(value) > 100:
return JSONResponse({"detail": f"{name} must be 100 or less"}, status_code=422)
return await call_next(request)
It only reads query parameters, so it doesn’t run into the issue I described in my post on FastAPI middleware and streaming responses.
5. A bad sort field is a 500
?sort=nope raised SQLAlchemy’s ArgumentError: Invalid sort column 'nope', and the client got a 500 Internal Server Error. That is a client mistake, so it should be a 400. One exception handler fixes it, and the message is already safe to show:
@app.exception_handler(ArgumentError)
async def bad_sort(request: Request, exc: ArgumentError):
return JSONResponse({"detail": str(exc)}, status_code=400)
6. PATCH skips the rule your create schema checks
This one surprised me most. POSTing a game with five minimum players and two maximum was rejected with a 422, as it should be. But before I added the database constraint, PATCH /games/2 with {"min_players": 9} returned 200 and saved Caverna with a minimum of 9 and a maximum of 7.
The reason is simple once you see it. The update schema only receives the fields being changed, so it cannot compare them with the values already in the database. A rule that spans fields belongs in the database. That is why the model above has a CheckConstraint. With it, the bad PATCH raised an IntegrityError, which I map to a 422 so the client knows what went wrong:
@app.exception_handler(IntegrityError)
async def broken_rule(request: Request, exc: IntegrityError):
return JSONResponse({"detail": "The change breaks a data rule: " + str(exc.orig)}, status_code=422)
PATCH /games/2 {"min_players": 9}
422 {"detail": "The change breaks a data rule: CHECK constraint failed: players_in_order"}
In a larger project, I would return a friendlier message per constraint name, rather than the raw database text.
7. Responses depend on select_schema
For the designers router, I first left out select_schema. Creating a designer then returned a 200 with a body of null, so the client had no way to learn the new ID. With select_schema set, POST returned the created row. Note that PATCH still returned null even with it, so clients should re-fetch after an update. Also, creates return 200 rather than 201, which matters if your clients check for 201.
Nesting related data with FastCRUD
FastCRUD can join related models for you with include_relationships. At first, I set include_relationships=["designer"] and nothing changed: the response had no designer at all. The join happened, but GameRead had no field to put it in. Adding one fixed it:
class GameWithDesigner(GameRead):
designer: DesignerRead | None = None
app.include_router(crud_router(..., select_schema=GameWithDesigner,
include_relationships=["designer"]))
GET /games/3
{"id": 3, "title": "Wingspan", "year": 2019, "min_players": 1, "max_players": 5,
"designer_id": 2, "designer": {"id": 2, "name": "Elizabeth Hargrave"}}
A game without a designer returned "designer": null, and the list endpoint nested designers the same way. Because the join runs in the same query, this avoids the one-query-per-row pattern I wrote about in the N+1 problem in Django. By default FastCRUD leaves out one-to-many relationships when it detects them, since those can return unbounded lists; keep that default unless you also set default_nested_limit.
Tests that keep the fixes in place
Finally, I wrote ten tests with FastAPI’s TestClient. Six check FastCRUD’s defaults, so an upgrade that changes them shows up at once. The other four check the fixes: writes need a key, a bad sort is a 400, page sizes are capped, PATCH cannot break the player rule, and the designer is nested.
def test_undeclared_filter_is_silently_ignored(default):
assert len(titles(default.get("/games?year__gt=2015"))) == 6 # not in FilterConfig
assert titles(default.get("/games?year__gte=2017")) == ["Wingspan", "Mariposas", "Azul"]
def test_patch_cannot_break_the_rule(safe):
r = safe.patch("/games/2", json={"min_players": 9}, headers=KEY)
assert r.status_code == 422
assert safe.get("/games/2").json()["min_players"] == 1
$ pytest -q test_app.py .......... [100%] 10 passed in 0.79s
Is FastCRUD worth it?
For an admin API, an internal tool or the first version of a product, yes. One call gives you working endpoints with paging, sorting, filtering and OpenAPI docs, and the escape hatches are there when you need them. You can also keep using FastCRUD’s FastCRUD class directly inside your own endpoints for the routes that need custom logic.
What it doesn’t replace is your design. Authentication, limits, error codes and the rules your data must follow are still your job, and a generic router can’t guess them. Keeping those decisions clear and in one place is the same idea I described in clean architecture and SOLID. So my checklist is short: protect the writes, declare every filter, cap the page size, handle bad sort fields, and put cross-field rules in the database.
