Skip to main content

FastAPI CRUD Kit

CI PyPI Python Version GitHub License

A powerful CRUD toolkit for FastAPI with SQLAlchemy, featuring query building, filtering, sorting, and field selection with async/sync support.

Why FastAPI CRUD Kit?

Building REST APIs with FastAPI and SQLAlchemy often requires writing repetitive CRUD code, handling query parameters, managing database sessions, and implementing common patterns like pagination, filtering, and soft deletes. FastAPI CRUD Kit eliminates this boilerplate by providing:

  • Ready-to-use CRUD operations that work with any SQLAlchemy model
  • Advanced query building with automatic parsing and validation of query parameters
  • Production-ready features like transactions, retries, timeouts, and read-only operations
  • Type-safe operations with full type hints support
  • Flexible architecture supporting both async and sync SQLAlchemy sessions

Features

  • 🚀 Full CRUD Operations: Create, Read, Update, Delete with minimal boilerplate
  • 🔍 Advanced Query Building: Filtering, sorting, field selection, and relationship loading
  • ⚡ Async & Sync Support: Works seamlessly with both async and sync SQLAlchemy sessions
  • 🛡️ Filter Validation: Configurable filter validation with custom callbacks
  • 🔒 Type Safe: Full type hints support throughout
  • 📦 Production Ready: Context managers for transactions, retries, and timeouts
  • 🗑️ Soft Delete: Built-in support for soft delete functionality
  • 📊 Pagination: Built-in pagination support with complete metadata

Installation

pip install fastapi-crud-kit

Or using poetry:

poetry add fastapi-crud-kit

Quick Example

from fastapi_crud_kit.crud.base import CRUDBase
from fastapi_crud_kit.models import BaseModel
from fastapi_crud_kit.query import AllowedFilters, QueryBuilderConfig, parse_query_params
from sqlalchemy import Column, String

# Define your model
class Category(BaseModel):
    __tablename__ = "categories"
    name = Column(String, nullable=False)

# Create CRUD class
class CategoryCRUD(CRUDBase[Category]):
    def __init__(self):
        query_config = QueryBuilderConfig(
            allowed_filters=[AllowedFilters.exact("name")]
        )
        super().__init__(model=Category, use_async=True, query_config=query_config)

# Use in FastAPI route
@router.get("/categories")
async def list_categories(request: Request, db: AsyncSession = Depends(get_db)):
    query_params = parse_query_params(request.query_params)
    return await category_crud.list_paginated(db, query_params)

How It Works

CRUD Operations

The CRUDBase class provides all standard CRUD operations (list, get, create, update, delete) that work with any SQLAlchemy model. It automatically handles:

  • Query building from URL parameters
  • Filter validation and application
  • Pagination with metadata
  • Soft delete filtering (if supported by the model)
  • Relationship loading (eager loading)

Query Building

The query builder automatically parses and validates query parameters from the request URL:

  • Filters: ?filter[name]=Tech&filter[price][gte]=100
  • Sorting: ?sort=name&sort=-created_at
  • Field Selection: ?fields=id,name
  • Includes: ?include=products,tags
  • Pagination: ?page=1&per_page=20

All query parameters are validated against your configuration, preventing SQL injection and ensuring type safety.

Base Models

The package provides ready-to-use base models with common features:

  • BaseModel: Includes primary key, UUID, timestamps, and soft delete
  • BaseModelWithUUIDPK: UUID as primary key
  • Individual mixins for custom combinations

Database Management

The DatabaseFactory simplifies database setup by automatically detecting the database type and configuring the appropriate drivers. It supports PostgreSQL, MySQL, and SQLite in both async and sync modes.

Context Managers

Production-ready context managers for common patterns:

  • Transactions: Automatic commit/rollback
  • Retries: Exponential backoff for transient failures
  • Timeouts: Prevent operations from hanging
  • Read-only: Enforce read-only operations

Requirements

  • Python >= 3.10
  • SQLAlchemy >= 2.0.45
  • Pydantic >= 2.12.5
  • FastAPI >= 0.128.0

Documentation

Comprehensive documentation with examples, guides, and API reference is available at:

https://mawuva.github.io/fastapi-crud-kit/

Or build it locally:

mkdocs serve

Examples

See the examples/ directory for complete working examples.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

See LICENSE file for details.

Support

For issues, questions, or contributions, please visit the GitHub repository.

Metadata

Release files for fastapi-crud-kit 0.2.0

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

Source distribution (sdist)

Source distribution for fastapi-crud-kit 0.2.0
File Size Uploaded Provenance
fastapi_crud_kit-0.2.0.tar.gz 35.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-crud-kit 0.2.0
File Interpreter ABI Platform
fastapi_crud_kit-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 91.8 kB

Release files / fastapi_crud_kit-0.2.0.tar.gz

Download URL fastapi_crud_kit-0.2.0.tar.gz
Size 35.9 kB
Tags Source
SHA-256 checksum
How to use checksums
3c8508e47adc44897e66a244d2c233bd3cd1b35d218b3d3b06a18f6e8c460bed
BLAKE2b-256 checksum
How to use checksums
af05ae6758fcfdd98004e0cee69b4141ebbc6d8a39053313eb59829ba75eb0b1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.11.14 Linux/6.11.0-1018-azure

Release files / fastapi_crud_kit-0.2.0-py3-none-any.whl

Download URL fastapi_crud_kit-0.2.0-py3-none-any.whl
Size 55.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb0f81876915c8a903dae3d596336b417f56e244565ce51fc548e5a632f89bb1
BLAKE2b-256 checksum
How to use checksums
b97fd9386900ac5f6ba27a9c266a96bdccd69a794a2c0ac2721c2934dff58582
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.11.14 Linux/6.11.0-1018-azure

Security for fastapi-crud-kit 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

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