Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fast crud #109

Merged
merged 2 commits into from
Jan 24, 2024
Merged

Fast crud #109

merged 2 commits into from
Jan 24, 2024

Conversation

igorbenav
Copy link
Owner

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.


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.


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.

This replaces CRUDBase with a more robust and tested way.

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:

Usage:

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

To know all available methods, check it in fastcrud readme.

@igorbenav igorbenav added the enhancement New feature or request label Jan 24, 2024
@igorbenav igorbenav self-assigned this Jan 24, 2024
@igorbenav igorbenav merged commit cb3cec2 into main Jan 24, 2024
@igorbenav igorbenav deleted the fast-crud branch January 24, 2024 05:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant