Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 2

Lab: A CRUD Resource Held in Memory

Build the full reading-list API — create, list, get, replace and delete — on an in-memory store, exercise every route with curl, then lock the behaviour in with TestClient tests.

Contentsand lesson path

What you will learn

  • Implement CRUD path operations with typed path, query and body parameters and explicit success status codes.

Prerequisites: HTTP & APIs

01. Goal and setup

The previous lesson showed how one route works. This lab builds the whole set: a reading-list API with create, list, get, replace and delete for books, every route typed and returning explicit status codes. The store is a plain dictionary in process memory, so you can focus entirely on the web layer; later skills swap it for a database without touching the route declarations.

“Held in memory” has consequences you will observe deliberately: restart the process and the data is gone, and two workers would hold two different stores. That is fine for learning the web layer, and it is the honest motivation for the storage skills later in this roadmap. Everything else here — the routes, the status codes, the tests — carries over unchanged.

You need: Python 3.12, the uv package manager, curl, and two terminals — one for the server, one for requests. If you have not used curl against a local API before, the inspecting traffic lesson covers it.

The finished layout is small:

Project layout
readinglist/
├── .venv/          virtual environment managed by uv (never committed)
├── main.py         schemas, an in-memory store, five routes
└── test_main.py    TestClient tests: happy path and validation

02. Step 1: create the environment with uv

Make the folder, then let uv create the virtual environment and install the packages the lab needs, pinned to the versions it was tested with. Pydantic and Starlette come with FastAPI anyway, but they are pinned too, because the version check below prints Pydantic’s number and a newer release would make your output differ. uv pip targets the .venv in the current folder, so the commands work without activating anything; source .venv/bin/activate (Windows: .venv\Scripts\activate) makes plain python mean the environment copy for the rest of the session.

Terminal 1
mkdir readinglist && cd readinglist
uv venv --python 3.12 .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
uv pip install fastapi==0.163.1 pydantic==2.14.3 starlette==1.10.0 \
  uvicorn==0.54.0 httpx2==2.16.2 pytest==9.2.0
Expected output (install lines for dependencies trimmed)
Using CPython 3.12.13
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
 + fastapi==0.163.1
 + httpx2==2.16.2
 + pydantic==2.14.3
 + pytest==9.2.0
 + starlette==1.10.0
 + uvicorn==0.54.0
Terminal 1 · confirm what you got
python -c "import fastapi, pydantic, uvicorn; print(fastapi.__version__, \
pydantic.VERSION, uvicorn.__version__)"
Expected output
0.163.1 2.14.3 0.54.0

httpx2 is the HTTP client that TestClient uses to call your app in step 5, so it belongs in the environment even though your own code never imports it. The pins make your output match this lab; in a real project a lock file (uv lock, or uv pip compile) keeps teammates and CI on the same numbers; the virtual environments lab covers pinning in depth.

03. Step 2: write the app

Two small Pydantic models separate what a client sends from what a client gets back: BookIn carries the fields of a new book, BookOut adds the id the server assigns. Constraints live on the model, so validation happens before any handler runs. The store is a dictionary plus a counter for the next id.

Python · main.py (models, store, create and list)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

app = FastAPI(title='Reading List API')


class BookIn(BaseModel):
    title: str = Field(min_length=1, max_length=200)
    author: str = Field(min_length=1, max_length=100)
    pages: int = Field(default=0, ge=0)


class BookOut(BookIn):
    id: int


books: dict[int, BookOut] = {}
next_id = 1


@app.post('/books', status_code=201)
def create_book(book: BookIn):
    global next_id
    created = BookOut(id=next_id, **book.model_dump())
    books[created.id] = created
    next_id += 1
    return created


@app.get('/books')
def list_books(q: str = '', limit: int = 10):
    found = [b for b in books.values() if q.lower() in b.title.lower()]
    return {'count': len(found), 'items': found[:limit]}
Python · main.py (get, replace and delete)
@app.get('/books/{book_id}')
def get_book(book_id: int):
    if book_id not in books:
        raise HTTPException(status_code=404, detail='book not found')
    return books[book_id]


@app.put('/books/{book_id}')
def replace_book(book_id: int, book: BookIn):
    if book_id not in books:
        raise HTTPException(status_code=404, detail='book not found')
    replaced = BookOut(id=book_id, **book.model_dump())
    books[book_id] = replaced
    return replaced


@app.delete('/books/{book_id}', status_code=204)
def delete_book(book_id: int):
    if book_id not in books:
        raise HTTPException(status_code=404, detail='book not found')
    del books[book_id]

Note what is not here: no parsing of JSON, no type conversion, no manual error responses. The body arrives as a validated BookIn, book_id arrives as an int, and a missing book is a clean 404. A PUT that replaces the whole record takes the same input model as creation, which is the usual contract for replace operations.

Two models are the minimum here, not the finish line. BookIn is used for both creating and replacing, and nothing stops a handler from returning a dictionary with extra keys. The next lesson gives create, update and read their own schemas, with constraints, custom validators and a response model that filters what leaves the server — for now, two models keep the lab focused on routing and status codes.

04. Step 3: serve it

Terminal 1
uvicorn main:app --port 8000
Expected output (your process id differs)
INFO:     Started server process [1911548]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

main:app means “the app object inside main.py”. The process id in the first line will differ. Open http://127.0.0.1:8000/docs in a browser and you will see all five routes, under the default heading because none has a tag, ready to try. During development, --reload restarts the server on every save.

05. Step 4: exercise every route with curl

In the second terminal, drive the API the way a client would. Create two books first; the -i flag shows the status line and headers, which is the part worth checking.

Terminal 2
curl -s -i -w '\n' -X POST http://127.0.0.1:8000/books \
  -H 'Content-Type: application/json' \
  -d '{"title": "The Pragmatic Programmer", "author": "Hunt & Thomas", "pages": 352}'
curl -s -w '\n' -X POST http://127.0.0.1:8000/books \
  -H 'Content-Type: application/json' \
  -d '{"title": "Refactoring", "author": "Fowler", "pages": 448}'
Expected output (headers trimmed)
HTTP/1.1 201 Created
content-type: application/json

{"title":"The Pragmatic Programmer","author":"Hunt & Thomas","pages":352,"id":1}
{"title":"Refactoring","author":"Fowler","pages":448,"id":2}
Terminal 2 · list with a filter, read one, read a missing one
curl -s -w '\n' 'http://127.0.0.1:8000/books?q=ref'
curl -s -i -w '\n' http://127.0.0.1:8000/books/1
curl -s -i -w '\n' http://127.0.0.1:8000/books/99
Expected output (headers trimmed)
{"count":1,"items":[{"title":"Refactoring","author":"Fowler","pages":448,"id":2}]}
HTTP/1.1 200 OK

{"title":"The Pragmatic Programmer","author":"Hunt & Thomas","pages":352,"id":1}
HTTP/1.1 404 Not Found

{"detail":"book not found"}
Terminal 2 · replace, delete, delete again, send a bad body
curl -s -w '\n' -X PUT http://127.0.0.1:8000/books/1 \
  -H 'Content-Type: application/json' \
  -d '{"title": "The Pragmatic Programmer", "author": "Hunt & Thomas", "pages": 320}'
curl -s -i -w '\n' -X DELETE http://127.0.0.1:8000/books/2
curl -s -i -w '\n' -X DELETE http://127.0.0.1:8000/books/2
curl -s -w '\n' -X POST http://127.0.0.1:8000/books \
  -H 'Content-Type: application/json' \
  -d '{"title": "", "author": "Fowler", "pages": -1}'
Expected output (headers trimmed; the long JSON wrapped to fit)
{"title":"The Pragmatic Programmer","author":"Hunt & Thomas","pages":320,"id":1}
HTTP/1.1 204 No Content

HTTP/1.1 404 Not Found

{"detail":"book not found"}
{"detail":[{"type":"string_too_short","loc":["body","title"],
"msg":"String should have at least 1 character","input":"",
"ctx":{"min_length":1}},{"type":"greater_than_equal","loc":["body","pages"],
"msg":"Input should be greater than or equal to 0","input":-1,
"ctx":{"ge":0}}]}

The last response is the framework working as designed: the body was well-formed JSON, so the transport was fine (400 would mean broken HTTP), but two fields broke their constraints, and each failure is reported with its location and reason. Delete twice and you see the idempotency story from the status codes lesson in action: 204, then 404, with the resource deleted either way.

06. Step 5: lock the behaviour in with tests

Manual curl runs prove the server works today; tests prove it keeps working. TestClient calls the app in process — no server, no port — and is built on the same client library (httpx2) you installed in step 1. The fixture clears the module-level store first, so each test starts from a known state and order does not matter. The pytest lesson covers fixtures if they are new to you.

Python · test_main.py
import pytest
from fastapi.testclient import TestClient

import main
from main import app


@pytest.fixture()
def client():
    main.books.clear()
    with TestClient(app) as test_client:
        yield test_client


def test_create_list_get_delete(client):
    created = client.post(
        '/books', json={'title': 'Refactoring', 'author': 'Fowler', 'pages': 448}
    )
    assert created.status_code == 201
    book_id = created.json()['id']

    listed = client.get('/books', params={'q': 'refactor'})
    assert listed.status_code == 200
    assert listed.json()['count'] == 1

    one = client.get(f'/books/{book_id}')
    assert one.status_code == 200
    assert one.json()['title'] == 'Refactoring'

    gone = client.delete(f'/books/{book_id}')
    assert gone.status_code == 204
    assert client.get(f'/books/{book_id}').status_code == 404


def test_create_rejects_bad_body(client):
    bad = client.post('/books', json={'title': '', 'author': 'Fowler', 'pages': -1})
    assert bad.status_code == 422
    fields = {e['loc'][1] for e in bad.json()['detail']}
    assert fields == {'title', 'pages'}
Terminal 1 (stop the server first with Ctrl+C)
python -m pytest -q
Illustrative output (the time differs per run)
..                                                                       [100%]
2 passed in 0.62s

The second test reaches into the error body instead of only checking the status: it asserts which fields failed, so a regression that silently loosens a constraint fails the test by name.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

What the running lab does

Answer from what you observed in the lab.

Q1. You create three books, stop uvicorn, start it again, and request GET /books. What comes back?
Q2. Why does the client fixture call main.books.clear() before each test?
Q3. The last curl in step 4 produced a 422. Which sentence describes it best?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

Extend the API without breaking the tests:

  1. Add a GET /books/{book_id}/age route (any calculation you like) and a test for it.
  2. Make list_books return 422 for limit outside 1–100 using Annotated[int, Query(ge=1, le=100)], and add a test that sends limit=500.
  3. Restart the server and confirm with curl that the store really is empty, then write one sentence in a comment in main.py naming the skill that will fix this (see SQL fundamentals).

10. Review prompt

Without looking back: which decorator argument produced the 201 and the 204, and which object produced the 404? Why did the invalid POST answer 422 and not 400? Where does the data live, and what proves it? Finally, explain what TestClient replaces and why the fixture clears the store.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check