Skip to main content

Powerful CRUD methods and automatic endpoint creation for FastAPI.

Tests PyPi Version Supported Python Versions


CRUDFastAPI 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.


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 CRUDFastAPI, ensure you have the following prerequisites:

  • Python: Version 3.9 or newer.
  • FastAPI: CRUDFastAPI is built to work with FastAPI, so having FastAPI in your project is essential.
  • SQLAlchemy: Version 2.0.21 or newer. CRUDFastAPI uses SQLAlchemy for database operations.
  • Pydantic: Version 2.4.1 or newer. CRUDFastAPI leverages Pydantic models for data validation and serialization.
  • SQLAlchemy-Utils: Optional, but recommended for additional SQLAlchemy utilities.

Installing

To install, just run:

pip install CRUDFastAPI

Or, if using poetry:

poetry add CRUDFastAPI

Usage

CRUDFastAPI offers two primary ways to use its functionalities:

  1. By using crud_router for automatic endpoint creation.
  2. By integrating CRUDFastAPI 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 CRUDFastAPI

main.py

from typing import AsyncGenerator

from fastapi import FastAPI
from CRUDFastAPI import CRUDFastAPI, 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 CRUDFastAPI in User-Defined FastAPI Endpoints

For more control over your endpoints, you can use CRUDFastAPI 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 CRUDFastAPI import CRUDFastAPI

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 CRUDFastAPI with your model
item_crud = CRUDFastAPI(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 CRUDFastAPI directly, providing more flexibility in how the endpoints are structured and how the responses are handled.

References

Similar Projects

License

MIT

Contact

github.com/mithun2003

Release files for CRUDFastAPI 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for CRUDFastAPI 0.1.2
File Size Uploaded
crudfastapi-0.1.2.tar.gz 31.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for CRUDFastAPI 0.1.2
File Interpreter ABI Platform
crudfastapi-0.1.2-py3-none-any.whl Python 3 none any Details

Total release size: 69.2 kB

Release files / crudfastapi-0.1.2.tar.gz

Download URL crudfastapi-0.1.2.tar.gz
Size 31.8 kB
Tags Source
SHA-256 checksum
How to use checksums
df637ea34558aa7b2dd62748645e31bcaeed3888eb33ece160a593c97db1ec97
BLAKE2b-256 checksum
How to use checksums
1e63e1312b107c2b0392484224e8316de1e7860f8653582ea6108377bd75bcce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.10.11

Release files / crudfastapi-0.1.2-py3-none-any.whl

Download URL crudfastapi-0.1.2-py3-none-any.whl
Size 37.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f49bbfe965edefa6d236b0e95ca76129df2b8e4bcc52041b2074b75e1260e9ec
BLAKE2b-256 checksum
How to use checksums
8e64c7795e34f97d50f7bad1f687b00f4a1a17097a588fecaa9e620c21d61fe3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.10.11

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files

0.1.1

2 release files

0.1.0

2 release files

0.0.9

2 release files

0.0.8

2 release files

0.0.7

2 release files

0.0.6

2 release files

0.0.5

2 release files

0.0.4

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

1 release file

0.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page