- Create database model
Important
Model must have primary key id
field to create CRUD for it with Crudly
database/models.py
:
from sqlmodel import SQLModel, Field
class Post(SQLModel, table=True):
id: int = Field(primary_key=True, nullable=False)
title: str = Field(nullable=False)
text: str = Field(nullable=False)
- Create database async session generator
database/session.py
:
from typing import AsyncGenerator
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = # URL to database
engine: AsyncEngine = create_async_engine(DATABASE_URL)
session_maker = sessionmaker(
bind=engine, class_=AsyncSession, autoflush=False, expire_on_commit=False
)
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
yield session_maker()
- Create FastAPI app and include Crudly router to it
Note
Crudly creates router without prefix
app.py
:
from fastapi import FastAPI
from crudly import Crudly
from database.models import Post
from database.session import get_db_session
from schemas.posts import PostCreateSchema, PostUpdateSchema
app = FastAPI()
app.include_router(
router=Crudly(
model=Post,
create_schema=PostCreateSchema,
update_schema=PostUpdateSchema,
db_session_generator=get_db_session
),
prefix="/posts",
tags=["Posts"]
)
See LICENSE
See CONTRIBUTING
Project inspired by igorbenav/FastCRUD