Skip to main content

FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities.

Project description

FastCRUD written in white with a drawing of a gear and inside this gear a bolt.

Powerful CRUD methods and automatic endpoint creation for FastAPI.

Tests PyPi Version Supported Python Versions


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: igorbenav.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:

pip install fastcrud

Or, if using poetry:

poetry 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

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.

References

Similar Projects

License

MIT

Contact

Igor Magalhaes – @igormagalhaesrigormagalhaesr@gmail.com github.com/igorbenav

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastcrud-0.15.0.tar.gz (40.2 kB view details)

Uploaded Source

Built Distribution

fastcrud-0.15.0-py3-none-any.whl (51.8 kB view details)

Uploaded Python 3

File details

Details for the file fastcrud-0.15.0.tar.gz.

File metadata

  • Download URL: fastcrud-0.15.0.tar.gz
  • Upload date:
  • Size: 40.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.11.4 Darwin/23.6.0

File hashes

Hashes for fastcrud-0.15.0.tar.gz
Algorithm Hash digest
SHA256 bc938f849bcaa1b8c6c96e4268c375e4f0ad8d86f3e8e3fc59db0841bbe4918f
MD5 e4d1058d206657f01d57ef476146c0a7
BLAKE2b-256 6096ad3f988d82b023050c97c76ea527bc5a7014dcb661ee2b74ab39dae975f6

See more details on using hashes here.

File details

Details for the file fastcrud-0.15.0-py3-none-any.whl.

File metadata

  • Download URL: fastcrud-0.15.0-py3-none-any.whl
  • Upload date:
  • Size: 51.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.11.4 Darwin/23.6.0

File hashes

Hashes for fastcrud-0.15.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b1368f42d03b46afa2db843896ebd714659d298528467633c18440defa17edf1
MD5 0d3185d28dbaf1e51d195159b04669f0
BLAKE2b-256 29466e5de17c5b8f1fbf8c3bed61a5b145b713d8de3e25dcf3ea48ee181a3295

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page