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
On this page
- Goal and setup
- Step 1: create the environment with uv
- Step 2: write the app
- Step 3: serve it
- Step 4: exercise every route with curl
- Step 5: lock the behaviour in with tests
- Troubleshooting
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of FastAPI Fundamentals
- From Function to Endpoint: Path Operations Concept · 15 min
- Lab: A CRUD Resource Held in Memory Lab · 30 min
- Validating Input and Shaping Output with Pydantic Worked example · 25 min
- Dependencies: Sharing Resources Without Globals Worked example · 20 min
- Routers, Settings and Application Lifespan Lab · 25 min
- Check: Trace a Request Through the App Knowledge check · 8 questions
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:
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 validation02. 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.
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.0Using 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.0python -c "import fastapi, pydantic, uvicorn; print(fastapi.__version__, \
pydantic.VERSION, uvicorn.__version__)"0.163.1 2.14.3 0.54.0httpx2 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.
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]}@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
uvicorn main:app --port 8000INFO: 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.
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}'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}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{"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"}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}'{"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.
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'}python -m pytest -q.. [100%]
2 passed in 0.62sThe 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
09. Apply it: stretch tasks
Extend the API without breaking the tests:
- Add a
GET /books/{book_id}/ageroute (any calculation you like) and a test for it. - Make
list_booksreturn422forlimitoutside 1–100 usingAnnotated[int, Query(ge=1, le=100)], and add a test that sendslimit=500. - Restart the server and confirm with curl that the store really is empty, then write one sentence in a comment in
main.pynaming 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.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.