Python Labs · Lab 3 of 6

A Tested REST API with FastAPI and SQLAlchemy

Build a small product catalog API with FastAPI, SQLAlchemy and SQLite: validated input, proper status codes, a dependency-injected database session and tests that use their own in-memory database.

Environment
Local
Level
Intermediate
Time
About 50 min
Cost
Free

You will build

A catalog API with create, list, get and delete endpoints for products, tested with FastAPI's TestClient and exercised with curl, ready to move into a container in the next lab.

Members can save this page, take notes and track progress. See membership · Sign in

SQLAlchemy keeps the database behind one URL, so the same code runs on SQLite today and on Postgres in the next
lab with no changes.

The output below was recorded with uv 0.13.10 and Python 3.12. Newer versions print newer version numbers and timings; everything else should match. The finished-project download leaves out uv.lock: uv sync creates it.

Project structure

catalog/
├── .gitignore
├── .python-version
├── README.md
├── pyproject.toml
├── uv.lock
├── src/
│   └── catalog/
│       ├── __init__.py
│       ├── db.py          # engine, session, Base
│       ├── models.py      # database tables
│       ├── schemas.py     # API input and output
│       └── main.py        # routes
└── tests/
    ├── conftest.py        # a fresh database per test
    └── test_products.py

Download starter filesDownload finished project

Steps

  1. 1Create the project and add dependencies

    httpx2 is what FastAPI's test client uses to make requests. (Older guides say httpx; current Starlette warns about it.)

    Run
    uv init --package catalog
    cd catalog
    uv add fastapi uvicorn sqlalchemy
    uv add --dev pytest httpx2 ruff
    
    Check:

    The installed packages include fastapi, pydantic, sqlalchemy and uvicorn.

    Hint

    Delete [project.scripts] from pyproject.toml: this project is a web service, not a command.

  2. 2Connect to the database

    The database URL comes from the environment, with SQLite as a development default. get_session is a FastAPI dependency: each request gets its own session, closed when the request ends.

    src/catalog/db.py
    import os
    from collections.abc import Iterator
    
    from sqlalchemy import create_engine
    from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
    
    DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./catalog.db")
    # SQLite objects can only be used on the thread that made them unless this is off; FastAPI uses a thread pool.
    connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}
    engine = create_engine(DATABASE_URL, connect_args=connect_args)
    SessionLocal = sessionmaker(engine, expire_on_commit=False)
    
    
    class Base(DeclarativeBase):
        pass
    
    
    def get_session() -> Iterator[Session]:
        with SessionLocal() as session:
            yield session
    
  3. 3Define the table

    Prices are stored as integer cents: exact, and the same in every database.

    src/catalog/models.py
    from sqlalchemy import String
    from sqlalchemy.orm import Mapped, mapped_column
    
    from catalog.db import Base
    
    
    class Product(Base):
        __tablename__ = "products"
    
        id: Mapped[int] = mapped_column(primary_key=True)
        name: Mapped[str] = mapped_column(String(200))
        price_cents: Mapped[int]
    
  4. 4Define what the API accepts and returns

    Pydantic models validate input before your code runs. from_attributes lets the response model read a SQLAlchemy object. Keeping API schemas separate from tables means you can change one without the other.

    src/catalog/schemas.py
    from pydantic import BaseModel, ConfigDict, Field
    
    
    class ProductIn(BaseModel):
        name: str = Field(min_length=1, max_length=200)
        price_cents: int = Field(ge=0)
    
    
    class ProductOut(ProductIn):
        model_config = ConfigDict(from_attributes=True)
    
        id: int
    
  5. 5Write the routes

    src/catalog/main.py
    from contextlib import asynccontextmanager
    from typing import Annotated
    
    from fastapi import Depends, FastAPI, HTTPException, Response, status
    from sqlalchemy import select
    from sqlalchemy.orm import Session
    
    from catalog.db import Base, engine, get_session
    from catalog.models import Product
    from catalog.schemas import ProductIn, ProductOut
    
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        Base.metadata.create_all(engine)  # fine for a lab; production uses migrations
        yield
    
    
    app = FastAPI(title="Catalog", lifespan=lifespan)
    SessionDep = Annotated[Session, Depends(get_session)]
    
    
    @app.get("/healthz")
    def healthz() -> dict:
        return {"status": "ok"}
    
    
    @app.post("/products", status_code=status.HTTP_201_CREATED, response_model=ProductOut)
    def create_product(body: ProductIn, session: SessionDep) -> Product:
        product = Product(**body.model_dump())
        session.add(product)
        session.commit()
        return product
    
    
    @app.get("/products", response_model=list[ProductOut])
    def list_products(session: SessionDep) -> list[Product]:
        return list(session.scalars(select(Product).order_by(Product.id)))
    
    
    @app.get("/products/{product_id}", response_model=ProductOut)
    def get_product(product_id: int, session: SessionDep) -> Product:
        product = session.get(Product, product_id)
        if product is None:
            raise HTTPException(status_code=404, detail="Product not found")
        return product
    
    
    @app.delete("/products/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
    def delete_product(product_id: int, session: SessionDep) -> Response:
        product = session.get(Product, product_id)
        if product is None:
            raise HTTPException(status_code=404, detail="Product not found")
        session.delete(product)
        session.commit()
        return Response(status_code=status.HTTP_204_NO_CONTENT)
    
  6. 6Give every test its own database

    The fixture replaces the get_session dependency with one that uses a fresh in-memory SQLite database, so tests never touch catalog.db and never affect each other.

    tests/conftest.py
    import pytest
    from fastapi.testclient import TestClient
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.pool import StaticPool
    
    from catalog.db import Base, get_session
    from catalog.main import app
    
    
    @pytest.fixture
    def client():
        # A fresh in-memory database per test; StaticPool shares the one connection across threads.
        engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
        Base.metadata.create_all(engine)
        TestSession = sessionmaker(engine, expire_on_commit=False)
    
        def override():
            with TestSession() as session:
                yield session
    
        app.dependency_overrides[get_session] = override
        yield TestClient(app)
        app.dependency_overrides.clear()
    
  7. 7Test the behaviour, including failures

    tests/test_products.py
    def test_create_and_get(client):
        created = client.post("/products", json={"name": "Mug", "price_cents": 1299})
        assert created.status_code == 201
        product = created.json()
        assert product == {"id": 1, "name": "Mug", "price_cents": 1299}
        assert client.get("/products/1").json() == product
    
    
    def test_list_is_ordered(client):
        for name in ("A", "B"):
            client.post("/products", json={"name": name, "price_cents": 100})
        assert [p["name"] for p in client.get("/products").json()] == ["A", "B"]
    
    
    def test_validation_rejects_negative_price(client):
        r = client.post("/products", json={"name": "Bad", "price_cents": -1})
        assert r.status_code == 422
    
    
    def test_missing_product_is_404(client):
        assert client.get("/products/42").status_code == 404
    
    
    def test_delete(client):
        client.post("/products", json={"name": "Temp", "price_cents": 1})
        assert client.delete("/products/1").status_code == 204
        assert client.get("/products/1").status_code == 404
    
  8. 8Run the tests

    Run
    uv run pytest -v
    

    Expected output

    collecting ... collected 5 items
    
    tests/test_products.py::test_create_and_get PASSED                       [ 20%]
    tests/test_products.py::test_list_is_ordered PASSED                      [ 40%]
    tests/test_products.py::test_validation_rejects_negative_price PASSED    [ 60%]
    tests/test_products.py::test_missing_product_is_404 PASSED               [ 80%]
    tests/test_products.py::test_delete PASSED                               [100%]
    
    ============================== 5 passed in 0.06s ===============================
  9. 9Run the server

    Leave this running and use a second terminal for the next step.

    Run
    uv run uvicorn catalog.main:app --port 8000
    

    Expected output

    INFO:     Started server process [1838355]
    INFO:     Waiting for application startup.
    INFO:     Application startup complete.
    ...
    Check:

    Open http://127.0.0.1:8000/docs: FastAPI generated interactive API documentation for you.

  10. 10Call the API

    Run
    curl -s localhost:8000/healthz
    curl -s -X POST localhost:8000/products -H 'Content-Type: application/json' \
         -d '{"name": "Coffee mug", "price_cents": 1299}'
    curl -s -X POST localhost:8000/products -H 'Content-Type: application/json' \
         -d '{"name": "Tea pot", "price_cents": 2450}'
    curl -s localhost:8000/products
    curl -s localhost:8000/products/99
    

    Expected output

    {"status":"ok"}
    {"name":"Coffee mug","price_cents":1299,"id":1}
    {"name":"Tea pot","price_cents":2450,"id":2}
    [{"name":"Coffee mug","price_cents":1299,"id":1},{"name":"Tea pot","price_cents":2450,"id":2}]
    {"detail":"Product not found"}
  11. 11Send invalid input

    Validation errors come back as 422 with every problem listed, before your route function runs.

    Run
    curl -s -X POST localhost:8000/products -H 'Content-Type: application/json' \
         -d '{"name": "", "price_cents": -5}'
    

    Expected output

    {"detail":[{"type":"string_too_short","loc":["body","name"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}},{"type":"greater_than_equal","loc":["body","price_cents"],"msg":"Input should be greater than or equal to 0","input":-5,"ctx":{"ge":0}}]}
    Check:

    Stop the server with Ctrl+C. Add *.db to .gitignore so the local database stays out of Git.

In production

The structure here (routes, schemas, models, a session dependency, isolated tests) is the structure production FastAPI services use. The pieces around it change.

What changes

In this lab In production
SQLite file Postgres (or another server database) with connection pooling and backups
create_all at startup Versioned migrations (Alembic) run as a separate release step
One uvicorn process on your laptop Several workers in a container, behind a load balancer that terminates HTTPS
Anyone can call every endpoint Authentication (OAuth2/OIDC tokens or API keys) and authorization per endpoint
GET /products returns everything Pagination with a maximum page size, so one request can't load the whole table
Docs at /docs for everyone Docs disabled or protected in production; the OpenAPI schema published for clients
uvicorn access log lines Structured JSON logs with a request ID, plus metrics and traces

Test the edges, not just the happy path

Most production incidents come from input nobody tested: empty strings, negative numbers, missing records. The tests here check validation and 404s on purpose.

Production checklist

  • Input validated by schemas; output limited to response models (no accidental field leaks)
  • Correct status codes: 201 create, 204 delete, 404 missing, 422 invalid
  • Tests run against an isolated database and cover failure cases
  • Database schema managed by migrations, not create_all
  • Authentication, pagination and rate limits before exposing the API publicly
  • Local database files git-ignored

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake