Skip to content

Move to a domain layout and a database

On this page you move shop to the domain level, where the items live in a SQL database. You learn how FastAPI works with an async SQL database through SQLAlchemy, how a dependency with yield gives each request a database session and cleans up after it, what lifespan events are, and how a domain package splits one resource into router, service and repository. You also use fastkit's --database option, the Alembic migrations option, the "Selected features" sections of the generated README and fastkit addroute in a domain project.

A new project at the next level

fastkit does not convert a project to another level. You create a new project and move your own code into it. Do this in another folder than the layered shop, because the new project is also called shop:

$ fastkit init --level domain --name shop --database SQLite --feature migrations=Alembic --no-venv -y
...
│ Database        │ SQLite                                                     │
│ Features        │ Testing: Coverage; Migrations: Alembic                     │
...

SQLite keeps the whole database in one file and needs no server, so it suits development. The Alembic option adds database migrations; Testing: Coverage is the test setup with pytest-cov that every level after hello has. README.md has a section for each of them under "Selected features": what it does, the files it added and the settings it reads. The new files:

$ cd shop
$ find src alembic -type f -not -name '__init__.py' | sort
alembic/env.py
alembic/script.py.mako
alembic/versions/182fb3ba8f64_initial.py
...
src/app/core/database.py
...
src/app/domains/items/models.py
src/app/domains/items/repository.py
src/app/domains/items/router.py
src/app/domains/items/schemas.py
src/app/domains/items/service.py
src/app/features/readiness.py
src/app/main.py

One domain: items

A domain package keeps everything about one resource in one folder. In src/app/domains/items/, router.py handles HTTP, service.py holds the rules, repository.py runs the SQL, models.py describes the table and schemas.py the JSON. The router gets the service from a dependency, get_item_service(session: SessionDep), which wraps the request's database session in an ItemRepository and that in an ItemService. The service raises its own error when an item is missing, and the router turns it into a 404. The handlers are async def and await the database: while one request waits for the database, the server handles other requests. The repository is the only place with SQL:

src/app/domains/items/repository.py
    async def add(self, name: str, price: float, in_stock: bool = True) -> Item:
        """Store a new item and commit; the database hands out its id."""
        item = Item(name=name, price=price, in_stock=in_stock)
        self.session.add(item)
        await self.session.commit()
        await self.session.refresh(item)
        return item

The database session

SQLAlchemy's engine keeps a pool of database connections. A session borrows one connection for a unit of work. src/app/core/database.py creates both and hands a session to each request:

src/app/core/database.py
# A dependency with `yield` gives the endpoint a session and closes it afterwards.
# https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/
async def get_db() -> AsyncIterator[AsyncSession]:
    """Yield one session per request and roll it back if the request fails."""
    async with SessionLocal() as session:
        try:
            yield session
        except Exception:
            await session.rollback()
            raise


#: ``session: SessionDep`` in an endpoint or service dependency signature.
SessionDep = Annotated[AsyncSession, Depends(get_db)]


# A lifespan runs its code after `yield` once, when the application shuts down.
# https://fastapi.tiangolo.com/advanced/events/
@asynccontextmanager
async def engine_lifespan(_app: FastAPI) -> AsyncIterator[None]:
    """Dispose of the connection pool when the application shuts down."""
    try:
        yield
    finally:
        await engine.dispose()

FastAPI runs a dependency with yield up to the yield, passes the yielded value to the endpoint, and runs the rest after the response. Here that rest rolls back the work the session has not committed yet when an exception passes through, and async with always closes the session. It does not undo a whole request: each repository method commits its own change (await self.session.commit()), and what it has committed stays committed. A lifespan works the same way for the whole application: the code before yield runs at startup, the code after it at shutdown. src/app/main.py adds this lifespan with app.include_router(database_lifespan). The URL of the database comes from the setting DATABASE_URL, which defaults to sqlite+aiosqlite:///./app.db.

Create the tables

Alembic creates and changes the tables with migration scripts in alembic/versions/. The first script creates the items table:

$ uv sync -q
$ uv run alembic upgrade head
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 182fb3ba8f64, initial revision

When you change a model later, the README's Alembic section shows how to record the change: alembic revision --autogenerate -m "add orders". An autogenerated revision is a draft: read and test it before it runs against real data, because Alembic guesses some changes wrong (a renamed column, for example, comes out as a dropped column plus a new one).

Items survive a restart

Start the server with uv run uvicorn src.app.main:app. In a second terminal, create an item:

$ curl -s -X POST http://127.0.0.1:8000/api/v1/items -H "Content-Type: application/json" -d '{"name": "Lamp", "price": 25.5}'
{"id":1,"name":"Lamp","price":25.5,"in_stock":true}

Stop the server with Ctrl+C, start it again and list the items. The lamp is still there, and /ready answers ok because the database responds:

$ curl -s http://127.0.0.1:8000/api/v1/items
{"items":[{"id":1,"name":"Lamp","price":25.5,"in_stock":true}],"total":1,"limit":20,"offset":0}
$ curl -s http://127.0.0.1:8000/ready
{"status":"ok"}

Bring users over

fastkit addroute works in a domain project too and creates a domain package:

$ fastkit addroute users .
...
Files to create (7):
  + src/app/domains/users/__init__.py
...
  + tests/test_users.py
Files to modify (1):
  ~ src/app/api/router.py
Note: users keeps its records in memory (src/app/domains/users/repository.py); src/app/domains/items/ shows the SQL-backed version (model, repository, service and router); an Alembic revision in alembic/versions/ creates its table.

Do you want to add route 'users' to the current project? [Y/n]: y
...

To give users a table, follow the items files the note names. Your own test from Test moves over with new imports, because here the endpoints get a UserService from get_user_service. Change these lines; the rest of the file stays the same, and all 91 tests pass:

tests/test_users_override.py
from src.app.domains.users.repository import UserRepository
from src.app.domains.users.router import get_user_service
from src.app.domains.users.service import UserService
from src.app.main import app
# ...
    app.dependency_overrides[get_user_service] = lambda: UserService(repository)

Switch to PostgreSQL

PostgreSQL is a database server, so you run one, for example in Docker. Then install its async driver, asyncpg, and point DATABASE_URL at the server:

$ docker run -d --name shop-db -e POSTGRES_USER=shop -e POSTGRES_PASSWORD=shop -e POSTGRES_DB=shop -p 5432:5432 postgres:16-alpine
0acce6b1c7b75671fb3d42ef3bd279825c9a256825131db2a0bc70b0206b3ba0
$ uv add asyncpg
...
 + asyncpg==0.32.0

Add the line DATABASE_URL=postgresql+asyncpg://shop:shop@localhost:5432/shop to .env. The URL has the form postgresql+asyncpg://USER:PASSWORD@HOST:PORT/DATABASE. alembic upgrade head creates the tables in the new, empty database; the rows in the SQLite file app.db are not copied. Create the tables, start the server again and create an item:

$ uv run alembic upgrade head
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 182fb3ba8f64, initial revision
$ curl -s -X POST http://127.0.0.1:8000/api/v1/items -H "Content-Type: application/json" -d '{"name": "Desk", "price": 120}'
{"id":1,"name":"Desk","price":120.0,"in_stock":true}
$ docker exec shop-db psql -U shop -c "SELECT * FROM items;"
 id | name | price | in_stock
----+------+-------+----------
  1 | Desk |   120 | t
(1 row)

No Python code changed. The tests still run on an in-memory SQLite database (conftest.py at the project root sets that before the app is imported), so uv run pytest needs no server. When you are done, docker rm -f -v shop-db removes the container and its data.

FastAPI documentation

Next

Deploy to production creates shop at the production level, with sign-in, structured logs and containers.