FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities.
Project description
Powerful CRUD methods and automatic endpoint creation for FastAPI.
FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities, streamlined through advanced features like auto-detected join conditions, dynamic sorting, and offset and cursor pagination.
Documentation: benavlabs.github.io/fastcrud
Discord Community: Join our Discord server
Also take a look at CRUDAdmin - Modern admin interface for FastAPI
Features
- ⚡️ Fully Async: Leverages Python's async capabilities for non-blocking database operations.
- 📚 SQLAlchemy 2.0: Works with the latest SQLAlchemy version for robust database interactions.
- 🦾 Powerful CRUD Functionality: Full suite of efficient CRUD operations with support for joins.
- ⚙️ Dynamic Query Building: Supports building complex queries dynamically, including filtering, sorting, and pagination.
- 🤝 Advanced Join Operations: Facilitates performing SQL joins with other models with automatic join condition detection.
- 📖 Built-in Offset Pagination: Comes with ready-to-use offset pagination.
- ➤ Cursor-based Pagination: Implements efficient pagination for large datasets, ideal for infinite scrolling interfaces.
- 🤸♂️ Modular and Extensible: Designed for easy extension and customization to fit your requirements.
- 🛣️ Auto-generated Endpoints: Streamlines the process of adding CRUD endpoints with custom dependencies and configurations.
- 🤖 Bundled Library Skill: Ships with a Library Skill so AI coding tools (Claude Code, Cursor, Copilot, …) know how to use FastCRUD correctly — including N+1 avoidance and when to drop to raw SQLAlchemy.
Requirements
Before installing FastCRUD, ensure you have the following prerequisites:
- Python: Version 3.10 or newer.
- FastAPI: FastCRUD is built to work with FastAPI, so having FastAPI in your project is essential.
- SQLAlchemy: Version 2.0.21 or newer. FastCRUD uses SQLAlchemy for database operations.
- Pydantic: Version 2.4.1 or newer. FastCRUD leverages Pydantic models for data validation and serialization.
- SQLAlchemy-Utils: Optional, but recommended for additional SQLAlchemy utilities.
⚠️ Warning: If you are using a non-native column type (such as those from
sqlalchemy-utils) in your models, you may encounter aNotImplementedError. In such cases, you need to add apython_typeattribute to your column type. For more details and a discussion on this issue, see this pull request.
Installing
To install, just run:
pip install fastcrud
Or, if using UV:
uv add fastcrud
For AI Coding Agents
FastCRUD ships with a bundled Library Skill at fastcrud/.agents/skills/fastcrud/SKILL.md, following the Agent Skills standard.
To make it available to your coding agent, run library-skills from your project directory after fastcrud is installed:
# In any project that has fastcrud installed
uvx library-skills # for Codex, Cursor, Copilot, OpenCode, etc.
uvx library-skills --claude # for Claude Code (uses .claude/skills instead)
This symlinks the bundled skill into .agents/skills/ (or .claude/skills/ for Claude Code). Re-run after upgrading FastCRUD to pick up skill changes.
The skill teaches agents:
- The canonical setup pattern (model → schemas →
crud_router) - How to pick the right method (and avoid N+1 when fetching related data)
- The
limit=Nonefootgun and the three-tier pagination default - When NOT to use FastCRUD — aggregates, CTEs,
GROUP BYprojections, bulk writes belong to raw SQLAlchemy - Return-value semantics, the filter operator syntax (
__gte,__in,__ilike, …), soft delete, joined-table inheritance gotchas
Reference deep-dives live under fastcrud/.agents/skills/fastcrud/references/ for methods, filters, joins, pagination, and endpoints.
Usage
FastCRUD offers two primary ways to use its functionalities:
- By using
crud_routerfor automatic endpoint creation. - By integrating
FastCRUDdirectly into your FastAPI endpoints for more control.
Below are examples demonstrating both approaches:
Using crud_router for Automatic Endpoint Creation
Here's a quick example to get you started:
Define Your Model and Schema
models.py
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
class Item(Base):
__tablename__ = 'items'
id = Column(Integer, primary_key=True)
name = Column(String)
description = Column(String)
schemas.py
from pydantic import BaseModel
class ItemCreateSchema(BaseModel):
name: str
description: str
class ItemUpdateSchema(BaseModel):
name: str
description: str
Set Up FastAPI and FastCRUD
main.py
from typing import AsyncGenerator
from fastapi import FastAPI
from fastcrud import FastCRUD, crud_router
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from yourapp.models import Base, Item
from yourapp.schemas import ItemCreateSchema, ItemUpdateSchema
# Database setup (Async SQLAlchemy)
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
engine = create_async_engine(DATABASE_URL, echo=True)
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# Database session dependency
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with async_session() as session:
yield session
# Create tables before the app start
async def lifespan(app: FastAPI):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
# FastAPI app
app = FastAPI(lifespan=lifespan)
# CRUD router setup
item_router = crud_router(
session=get_session,
model=Item,
create_schema=ItemCreateSchema,
update_schema=ItemUpdateSchema,
path="/items",
tags=["Items"],
)
app.include_router(item_router)
Using FastCRUD in User-Defined FastAPI Endpoints
For more control over your endpoints, you can use FastCRUD directly within your custom FastAPI route functions. Here's an example:
main.py
from typing import AsyncGenerator
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from fastcrud import FastCRUD
from models import Base, Item
from schemas import ItemCreateSchema, ItemUpdateSchema
# Database setup (Async SQLAlchemy)
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
engine = create_async_engine(DATABASE_URL, echo=True)
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# Database session dependency
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with async_session() as session:
yield session
# Create tables before the app start
async def lifespan(app: FastAPI):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
# FastAPI app
app = FastAPI(lifespan=lifespan)
# Instantiate FastCRUD with your model
item_crud = FastCRUD(Item)
@app.post("/custom/items/")
async def create_item(
item_data: ItemCreateSchema, db: AsyncSession = Depends(get_session)
):
return await item_crud.create(db, item_data)
@app.get("/custom/items/{item_id}")
async def read_item(item_id: int, db: AsyncSession = Depends(get_session)):
item = await item_crud.get(db, id=item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
# You can add more routes for update and delete operations in a similar fashion
In this example, we define custom endpoints for creating and reading items using FastCRUD directly, providing more flexibility in how the endpoints are structured and how the responses are handled.
To read more detailed descriptions, go to the documentation.
🧠 DeepWiki Docs: deepwiki.com/benavlabs/FastAPI-boilerplate
Showcase
Browse our showcase to see projects and tutorials built with FastCRUD:
- 🚀 Applications: Web apps and services powered by FastCRUD
- 📖 Open Source: Libraries and tools built with FastCRUD
- 📝 Tutorials: Learn how to build with FastCRUD
Featured Projects
- FastAPI Boilerplate: Extendable async API using FastAPI, Pydantic V2, SQLAlchemy 2.0 and PostgreSQL
- Email Assistant API: Personalized email writing assistant using OpenAI
- SQLModel Boilerplate: Async API boilerplate using FastAPI, SQLModel and PostgreSQL
Share Your Project
Built something with FastCRUD? We'd love to feature it! Submit your project through our showcase submission process.
References
- This project was heavily inspired by CRUDBase in
FastAPI Microservicesby @kludex. - Thanks @ada0l for the PyPI package name!
Similar Projects
- flask-muck - "I'd love something like this for flask" There you have it
- FastAPI CRUD Router - Supports multiple ORMs, but currently unmantained
- FastAPI Quick CRUD - Same purpose, but only for SQLAlchemy 1.4
License
Contact
Benav Labs – benav.io github.com/benavlabs
Build a full SaaS on FastAPI
FastCRUD handles the data layer in FastroAI - the complete FastAPI SaaS template: auth, Stripe payments (subscriptions, credits, discounts), entitlements, transactional email, an Astro frontend, and PydanticAI agents, wired together and production-ready.
Ship your SaaS faster with FastroAI →
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastcrud-0.22.3.tar.gz.
File metadata
- Download URL: fastcrud-0.22.3.tar.gz
- Upload date:
- Size: 103.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d8ebe74bf07352c5260698fec7bd40f0a1c09b8f189c6d57d157f04ef86bc09a
|
|
| MD5 |
0959451bb1efc5b140312d19dc487131
|
|
| BLAKE2b-256 |
e4065ef9131152b98d1d914067389a3334cebe21b1db4505e232cc6f2a6392cb
|
File details
Details for the file fastcrud-0.22.3-py3-none-any.whl.
File metadata
- Download URL: fastcrud-0.22.3-py3-none-any.whl
- Upload date:
- Size: 136.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8ea2cb20ab111ae37793cfc0c88592dbed4700ef6ebebfcb6ef161582df780da
|
|
| MD5 |
06a4ce7f5f25a74c793e8e9671b33f25
|
|
| BLAKE2b-256 |
36ac23eed29a3ff360e5f07f84fe61f409360341e839e15838e2aa823a782846
|