Skip to content

Ormar

FastAPI Users provides the necessary tools to work with ormar.

Installation

Install the database driver that corresponds to your DBMS:

pip install asyncpg psycopg2
pip install aiomysql pymysql
pip install aiosqlite

For the sake of this tutorial from now on, we'll use a simple SQLite database.

Setup User table

Let's declare our User ORM model.

import databases
import sqlalchemy
from fastapi_users.db import OrmarBaseUserModel, OrmarUserDatabase

from .models import UserDB

DATABASE_URL = "sqlite:///test.db"
metadata = sqlalchemy.MetaData()
database = databases.Database(DATABASE_URL)


class UserModel(OrmarBaseUserModel):
    class Meta:
        tablename = "users"
        metadata = metadata
        database = database


engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)


async def get_user_db():
    yield OrmarUserDatabase(UserDB, UserModel)

As you can see, FastAPI Users provides an abstract model that will include base fields for our User table. You can of course add you own fields there to fit to your needs!

Create the database adapter

The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency.

import databases
import sqlalchemy
from fastapi_users.db import OrmarBaseUserModel, OrmarUserDatabase

from .models import UserDB

DATABASE_URL = "sqlite:///test.db"
metadata = sqlalchemy.MetaData()
database = databases.Database(DATABASE_URL)


class UserModel(OrmarBaseUserModel):
    class Meta:
        tablename = "users"
        metadata = metadata
        database = database


engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)


async def get_user_db():
    yield OrmarUserDatabase(UserDB, UserModel)

Notice that we pass a reference to your UserDB model.

Warning

In production, it's strongly recommended to setup a migration system to update your SQL schemas. See Alembic.

Back to top