<p align="center">
<a href="https://igorbenav.github.io/fastcrud/">
<img src="https://github.com/igorbenav/fastcrud/blob/main/assets/fastcrud.png?raw=true" alt="FastCRUD written in white with a drawing of a gear and inside this gear a bolt." width="45%" height="auto">
</a>
</p>
<p align="center" markdown=1>
<i>Powerful CRUD methods and automatic endpoint creation for FastAPI.</i>
</p>
<p align="center" markdown=1>
<a href="https://github.com/igorbenav/fastcrud/actions/workflows/tests.yml">
<img src="https://github.com/igorbenav/fastcrud/actions/workflows/tests.yml/badge.svg" alt="Tests"/>
</a>
<a href="https://pypi.org/project/fastcrud/">
<img src="https://img.shields.io/pypi/v/fastcrud?color=%2334D058&label=pypi%20package" alt="PyPi Version"/>
</a>
<a href="https://pypi.org/project/fastcrud/">
<img src="https://img.shields.io/pypi/pyversions/fastcrud.svg?color=%2334D058" alt="Supported Python Versions"/>
</a>
<a href="https://codecov.io/gh/igorbenav/fastcrud" >
<img src="https://codecov.io/gh/igorbenav/fastcrud/graph/badge.svg?token=J7XUP29RKU"/>
</a>
</p>
<hr>
<p align="justify">
<b>FastCRUD</b> is a Python package for <b>FastAPI</b>, offering robust async CRUD operations and flexible endpoint creation utilities, streamlined through advanced features like <b>auto-detected join</b> conditions, <b>dynamic sorting</b>, and offset and cursor <b>pagination</b>.
</p>
<p><b>Documentation</b>: <a href="https://igorbenav.github.io/fastcrud/">igorbenav.github.io/fastcrud</a></p>
<hr>
<h2>Features</h2>
- β‘οΈ **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.
<h2>Requirements</h2>
<p>Before installing FastCRUD, ensure you have the following prerequisites:</p>
<ul>
<li><b>Python:</b> Version 3.9 or newer.</li>
<li><b>FastAPI:</b> FastCRUD is built to work with FastAPI, so having FastAPI in your project is essential.</li>
<li><b>SQLAlchemy:</b> Version 2.0.21 or newer. FastCRUD uses SQLAlchemy for database operations.</li>
<li><b>Pydantic:</b> Version 2.4.1 or newer. FastCRUD leverages Pydantic models for data validation and serialization.</li>
<li><b>SQLAlchemy-Utils:</b> Optional, but recommended for additional SQLAlchemy utilities.</li>
</ul>
<h2>Installing</h2>
To install, just run:
```sh
pip install fastcrud
```
Or, if using poetry:
```sh
poetry add fastcrud
```
<h2>Usage</h2>
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:
<h3>Using crud_router for Automatic Endpoint Creation</h3>
Here's a quick example to get you started:
<h4>Define Your Model and Schema</h4>
**models.py**
```python
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**
```python
from pydantic import BaseModel
class ItemCreateSchema(BaseModel):
name: str
description: str
class ItemUpdateSchema(BaseModel):
name: str
description: str
```
<h4>Set Up FastAPI and FastCRUD</h4>
**main.py**
```python
from typing import AsyncGenerator
from fastapi import FastAPI
from fastcrud import FastCRUD, 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)
```
<h3>Using FastCRUD in User-Defined FastAPI Endpoints</h3>
For more control over your endpoints, you can use FastCRUD directly within your custom FastAPI route functions. Here's an example:
**main.py**
```python
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 fastcrud import FastCRUD
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 FastCRUD with your model
item_crud = FastCRUD(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 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 <a href="https://igorbenav.github.io/fastcrud/">documentation</a>.
## References
- This project was heavily inspired by CRUDBase in [`FastAPI Microservices`](https://github.com/Kludex/fastapi-microservices) by [@kludex](https://github.com/kludex).
- Thanks [@ada0l](https://github.com/ada0l) for the PyPI package name!
## Similar Projects
- **[flask-muck](https://github.com/dtiesling/flask-muck)** - _"I'd love something like this for flask"_ There you have it
- **[FastAPI CRUD Router](https://github.com/awtkns/fastapi-crudrouter)** - Supports multiple ORMs, but currently unmantained
- **[FastAPI Quick CRUD](https://github.com/LuisLuii/FastAPIQuickCRUD)** - Same purpose, but only for SQLAlchemy 1.4
## License
[`MIT`](LICENSE.md)
## Contact
Igor Magalhaes β [@igormagalhaesr](https://twitter.com/igormagalhaesr) β igormagalhaesr@gmail.com
[github.com/igorbenav](https://github.com/igorbenav/)
Raw data
{
"_id": null,
"home_page": "https://github.com/igorbenav/fastcrud",
"name": "fastcrud",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.9",
"maintainer_email": null,
"keywords": "fastapi, crud, async, sqlalchemy, pydantic",
"author": "Igor Benav",
"author_email": "igor.magalhaes.r@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/92/52/b2dfbc4638476f1d5aa6995c237c04131a18b3d51c5d684441273eaff8e5/fastcrud-0.15.1.tar.gz",
"platform": null,
"description": "<p align=\"center\">\n <a href=\"https://igorbenav.github.io/fastcrud/\">\n <img src=\"https://github.com/igorbenav/fastcrud/blob/main/assets/fastcrud.png?raw=true\" alt=\"FastCRUD written in white with a drawing of a gear and inside this gear a bolt.\" width=\"45%\" height=\"auto\">\n </a>\n</p>\n<p align=\"center\" markdown=1>\n <i>Powerful CRUD methods and automatic endpoint creation for FastAPI.</i>\n</p>\n<p align=\"center\" markdown=1>\n<a href=\"https://github.com/igorbenav/fastcrud/actions/workflows/tests.yml\">\n <img src=\"https://github.com/igorbenav/fastcrud/actions/workflows/tests.yml/badge.svg\" alt=\"Tests\"/>\n</a>\n<a href=\"https://pypi.org/project/fastcrud/\">\n <img src=\"https://img.shields.io/pypi/v/fastcrud?color=%2334D058&label=pypi%20package\" alt=\"PyPi Version\"/>\n</a>\n<a href=\"https://pypi.org/project/fastcrud/\">\n <img src=\"https://img.shields.io/pypi/pyversions/fastcrud.svg?color=%2334D058\" alt=\"Supported Python Versions\"/>\n</a>\n<a href=\"https://codecov.io/gh/igorbenav/fastcrud\" > \n <img src=\"https://codecov.io/gh/igorbenav/fastcrud/graph/badge.svg?token=J7XUP29RKU\"/> \n</a>\n</p>\n<hr>\n<p align=\"justify\">\n<b>FastCRUD</b> is a Python package for <b>FastAPI</b>, offering robust async CRUD operations and flexible endpoint creation utilities, streamlined through advanced features like <b>auto-detected join</b> conditions, <b>dynamic sorting</b>, and offset and cursor <b>pagination</b>.\n</p>\n<p><b>Documentation</b>: <a href=\"https://igorbenav.github.io/fastcrud/\">igorbenav.github.io/fastcrud</a></p>\n<hr>\n<h2>Features</h2>\n\n- \u26a1\ufe0f **Fully Async**: Leverages Python's async capabilities for non-blocking database operations.\n- \ud83d\udcda **SQLAlchemy 2.0**: Works with the latest SQLAlchemy version for robust database interactions.\n- \ud83e\uddbe **Powerful CRUD Functionality**: Full suite of efficient CRUD operations with support for joins.\n- \u2699\ufe0f **Dynamic Query Building**: Supports building complex queries dynamically, including filtering, sorting, and pagination.\n- \ud83e\udd1d **Advanced Join Operations**: Facilitates performing SQL joins with other models with automatic join condition detection.\n- \ud83d\udcd6 **Built-in Offset Pagination**: Comes with ready-to-use offset pagination.\n- \u27a4 **Cursor-based Pagination**: Implements efficient pagination for large datasets, ideal for infinite scrolling interfaces.\n- \ud83e\udd38\u200d\u2642\ufe0f **Modular and Extensible**: Designed for easy extension and customization to fit your requirements.\n- \ud83d\udee3\ufe0f **Auto-generated Endpoints**: Streamlines the process of adding CRUD endpoints with custom dependencies and configurations.\n\n<h2>Requirements</h2>\n<p>Before installing FastCRUD, ensure you have the following prerequisites:</p>\n<ul>\n <li><b>Python:</b> Version 3.9 or newer.</li>\n <li><b>FastAPI:</b> FastCRUD is built to work with FastAPI, so having FastAPI in your project is essential.</li>\n <li><b>SQLAlchemy:</b> Version 2.0.21 or newer. FastCRUD uses SQLAlchemy for database operations.</li>\n <li><b>Pydantic:</b> Version 2.4.1 or newer. FastCRUD leverages Pydantic models for data validation and serialization.</li>\n <li><b>SQLAlchemy-Utils:</b> Optional, but recommended for additional SQLAlchemy utilities.</li>\n</ul>\n\n<h2>Installing</h2>\n\nTo install, just run:\n\n```sh\npip install fastcrud\n```\n\nOr, if using poetry:\n\n```sh\npoetry add fastcrud\n```\n\n<h2>Usage</h2>\n\nFastCRUD offers two primary ways to use its functionalities:\n\n1. By using `crud_router` for automatic endpoint creation.\n2. By integrating `FastCRUD` directly into your FastAPI endpoints for more control.\n\nBelow are examples demonstrating both approaches:\n\n<h3>Using crud_router for Automatic Endpoint Creation</h3>\n\nHere's a quick example to get you started:\n\n<h4>Define Your Model and Schema</h4>\n\n**models.py**\n\n```python\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.orm import DeclarativeBase\n\nclass Base(DeclarativeBase):\n pass\n\nclass Item(Base):\n __tablename__ = 'items'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n description = Column(String)\n```\n\n**schemas.py**\n\n```python\nfrom pydantic import BaseModel\n\nclass ItemCreateSchema(BaseModel):\n name: str\n description: str\n\nclass ItemUpdateSchema(BaseModel):\n name: str\n description: str\n```\n\n<h4>Set Up FastAPI and FastCRUD</h4>\n\n**main.py**\n\n```python\nfrom typing import AsyncGenerator\n\nfrom fastapi import FastAPI\nfrom fastcrud import FastCRUD, crud_router\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom yourapp.models import Base, Item\nfrom yourapp.schemas import ItemCreateSchema, ItemUpdateSchema\n\n# Database setup (Async SQLAlchemy)\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nengine = create_async_engine(DATABASE_URL, echo=True)\nasync_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\n\n# Database session dependency\nasync def get_session() -> AsyncGenerator[AsyncSession, None]:\n async with async_session() as session:\n yield session\n\n# Create tables before the app start\nasync def lifespan(app: FastAPI):\n async with engine.begin() as conn:\n await conn.run_sync(Base.metadata.create_all)\n yield\n\n# FastAPI app\napp = FastAPI(lifespan=lifespan)\n\n# CRUD router setup\nitem_router = crud_router(\n session=get_session,\n model=Item,\n create_schema=ItemCreateSchema,\n update_schema=ItemUpdateSchema,\n path=\"/items\",\n tags=[\"Items\"],\n)\n\napp.include_router(item_router)\n\n```\n\n<h3>Using FastCRUD in User-Defined FastAPI Endpoints</h3>\n\nFor more control over your endpoints, you can use FastCRUD directly within your custom FastAPI route functions. Here's an example:\n\n**main.py**\n\n```python\nfrom typing import AsyncGenerator\n\nfrom fastapi import FastAPI, Depends, HTTPException\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom fastcrud import FastCRUD\n\nfrom models import Base, Item\nfrom schemas import ItemCreateSchema, ItemUpdateSchema\n\n# Database setup (Async SQLAlchemy)\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nengine = create_async_engine(DATABASE_URL, echo=True)\nasync_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\n\n# Database session dependency\nasync def get_session() -> AsyncGenerator[AsyncSession, None]:\n async with async_session() as session:\n yield session\n\n# Create tables before the app start\nasync def lifespan(app: FastAPI):\n async with engine.begin() as conn:\n await conn.run_sync(Base.metadata.create_all)\n yield\n\n# FastAPI app\napp = FastAPI(lifespan=lifespan)\n\n# Instantiate FastCRUD with your model\nitem_crud = FastCRUD(Item)\n\n@app.post(\"/custom/items/\")\nasync def create_item(\n item_data: ItemCreateSchema, db: AsyncSession = Depends(get_session)\n):\n return await item_crud.create(db, item_data)\n\n@app.get(\"/custom/items/{item_id}\")\nasync def read_item(item_id: int, db: AsyncSession = Depends(get_session)):\n item = await item_crud.get(db, id=item_id)\n if not item:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return item\n\n# You can add more routes for update and delete operations in a similar fashion\n```\n\nIn 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.\n\nTo read more detailed descriptions, go to the <a href=\"https://igorbenav.github.io/fastcrud/\">documentation</a>.\n\n## References\n\n- This project was heavily inspired by CRUDBase in [`FastAPI Microservices`](https://github.com/Kludex/fastapi-microservices) by [@kludex](https://github.com/kludex).\n- Thanks [@ada0l](https://github.com/ada0l) for the PyPI package name!\n\n## Similar Projects\n\n- **[flask-muck](https://github.com/dtiesling/flask-muck)** - _\"I'd love something like this for flask\"_ There you have it\n- **[FastAPI CRUD Router](https://github.com/awtkns/fastapi-crudrouter)** - Supports multiple ORMs, but currently unmantained\n- **[FastAPI Quick CRUD](https://github.com/LuisLuii/FastAPIQuickCRUD)** - Same purpose, but only for SQLAlchemy 1.4\n\n## License\n\n[`MIT`](LICENSE.md)\n\n## Contact\n\nIgor Magalhaes \u2013 [@igormagalhaesr](https://twitter.com/igormagalhaesr) \u2013 igormagalhaesr@gmail.com\n[github.com/igorbenav](https://github.com/igorbenav/)\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities.",
"version": "0.15.1",
"project_urls": {
"Homepage": "https://github.com/igorbenav/fastcrud",
"Repository": "https://github.com/igorbenav/fastcrud"
},
"split_keywords": [
"fastapi",
" crud",
" async",
" sqlalchemy",
" pydantic"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "cf4d872e2050cf11b26126f55c8b71e18d1dc72ef87287aa5a3d7ca13e1245fe",
"md5": "c250dd81366c36f2352b9a88c4f7044d",
"sha256": "51425f7c941e2dae6df37cdb1ebce5861397aeee112aff9c3a6fda775f999ece"
},
"downloads": -1,
"filename": "fastcrud-0.15.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c250dd81366c36f2352b9a88c4f7044d",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.9",
"size": 51746,
"upload_time": "2024-09-19T01:55:30",
"upload_time_iso_8601": "2024-09-19T01:55:30.898119Z",
"url": "https://files.pythonhosted.org/packages/cf/4d/872e2050cf11b26126f55c8b71e18d1dc72ef87287aa5a3d7ca13e1245fe/fastcrud-0.15.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "9252b2dfbc4638476f1d5aa6995c237c04131a18b3d51c5d684441273eaff8e5",
"md5": "fba4c4f63ad972e650a7b891b8ecd2e5",
"sha256": "b00034d519a20b3487520dbe9498c07e256e28298ad2564b32841014bfb4b750"
},
"downloads": -1,
"filename": "fastcrud-0.15.1.tar.gz",
"has_sig": false,
"md5_digest": "fba4c4f63ad972e650a7b891b8ecd2e5",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.9",
"size": 40168,
"upload_time": "2024-09-19T01:55:33",
"upload_time_iso_8601": "2024-09-19T01:55:33.056307Z",
"url": "https://files.pythonhosted.org/packages/92/52/b2dfbc4638476f1d5aa6995c237c04131a18b3d51c5d684441273eaff8e5/fastcrud-0.15.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-19 01:55:33",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "igorbenav",
"github_project": "fastcrud",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "fastcrud"
}