From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
Move a FastAPI Book API from an in-memory list to SQLite without changing a single URL. Three layers (route, service, repository), a SQLAlchemy model, and the real SQL each request sends with echo=True.
What you will learn
- Explain why data that must last belongs in a database, not a list
- Split a FastAPI app into a route, a service and a repository, each with one job
- Map a SQLAlchemy model to a table and its calls to the SQL it sends
- Keep a business rule in the service and see it in the UPDATE statement
Before you start
- FastAPI POST, PUT and DELETE routes
- SQL basics: SELECT, INSERT, UPDATE, DELETE
- FastAPI Depends
So far the Book API kept its books in a Python list. A list lives in the memory of the running program, so when the app stops, the list is gone. Data that must last belongs in a database, which keeps it in tables.
This article moves the books into SQLite. The nice part: from outside, nothing changes. Same URLs, same status codes as in POST, PUT and DELETE in FastAPI. Inside, a service, a repository, a SQLAlchemy model and the SQL it sends all take their place. (In this lesson SQLite runs in memory too, which is fine for learning; a real database keeps its data on disk. The code stays the same.)
Three layers, one job each
The route takes HTTP in and sends JSON out. The service holds our rules. The repository does the database work. At the bottom sits the book table. The route asks the service for the book by id, the service asks the repository, and the repository, with SQLAlchemy, sends SQL.
The database setup
library/database.py:
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
from sqlalchemy.pool import StaticPool
# SQLite in memory: gone when the app stops. echo=True prints every SQL statement.
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
echo=True,
)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
def get_db():
with SessionLocal() as db: # one session per request, closed at the end
yield db
echo=True is what lets us see every SQL statement below. get_db gives each request its own session and closes it at the end. At startup, a lifespan function in main.py calls seed_books(), which runs Base.metadata.create_all(engine) and adds the three first books.
One class, one table
library/models.py:
from sqlalchemy.orm import Mapped, mapped_column
from library.database import Base
class Book(Base):
__tablename__ = "book"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str]
author: Mapped[str]
pages: Mapped[int]
shelf_code: Mapped[str] = mapped_column(default="NEW-ARRIVALS") # internal: where the book stands
The class extends Base, __tablename__ names the table, and each Mapped line is a column. shelf_code is an internal column for the staff. One class is one table; one Book object is one row. (For the same mapping in the blog track, plus Alembic migrations, see FastAPI with SQLAlchemy models and Alembic.)
The repository: no SQL written by us
from sqlalchemy import select
from sqlalchemy.orm import Session
from library.models import Book
class BookRepository:
def __init__(self, db: Session):
self.db = db
def find_all(self) -> list[Book]:
return list(self.db.scalars(select(Book)))
def find_by_id(self, book_id: int) -> Book | None:
return self.db.get(Book, book_id)
def save(self, book: Book) -> Book:
self.db.add(book)
self.db.commit()
return book
def delete(self, book: Book) -> None:
self.db.delete(book)
self.db.commit()
Four methods: find_all, find_by_id, save and delete. select(Book) and db.get(Book, book_id) say what we want, and SQLAlchemy writes the SQL.
The service keeps the rules
class BookService:
def __init__(self, repository: BookRepository):
self.repository = repository
def list_all(self) -> list[Book]:
return self.repository.find_all()
def get(self, book_id: int) -> Book | None:
return self.repository.find_by_id(book_id)
def create(self, book: Book) -> Book:
return self.repository.save(book)
def replace(self, book_id: int, changes: Book) -> Book | None:
book = self.repository.find_by_id(book_id)
if book is None:
return None
book.title, book.author, book.pages = changes.title, changes.author, changes.pages
return self.repository.save(book)
def delete(self, book_id: int) -> bool:
book = self.repository.find_by_id(book_id)
if book is None:
return False
self.repository.delete(book)
return True
Look at replace. It copies the title, author and pages from the new version, and that's all. The shelf code is never touched, so a client can't change it. That's a rule, and rules live in the service: not in the route, not in the database.
The route wires it together
def get_service(db: Session = Depends(get_db)) -> BookService:
return BookService(BookRepository(db))
@router.get("/{book_id}", response_model=Book, summary="One book", operation_id="one")
def get_book(book_id: int, service: BookService = Depends(get_service)):
book = service.get(book_id)
if book is None:
raise HTTPException(status_code=404, detail="Book not found")
return book
@router.post("", response_model=Book, status_code=201, summary="Add a book", operation_id="create")
def add_book(book: Book, response: Response, service: BookService = Depends(get_service)):
saved = service.create(models.Book(**book.model_dump(exclude={"id"})))
response.headers["Location"] = f"/api/books/{saved.id}"
return saved
get_service builds a service on top of a repository on top of the request's session, and Depends hands it to each route. The route still owns the HTTP parts: the 404, the 201 and the Location header. Note there are now two Book classes: library.schemas.Book (Pydantic, the JSON) and models.Book (SQLAlchemy, the row). The schema has from_attributes=True so it can be filled from a row.
SQLAlchemy turns each call into SQL
With echo=True, the run captured the SQL for each request:
| Request | SQL sent |
|---|---|
GET /api/books | SELECT book.id, book.title, book.author, book.pages, book.shelf_code FROM book |
GET /api/books/2 | the same SELECT WHERE book.id = ?, parameters (2,) |
POST Matilda | INSERT INTO book (title, author, pages, shelf_code) VALUES (?, ?, ?, ?), then COMMIT |
PUT /api/books/2 | SELECT by id, then UPDATE book SET title=?, pages=? WHERE book.id = ?, then COMMIT |
DELETE /api/books/3 | SELECT by id, then DELETE FROM book WHERE book.id = ?, then COMMIT |
Here are two of them exactly as captured. The POST:
BEGIN (implicit)
INSERT INTO book (title, author, pages, shelf_code) VALUES (?, ?, ?, ?)
-- parameters: ('Matilda', 'Roald Dahl', 240, 'NEW-ARRIVALS')
COMMIT
And the DELETE, which takes two statements: a SELECT to load the book, then the delete itself:
BEGIN (implicit)
SELECT book.id, book.title, book.author, book.pages, book.shelf_code
FROM book
WHERE book.id = ?
-- parameters: (3,)
DELETE FROM book WHERE book.id = ?
-- parameters: (3,)
COMMIT
The question marks are parameters, filled in by the database driver, so values never get pasted into the SQL text. Read-only requests end with ROLLBACK, because nothing was changed.
The rule shows up in the SQL
The PUT sends Dune Messiah, same author, 256 pages:
UPDATE book SET title=?, pages=? WHERE book.id = ?
-- parameters: ('Dune Messiah', 256, 2)
Only the title and the pages changed, so SQLAlchemy updates only those two columns. The author is the same, and the shelf code is never copied, so the answer still says "shelf_code":"NEW-ARRIVALS".
Same conversation from outside
| Request | Status |
|---|---|
| GET all books | 200 |
| GET one book | 200 |
| POST Matilda | 201, Location /api/books/4 |
| PUT book 2 | 200 |
| DELETE book 3 | 204 |
| a book that isn't there | 404 |
Inside changed; the conversation didn't. One thing slipped out, though. GET /api/books/2 now answers:
{"id":2,"title":"Dune","author":"Frank Herbert","pages":412,"shelf_code":"NEW-ARRIVALS"}
The staff-only shelf_code is visible to every client. The fix is separate request and response models, in FastAPI request and response models with Pydantic.
Common mistakes
- SQL or session code in the route. Keep HTTP in the route, rules in the service, database work in the repository.
- Mixing up the two Book classes. One is the JSON shape (Pydantic), the other is the row (SQLAlchemy).
- Forgetting
commit(). Without it, the insert, update or delete is rolled back when the session closes. - Returning the row and hoping internal columns stay hidden. They don't, as
shelf_codeshows.
Quick recap
| Layer | File | Job |
|---|---|---|
| Route | routers/books.py | HTTP in, JSON out, status codes |
| Service | services/book_service.py | rules, like never copying shelf_code |
| Repository | repositories/book_repository.py | select, get, add, delete, commit |
| Model | models.py | one class, one table |
| SQLAlchemy | database.py | writes the SQL; echo=True shows it |
Try it yourself
Run the app, send the requests in requests.http and watch the SQL in the console. Then change the PUT body so only the author differs, and predict the UPDATE statement before you send it.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
A Post model in SQLAlchemy 2, an engine and a get_db dependency that yields one session per request, then Alembic turns the model into a posts table and shows its SQL before running it. Three timed routes show when async def helps: 3.0 s with a blocking call, 1.0 s with def or await.
Docker Compose: Run a FastAPI App and Postgres From One File
A notes API in FastAPI plus Postgres, described in one compose.yaml: the service name as the database host, a named volume, a pg_isready healthcheck with depends_on, and a real run showing notes surviving docker compose down but not down -v.
Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
Make a FastAPI plus Postgres Compose stack ready for a server: config from the environment, logs to stdout, a /health route behind HEALTHCHECK that turns the API unhealthy when the database stops, an internal network that hides the database, and a 256 MB limit that kills a 400 MB allocation with exit code 137.
