Coder Social home page Coder Social logo

edwardburns / fastcrud Goto Github PK

View Code? Open in Web Editor NEW

This project forked from igorbenav/fastcrud

0.0 0.0 0.0 1.26 MB

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

License: MIT License

Python 100.00%

fastcrud's Introduction

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

Warning

For now, your primary column must be named id or automatic endpoint creation will not work.

Here's a quick example to get you started:

Define Your Model and Schema

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import DeclarativeBase
from pydantic import BaseModel

class Base(DeclarativeBase):
    pass

class Item(Base):
    __tablename__ = 'items'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    description = Column(String)

class ItemCreateSchema(BaseModel):
    name: str
    description: str

class ItemUpdateSchema(BaseModel):
    name: str
    description: str

Set Up FastAPI and FastCRUD

from fastapi import FastAPI
from fastcrud import FastCRUD, crud_router
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

# 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)

# FastAPI app
app = FastAPI()

# CRUD operations setup
crud = FastCRUD(Item)

# CRUD router setup
item_router = crud_router(
    session=async_session,
    model=Item,
    crud=crud,
    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:

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from fastcrud import FastCRUD
from yourapp.models import Item
from yourapp.schemas import ItemCreateSchema, ItemUpdateSchema

app = FastAPI()

# Assume async_session is already set up as per the previous example

# Instantiate FastCRUD with your model
item_crud = FastCRUD(Item)

@app.post("/custom/items/")
async def create_item(item_data: ItemCreateSchema, db: AsyncSession = Depends(async_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(async_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

This project was heavily inspired by CRUDBase in FastAPI Microservices by @kludex.

10. License

MIT

11. Contact

Igor Magalhaes – @igormagalhaesr – [email protected] github.com/igorbenav

fastcrud's People

Contributors

igorbenav avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.