Skip to main content

Web frameworks · Intermediate · 22 min

Connect FastAPI to a database with SQLModel

By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · FastAPI 0.165 · SQLModel 0.0.50 · SQLAlchemy 2.1

You will move a FastAPI items API from memory into a database with SQLModel, with separate models for input and output, a session per request, tables created at startup, paginated lists and data that survives a restart.

On this page

The items API in build a REST API with FastAPI keeps its data in a Python dictionary. That is fine for learning the framework, but every restart wipes it, and two workers would each hold a different copy. This tutorial puts the same kind of API on a real database.

You will use SQLModel, a library from the author of FastAPI. A SQLModel class is a Pydantic model and an SQLAlchemy table definition at once, so one set of type hints describes the columns, validates requests and shapes responses. Under it sits SQLAlchemy 2.1, which talks to the database. You develop on SQLite, which is a single file and needs no server, and switch to PostgreSQL for production by changing one environment variable.

By the end you have an API with create, read, list, update and delete routes, proper 404 answers, paginated lists, and data that is still there after you stop and start the server.

Step 1 · Create the project and add SQLModel

Make a new project folder and add FastAPI with its standard extras (the fastapi command and the Uvicorn server) and SQLModel. Both are still below version 1, where a minor release may change behaviour, so the ranges allow patch releases only:

Bash
mkdir -p ~/items-db-demo
cd ~/items-db-demo
uv init --no-package
uv add "fastapi[standard]>=0.165,<0.166" "sqlmodel>=0.0.50,<0.0.51"

SQLModel brings SQLAlchemy with it. SQLite support is part of Python itself, so there is no database driver to install yet.

Check it worked

Bash
uv run python -c "import fastapi, sqlmodel, sqlalchemy; print(fastapi.__version__, sqlmodel.__version__, sqlalchemy.__version__)"

The output is 0.165.0 0.0.50 2.1.9, or later patch releases of the same lines.

Step 2 · Define the table and the API models

The in-memory tutorial used one input model and one output model. With a database you need a third kind: the table model, which maps to rows. Keep the three apart, because they answer different questions:

  • What may a client send when creating an item? A title and an optional done flag. Never an id: the database assigns it.
  • What does the API send back? Everything, including the id.
  • What may a client change? Any field, but each one is optional, so a client can mark an item done without resending its title.

Create models.py:

Bash
cat > models.py <<'PY'
from sqlmodel import Field, SQLModel


class ItemBase(SQLModel):
    title: str = Field(min_length=1, max_length=100)
    done: bool = False


class Item(ItemBase, table=True):
    id: int | None = Field(default=None, primary_key=True)


class ItemCreate(ItemBase):
    pass


class ItemPublic(ItemBase):
    id: int


class ItemUpdate(SQLModel):
    title: str | None = Field(default=None, min_length=1, max_length=100)
    done: bool | None = None
PY

ItemBase holds the shared fields once. Only Item has table=True, so it is the only class that becomes a table, named item after the class. Its id is None until the database fills it in on insert. ItemPublic repeats the id as a plain int, which tells clients and the generated docs that a returned item always has one. max_length=100 does double duty: it is checked on requests and becomes VARCHAR(100) in the table.

One thing to know: a table model does not run validation when you construct it directly. Validation happens on the data models (ItemCreate, ItemUpdate) that FastAPI fills from the request body, which is why the routes accept those and never Item itself.

Check it worked

Bash
uv run python -c "from models import Item, ItemCreate; print(Item.__tablename__, sorted(ItemCreate.model_fields))"

The output is item ['done', 'title']. id is not a field a client can set when creating.

Step 3 · Open a session per request and create tables at startup

Create database.py. It builds one engine for the whole app, reads the database address from an environment variable, and provides a session to each request:

Bash
cat > database.py <<'PY'
import os
from collections.abc import Iterator
from typing import Annotated

from fastapi import Depends
from sqlmodel import Session, SQLModel, create_engine

DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///items.db")

connect_args = {}
if DATABASE_URL.startswith("sqlite"):
    connect_args = {"check_same_thread": False}

engine = create_engine(DATABASE_URL, connect_args=connect_args)


def create_tables() -> None:
    SQLModel.metadata.create_all(engine)


def get_session() -> Iterator[Session]:
    with Session(engine) as session:
        yield session


SessionDep = Annotated[Session, Depends(get_session)]
PY
  • The engine holds a pool of database connections. Create it once, at import, and share it.
  • sqlite:///items.db means a file called items.db in the folder you start the server from. Python's sqlite3 module refuses by default to use a connection from a thread other than the one that opened it. FastAPI runs ordinary def routes in a thread pool, so check_same_thread=False turns that check off. Each request still gets its own session, so no two requests share one at the same time. PostgreSQL does not take this option, hence the if.
  • get_session is a dependency with yield. FastAPI runs it up to the yield before your route, hands the session to the route, and runs the rest after the response, which closes the session even when the route raised an error.
  • SessionDep is a short name for "a Session that comes from get_session". A route that declares a parameter of this type gets a fresh session.

Now create main.py with a lifespan handler. Code before its yield runs once when the server starts, before the first request; code after it runs at shutdown:

Bash
cat > main.py <<'PY'
from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import FastAPI, HTTPException, Query, Response, status
from sqlmodel import select

from database import SessionDep, create_tables
from models import Item, ItemCreate, ItemPublic, ItemUpdate


@asynccontextmanager
async def lifespan(app: FastAPI):
    create_tables()
    yield


app = FastAPI(title="Items API", lifespan=lifespan)


@app.get("/api/health")
def health():
    return {"status": "ok"}
PY

create_all looks at every table model that has been imported, which is why main.py imports Item, and creates the tables that do not exist yet. It never changes or drops a table that is already there. Some imports are not used yet; the next steps add the routes that need them.

Start the development server in a second terminal, in the project folder. It reloads when you save a file, so leave it running:

Bash
cd ~/items-db-demo
uv run fastapi dev main.py

Check it worked

The server prints a line like Uvicorn running on http://127.0.0.1:8000, and the project folder now has an items.db file. List the tables in it with Python's built-in sqlite3 module:

Bash
uv run python -c "import sqlite3; print(sqlite3.connect('items.db').execute(\"select name from sqlite_master where type='table'\").fetchall())"

The output is [('item',)].

Step 4 · Create and read items

Add the first two routes to the end of main.py:

Bash
cat >> main.py <<'PY'


@app.post("/api/items", response_model=ItemPublic, status_code=status.HTTP_201_CREATED)
def create_item(data: ItemCreate, session: SessionDep, response: Response):
    item = Item.model_validate(data)
    session.add(item)
    session.commit()
    session.refresh(item)
    response.headers["Location"] = f"/api/items/{item.id}"
    return item


@app.get("/api/items/{item_id}", response_model=ItemPublic)
def read_item(item_id: int, session: SessionDep):
    item = session.get(Item, item_id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item
PY

In create_item, Item.model_validate(data) copies the validated input into a table object. session.add stages it, session.commit writes it in a transaction, and session.refresh reloads it so the id the database chose is on the object. response_model=ItemPublic decides what the client sees.

session.get(Item, item_id) looks a row up by primary key and returns None when there is none. That None check is your 404. Without it, the route would try to return None and the client would get a confusing 500.

Try it, and include an id in the body to see that it is ignored:

Bash
curl -si -w '\n' --json '{"title": "Learn SQLModel", "id": 99}' http://127.0.0.1:8000/api/items
curl -s -w '\n' http://127.0.0.1:8000/api/items/1
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/api/items/42

The first answer starts with HTTP/1.1 201 Created, has location: /api/items/1, and its body is {"title":"Learn SQLModel","done":false,"id":1}: the database gave it id 1, not 99. The second prints the same item. The third prints {"detail":"Item not found"} and 404.

Check it worked

The row is in the file, not just in the server's memory:

Bash
uv run python -c "import sqlite3; print(sqlite3.connect('items.db').execute('select id, title, done from item').fetchall())"

The output is [(1, 'Learn SQLModel', 0)]. SQLite stores booleans as 0 and 1; SQLModel turns them back into false and true for you.

Step 5 · List items with offset and limit

A list route that returns every row works with ten rows and fails with a hundred thousand. Return one page at a time. offset says how many rows to skip and limit how many to return, and the route caps limit so no client can ask for everything at once. Small pages also matter to people on prepaid mobile data or slow connections, where every kilobyte costs money or time.

Append the route:

Bash
cat >> main.py <<'PY'


@app.get("/api/items", response_model=list[ItemPublic])
def list_items(
    session: SessionDep,
    offset: Annotated[int, Query(ge=0)] = 0,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
):
    statement = select(Item).order_by(Item.id).offset(offset).limit(limit)
    return session.exec(statement).all()
PY

select(Item) builds a query, and session.exec(...).all() runs it and returns a list of Item objects. order_by(Item.id) matters: without an order, a database may return rows in any order it likes, and pages could overlap or skip rows.

Add 24 more items so there is something to page through:

Bash
for n in $(seq 2 25); do
  curl -s -o /dev/null --json "{\"title\": \"Item $n\"}" http://127.0.0.1:8000/api/items
done
curl -s -w '\n' 'http://127.0.0.1:8000/api/items?offset=20&limit=3'

The last command prints items 21, 22 and 23.

Check it worked

Bash
curl -s http://127.0.0.1:8000/api/items | python3 -c "import json, sys; print(len(json.load(sys.stdin)))"
curl -s -o /dev/null -w '%{http_code}\n' 'http://127.0.0.1:8000/api/items?limit=0'

The output is 20, the default page size, and then 422, because a limit must be at least 1.

Step 6 · Update and delete with proper 404s

Use PATCH for updates, so a client sends only the fields it wants to change. Append both routes:

Bash
cat >> main.py <<'PY'


@app.patch("/api/items/{item_id}", response_model=ItemPublic)
def update_item(item_id: int, data: ItemUpdate, session: SessionDep):
    item = session.get(Item, item_id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    changes = data.model_dump(exclude_unset=True, exclude_none=True)
    item.sqlmodel_update(changes)
    session.add(item)
    session.commit()
    session.refresh(item)
    return item


@app.delete("/api/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int, session: SessionDep) -> None:
    item = session.get(Item, item_id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    session.delete(item)
    session.commit()
PY

exclude_unset=True keeps only the fields the client actually sent, so a body of {"done": true} leaves the title alone. exclude_none=True drops fields sent as null. Neither column in this table is nullable, so treating null as "no change" avoids a database error. sqlmodel_update copies the remaining values onto the row object. Both routes look the row up first and answer 404 if it is missing, before they change anything.

Bash
curl -s -w '\n' -X PATCH --json '{"done": true}' http://127.0.0.1:8000/api/items/1
curl -s -w '\n%{http_code}\n' -X PATCH --json '{"title": ""}' http://127.0.0.1:8000/api/items/1
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://127.0.0.1:8000/api/items/2
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://127.0.0.1:8000/api/items/2

The first prints {"title":"Learn SQLModel","done":true,"id":1}, with the title unchanged. The second is rejected with 422, because ItemUpdate keeps the same length rules as ItemCreate. The first delete prints 204; the second prints 404, because the item is gone.

Check it worked

Bash
curl -s -o /dev/null -w '%{http_code}\n' -X PATCH --json '{"done": false}' http://127.0.0.1:8000/api/items/999

The output is 404.

Step 7 · Restart the server and check the data is still there

This is the point of the whole exercise. Stop the server with Ctrl+C in the second terminal, then start it again:

Bash
uv run fastapi dev main.py

On startup the lifespan handler runs create_all again. The table already exists, so it leaves it and its rows untouched.

Check it worked

Bash
curl -s -w '\n' http://127.0.0.1:8000/api/items/1
curl -s -w '\n' 'http://127.0.0.1:8000/api/items?offset=22'

The first prints {"title":"Learn SQLModel","done":true,"id":1}, the change you made before the restart. The second prints items 24 and 25: 25 created, one deleted, and the first 22 skipped.

Step 8 · Point the app at PostgreSQL for production

SQLite is a good fit for development, tests and small single-server tools. For an API with several workers or several servers writing at once, use PostgreSQL. The code does not change; only DATABASE_URL does. Add the psycopg driver first:

Bash
uv add "psycopg[binary]>=3.3,<3.4"

On the server, the address looks like this. Replace the user, host and database name with your own:

Text
postgresql+psycopg://items_app@127.0.0.1:5432/items

postgresql+psycopg tells SQLAlchemy to use psycopg 3. There is no password in the URL on purpose: an address in an environment variable ends up in process listings and error reports. psycopg uses libpq, which reads the password from ~/.pgpass of the user that runs the app, a file that must be readable by that user only. Create it private from the start:

Bash
install -m 600 /dev/null ~/.pgpass
nano ~/.pgpass

Put one line in it, in the form 127.0.0.1:5432:items:items_app:<password>, with your own password. Then start the app with the address set:

Bash
DATABASE_URL='postgresql+psycopg://items_app@127.0.0.1:5432/items' uv run fastapi run main.py --port 8000

On a server you would set DATABASE_URL in the service's environment rather than on the command line each time. Install PostgreSQL 18 on Ubuntu 26.04 covers creating the database and user.

create_all is fine for a first deployment, but it never alters a table that exists. Once real data is in production and you add or rename a column, use a migration tool such as Alembic, which works with SQLModel's metadata, instead of dropping tables.

Check it worked

Confirm the app reads the variable, without connecting to anything (creating an engine does not open a connection):

Bash
DATABASE_URL='postgresql+psycopg://items_app@127.0.0.1:5432/items' uv run python -c "from database import engine; print(engine.dialect.name, engine.dialect.driver)"

The output is postgresql psycopg.

Step 9 · Stop the server and clean up

Press Ctrl+C in the server terminal. The demo folder holds only what you created here, including items.db, so delete it:

Bash
cd ~
rm -rf ~/items-db-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.