Package: fastcrud
Powerful CRUD methods and automatic endpoint creation for FastAPI.FastCRUDis a Python package forFastAPI, offering robust async CRUD operations and flexible endpoint creation utilities, streamlined through advanced features likeauto-detected joinconditions,dynamic sorting, and offset and cursorpagination.Documentation:igorbenav.github.io/fastcrudFeatures⚡️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.RequirementsBefore 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.InstallingTo install, just run:pipinstallfastcrudOr, if using poetry:poetryaddfastcrudUsageFastCRUD offers two primary ways to use its functionalities:By usingcrud_routerfor automatic endpoint creation.By integratingFastCRUDdirectly 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 namedidor automatic endpoint creation will not work.Here's a quick example to get you started:Define Your Model and Schemamodels.pyfromsqlalchemyimportColumn,Integer,Stringfromsqlalchemy.ormimportDeclarativeBaseclassBase(DeclarativeBase):passclassItem(Base):__tablename__='items'id=Column(Integer,primary_key=True)name=Column(String)description=Column(String)schemas.pyfrompydanticimportBaseModelclassItemCreateSchema(BaseModel):name:strdescription:strclassItemUpdateSchema(BaseModel):name:strdescription:strSet Up FastAPI and FastCRUDmain.pyfromtypingimportAsyncGeneratorfromfastapiimportFastAPIfromfastcrudimportFastCRUD,crud_routerfromsqlalchemy.ext.asyncioimportAsyncSession,create_async_enginefromsqlalchemy.ormimportsessionmakerfromyourapp.modelsimportBase,Itemfromyourapp.schemasimportItemCreateSchema,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 dependencyasyncdefget_session()->AsyncGenerator[AsyncSession,None]:asyncwithasync_session()assession:yieldsession# Create tables before the app startasyncdeflifespan(app:FastAPI):asyncwithengine.begin()asconn:awaitconn.run_sync(Base.metadata.create_all)yield# FastAPI appapp=FastAPI(lifespan=lifespan)# CRUD operations setupcrud=FastCRUD(Item)# CRUD router setupitem_router=crud_router(session=get_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 EndpointsFor more control over your endpoints, you can use FastCRUD directly within your custom FastAPI route functions. Here's an example:main.pyfromtypingimportAsyncGeneratorfromfastapiimportFastAPI,Depends,HTTPExceptionfromsqlalchemy.ext.asyncioimportAsyncSession,create_async_enginefromsqlalchemy.ormimportsessionmakerfromfastcrudimportFastCRUDfrommodelsimportBase,ItemfromschemasimportItemCreateSchema,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 dependencyasyncdefget_session()->AsyncGenerator[AsyncSession,None]:asyncwithasync_session()assession:yieldsession# Create tables before the app startasyncdeflifespan(app:FastAPI):asyncwithengine.begin()asconn:awaitconn.run_sync(Base.metadata.create_all)yield# FastAPI appapp=FastAPI(lifespan=lifespan)# Instantiate FastCRUD with your modelitem_crud=FastCRUD(Item)@app.post("/custom/items/")asyncdefcreate_item(item_data:ItemCreateSchema,db:AsyncSession=Depends(get_session)):returnawaititem_crud.create(db,item_data)@app.get("/custom/items/{item_id}")asyncdefread_item(item_id:int,db:AsyncSession=Depends(get_session)):item=awaititem_crud.get(db,id=item_id)ifnotitem:raiseHTTPException(status_code=404,detail="Item not found")returnitem# You can add more routes for update and delete operations in a similar fashionIn 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 thedocumentation.ReferencesThis project was heavily inspired by CRUDBase inFastAPI Microservicesby@kludex.Thanks@ada0lfor the PyPI package name!Similar Projectsflask-muck-"I'd love something like this for flask"There you have itFastAPI CRUD Router- Supports multiple ORMs, but currently unmantainedFastAPI Quick CRUD- Same purpose, but only for SQLAlchemy 1.4LicenseMITContactIgor Magalhaes –@igormagalhaesr–igormagalhaesr@gmail.comgithub.com/igorbenav