DEV Community

Cover image for Fastapi-SQLA now supports SQLModel 🎉
Hadrien
Hadrien

Posted on

Fastapi-SQLA now supports SQLModel 🎉

Fastapi-SQLA is an SQLAlchemy extension for FastAPI with support for pagination, asyncio, pytest and now: SQLModel!

Here is a quick example:

    from http import HTTPStatus

    from fastapi import FastAPI, HTTPException
    from fastapi_sqla import Item, Page, Paginate, Session, setup
    from sqlmodel import Field, SQLModel, select


    class Hero(SQLModel, table=True):
        id: int | None = Field(default=None, primary_key=True)
        name: str
        secret_name: str
        age: int | None = None


    app = FastAPI()
    setup(app)

    @app.get("/heros", response_model=Page[Hero])
    def list_hero(paginate: Paginate) -> Page[Hero]:
        return paginate(select(Hero))


    @app.get("/heros/{hero_id}", response_model=Item[Hero])
    def get_hero(hero_id: int, session: Session) -> Item[Hero]:
        hero = session.get(Hero, hero_id)
        if hero is None:
            raise HTTPException(HTTPStatus.NOT_FOUND)
        return {"data": hero}

Enter fullscreen mode Exit fullscreen mode

Enjoy!

Top comments (0)