https://github.com/benavlabs/fastcrud
FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities.
https://github.com/benavlabs/fastcrud
async backend crud fastapi pydantic pydantic-v2 python sqlalchemy
Last synced: 28 days ago
JSON representation
FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities.
- Host: GitHub
- URL: https://github.com/benavlabs/fastcrud
- Owner: benavlabs
- License: mit
- Created: 2024-01-08T04:04:17.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-05-10T07:14:08.000Z (29 days ago)
- Last Synced: 2025-05-11T17:58:46.671Z (28 days ago)
- Topics: async, backend, crud, fastapi, pydantic, pydantic-v2, python, sqlalchemy
- Language: Python
- Homepage:
- Size: 3.44 MB
- Stars: 1,055
- Watchers: 8
- Forks: 75
- Open Issues: 29
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Security: SECURITY.md
Awesome Lists containing this project
README
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
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.Requirements
Before installing FastCRUD, ensure you have the following prerequisites:
-
Python: Version 3.9 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.
Installing
To install, just run:
```sh
pip install fastcrud
```
Or, if using UV:
```sh
uv add fastcrud
```
Usage
FastCRUD offers two primary ways to use its functionalities:
1. By using `crud_router` for automatic endpoint creation.
2. By integrating `FastCRUD` directly 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**
```python
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**
```python
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**
```python
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**
```python
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.
Showcase
Browse our [showcase](https://benavlabs.github.io/fastcrud/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](https://github.com/benavlabs/FastAPI-boilerplate)**: Extendable async API using FastAPI, Pydantic V2, SQLAlchemy 2.0 and PostgreSQL
- **[Email Assistant API](https://github.com/igorbenav/email-assistant-api)**: Personalized email writing assistant using OpenAI
- **[SQLModel Boilerplate](https://github.com/benavlabs/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](https://benavlabs.github.io/fastcrud/community/showcase_submission/).
## References
- This project was heavily inspired by CRUDBase in [`FastAPI Microservices`](https://github.com/Kludex/fastapi-microservices) by [@kludex](https://github.com/kludex).
- Thanks [@ada0l](https://github.com/ada0l) for the PyPI package name!
## Similar Projects
- **[flask-muck](https://github.com/dtiesling/flask-muck)** - _"I'd love something like this for flask"_ There you have it
- **[FastAPI CRUD Router](https://github.com/awtkns/fastapi-crudrouter)** - Supports multiple ORMs, but currently unmantained
- **[FastAPI Quick CRUD](https://github.com/LuisLuii/FastAPIQuickCRUD)** - Same purpose, but only for SQLAlchemy 1.4
## License
[`MIT`](LICENSE.md)
## Contact
Benav Labs β [benav.io](https://benav.io)
[github.com/benavlabs](https://github.com/benavlabs/)