Fastcrud
FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities.
Install / Use
/learn @benavlabs/FastcrudREADME
- ⚡️ 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.
<h2>Installing</h2>⚠️ 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.
To install, just run:
pip install fastcrud
Or, if using UV:
uv add fastcrud
<h2>Usage</h2>
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:
<h3>Using crud_router for Automatic Endpoint Creation</h3>Here's a quick example to get you started:
<h4>Define Your Model and Schema</h4>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
<h4>Set Up FastAPI and FastCRUD</h4>
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)
<h3>Using FastCRUD in User-Defined FastAPI Endpoints</h3>
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 <a href="https://benavlabs.github.io/fastcrud/">documentation</a>.
🧠 DeepWiki Docs: deepwiki.com/benavlabs/FastAPI-boilerplate
<h2>Showcase</h2>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
- 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
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 SQ
Related Skills
claude-opus-4-5-migration
83.9kMigrate prompts and code from Claude Sonnet 4.0, Sonnet 4.5, or Opus 4.1 to Opus 4.5
model-usage
339.3kUse CodexBar CLI local cost usage to summarize per-model usage for Codex or Claude, including the current (most recent) model or a full model breakdown. Trigger when asked for model-level usage/cost data from codexbar, or when you need a scriptable per-model summary from codexbar cost JSON.
feishu-drive
339.3k|
things-mac
339.3kManage Things 3 via the `things` CLI on macOS (add/update projects+todos via URL scheme; read/search/list from the local Things database)
