Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Databases

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Databases

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

GET /api/books/2 goes down four boxes: the route takes HTTP in and sends JSON out, the service holds the rules, the repository does the database work with SQLAlchemy, and the book table answers. The Book object travels back up and leaves as JSON. Route (routers/books.py) HTTP in, JSON out Service (BookService) our rules Repository (BookRepository) database work, SQLAlchemy writes SQL SQLite: table book id, title, author, pages, shelf_code GET /api/books/2 200, JSON down up
The request goes down one layer at a time; the book travels back up and leaves as JSON.

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:

RequestSQL sent
GET /api/booksSELECT book.id, book.title, book.author, book.pages, book.shelf_code FROM book
GET /api/books/2the same SELECT WHERE book.id = ?, parameters (2,)
POST MatildaINSERT INTO book (title, author, pages, shelf_code) VALUES (?, ?, ?, ?), then COMMIT
PUT /api/books/2SELECT by id, then UPDATE book SET title=?, pages=? WHERE book.id = ?, then COMMIT
DELETE /api/books/3SELECT 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

RequestStatus
GET all books200
GET one book200
POST Matilda201, Location /api/books/4
PUT book 2200
DELETE book 3204
a book that isn't there404

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_code shows.

Quick recap

LayerFileJob
Routerouters/books.pyHTTP in, JSON out, status codes
Serviceservices/book_service.pyrules, like never copying shelf_code
Repositoryrepositories/book_repository.pyselect, get, add, delete, commit
Modelmodels.pyone class, one table
SQLAlchemydatabase.pywrites 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 22 of 26

Previous
FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
Next post
Docker Compose: Run a FastAPI App and Postgres From One File

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.

On this page

  • Three layers, one job each
  • The database setup
  • One class, one table
  • The repository: no SQL written by us
  • The service keeps the rules
  • The route wires it together
  • SQLAlchemy turns each call into SQL
  • The rule shows up in the SQL
  • Same conversation from outside
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.