Automatically generate CRUD APIs for FastAPI with SQLAlchemy models
Project description
fastapi-autocrud-rishabh
🚀 Automatically generate fully functional CRUD APIs for FastAPI applications using SQLAlchemy models and Pydantic schemas — without writing repetitive endpoint code.
Features
✨ Auto-generate CRUD endpoints - Create, Read, Update, Delete with one line
📄 Built-in Pagination - Limit/offset pagination out of the box
🔍 Advanced Filtering - Support for multiple filter operators (icontains, gte, in, etc.)
📊 Ordering - Sort by any field ascending or descending
🔐 Role-Based Access Control - Optional permission system
📚 Auto OpenAPI Docs - Swagger UI documentation generated automatically
⚡ Zero Dependencies - Only requires FastAPI and SQLAlchemy
Installation
pip install fastapi-autocrud-rishabh
Quick Start
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from pydantic import BaseModel
from fastapi_autocrud_rishabh import AutoCRUDRouter
# Database setup
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# SQLAlchemy Model
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)
age = Column(Integer)
Base.metadata.create_all(bind=engine)
# Pydantic Schemas
class UserCreate(BaseModel):
name: str
email: str
age: int
class UserRead(BaseModel):
id: int
name: str
email: str
age: int
class Config:
from_attributes = True
# Database dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# FastAPI App
app = FastAPI()
# Generate CRUD Router (1 line!)
user_router = AutoCRUDRouter(
model=User,
create_schema=UserCreate,
read_schema=UserRead,
db_session=get_db,
prefix="/users",
tags=["Users"]
)
# Include router
app.include_router(user_router.router)
That's it! You now have 5 endpoints:
POST /users/- Create userGET /users/- List users (with pagination & filters)GET /users/{id}- Get user by IDPUT /users/{id}- Update userDELETE /users/{id}- Delete user
Advanced Usage
Filtering & Pagination
# Pagination
GET /users/?limit=25&offset=0
# Filtering
GET /users/?name__icontains=john&age__gte=18
# Ordering
GET /users/?order_by=-created_at
# Combine all
GET /users/?limit=10&age__gte=21&name__icontains=alice&order_by=-id
Supported Filter Operators
| Operator | Description | Example |
|---|---|---|
exact |
Exact match (default) | name=John |
contains |
Case-sensitive contains | name__contains=oh |
icontains |
Case-insensitive contains | name__icontains=JOHN |
gt |
Greater than | age__gt=18 |
gte |
Greater than or equal | age__gte=18 |
lt |
Less than | age__lt=65 |
lte |
Less than or equal | age__lte=65 |
in |
In list | id__in=1,2,3 |
not_in |
Not in list | status__not_in=banned,deleted |
Role-Based Access Control
from fastapi import Request
# Define role getter
def get_user_role(request: Request):
return request.state.user.role # Adjust based on your auth system
# Create router with role restrictions
user_router = AutoCRUDRouter(
model=User,
create_schema=UserCreate,
read_schema=UserRead,
db_session=get_db,
prefix="/users",
roles={
"delete": ["admin"],
"update": ["admin", "staff"],
"create": ["admin", "staff", "user"]
},
user_role_getter=get_user_role
)
Global Dependencies (JWT Auth)
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
security = HTTPBearer()
async def verify_token(token: str = Depends(security)):
# Your token verification logic
if not valid_token(token):
raise HTTPException(status_code=401, detail="Invalid token")
return token
# Add to all endpoints
user_router = AutoCRUDRouter(
model=User,
create_schema=UserCreate,
read_schema=UserRead,
db_session=get_db,
prefix="/users",
dependencies=[Depends(verify_token)]
)
Custom Update Schema
class UserUpdate(BaseModel):
name: Optional[str] = None
age: Optional[int] = None
user_router = AutoCRUDRouter(
model=User,
create_schema=UserCreate,
read_schema=UserRead,
update_schema=UserUpdate, # Separate update schema
db_session=get_db,
prefix="/users"
)
Response Format
List Endpoint Response
{
"items": [
{"id": 1, "name": "John", "email": "john@example.com", "age": 25},
{"id": 2, "name": "Jane", "email": "jane@example.com", "age": 30}
],
"total": 2,
"limit": 100,
"offset": 0
}
Error Responses
{
"detail": "Item not found"
}
Development
Setup Development Environment
# Clone repository
git clone https://github.com/yourusername/fastapi-autocrud-rishabh.git
cd fastapi-autocrud-rishabh
# Install with dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run tests with coverage
pytest --cov=fastapi_autocrud_rishabh --cov-report=html
# Format code
black .
isort .
# Lint
flake8 fastapi_autocrud_rishabh
Publishing to PyPI
# Build package
python -m pip install build twine
python -m build
# Upload to PyPI
python -m twine upload dist/*
Roadmap
- ✅ v0.1.0 - Initial release with sync SQLAlchemy support
- ⏳ v0.2.0 - Async SQLAlchemy support
- ⏳ v0.3.0 - Relationship support (1-to-many, many-to-many)
- ⏳ v0.4.0 - Pydantic v2 support
- ⏳ v1.0.0 - Production ready with full test coverage
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License - see LICENSE file for details.
Author
Rishabh
Support
If you encounter any issues or have questions, please open an issue on GitHub.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_autocrud_rishabh-0.1.0.tar.gz.
File metadata
- Download URL: fastapi_autocrud_rishabh-0.1.0.tar.gz
- Upload date:
- Size: 16.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5ce8961c23fc202a1d44fe7a19b5e7f71c193a3d14b0f0fbdedc8a0871772b35
|
|
| MD5 |
a6c4b93bd8d56817115dd9440d205de8
|
|
| BLAKE2b-256 |
b379d95b6cada27a414b3da6a811989bad77296ea7e83c38c79b00c0de3d82f1
|
File details
Details for the file fastapi_autocrud_rishabh-0.1.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_autocrud_rishabh-0.1.0-py3-none-any.whl
- Upload date:
- Size: 12.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0f506c98e1ef22eec27c8174be8954517c5ba1535978527bc59b43e126778f97
|
|
| MD5 |
9644c6ce7e3a2235444e846e9bf5b17d
|
|
| BLAKE2b-256 |
e08b6c9e27d34912b3a40265f0fd8a1e754968bc660047d4f8c3d54b8646f054
|