github benavlabs/fastcrud v0.4.0
0.4.0

latest releases: v0.23.0, v0.22.3, v0.22.2...
2 years ago

0.4.0 Summary

Added

  • tests and docs for SQLModel support
  • py.typed for typing support

Detailed

Since SQLModel is just a combination of SQLAlchemy and Pydantic, the process simplifies as SQLModel combines the model and schema definitions.

Wherever in the docs you see a SQLAlchemy model or Pydantic schema being used, you may just replace it with SQLModel and it will work. For the quick start:

Define your SQLModel model

from sqlmodel import SQLModel, Field
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession

class Item(SQLModel):
    __tablename__ = 'items'
    id: int = Field(primary_key=True)
    name: str

class ItemCreateSchema(SQLModel):
    name: str

DATABASE_URL = "sqlite+aiosqlite:///./test.db"
engine = create_async_engine(DATABASE_URL, echo=True)
session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

Then your schemas

from sqlmodel import SQLModel, Field
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession

class Item(SQLModel):
    __tablename__ = 'items'
    id: int = Field(primary_key=True)
    name: str

class ItemCreateSchema(SQLModel):
    name: str

DATABASE_URL = "sqlite+aiosqlite:///./test.db"
engine = create_async_engine(DATABASE_URL, echo=True)
session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

And, finally, your database connection

from sqlmodel import SQLModel, Field
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession

class Item(SQLModel):
    __tablename__ = 'items'
    id: int = Field(primary_key=True)
    name: str

class ItemCreateSchema(SQLModel):
    name: str

DATABASE_URL = "sqlite+aiosqlite:///./test.db"
engine = create_async_engine(DATABASE_URL, echo=True)
session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

Use crud_router and include it in your FastAPI application

from fastcrud import FastCRUD, crud_router

app = FastAPI()

item_router = crud_router(
    session=session,
    model=Item,
    crud=FastCRUD(Item),
    create_schema=ItemSchema,
    update_schema=ItemSchema,
    path="/items",
    tags=["Items"]
)

app.include_router(item_router)

By following the above setup, FastCRUD auto-generates CRUD endpoints for your model, accessible through the /docs route of your FastAPI application.

What's Changed

Full Changelog: v0.3.0...v0.4.0

Don't miss a new fastcrud release

NewReleases is sending notifications on new releases.