- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Building a Database-Backed CRUD Application with FastAPI
A small city car-sharing startup needs a backend for its ops team: an API to register cars, book trips against them, and keep mileage in sync whenever a trip is logged. You inherit a skeleton FastAPI project with an empty app and stub files, and you build it out step by step into a working, documented, persisted service.
Lab Info
Table of Contents
-
Challenge
Meet the car-sharing API
A car-sharing service needs a backend
Your client is a small city car-sharing startup. Its ops team needs one backend that can register cars, book trips against them, and keep each car's mileage in sync whenever a trip is logged. You are inheriting the very first skeleton of that backend: a FastAPI app that starts but does almost nothing yet. Over the next four steps you will turn it into a documented, validated, database-backed CRUD service, one route and one file at a time. ## A tour of the starter project
The starter project has three files you will keep coming back to:
app/main.pyholds theFastAPIapp instance and every route handler, both synchronous and asynchronous.app/models.pyholds the Pydantic and SQLModel classes that shape requests and responses, along with helper functions that assemble nested payloads.app/database.pyholds the SQLModel engine, table setup, and the session plumbing that will eventually replace the in-memoryCARSlist with real persistence.
Each file already has the imports and scaffolding in place; the
TODOcomments mark exactly where your logic belongs. ## Where you're headed- Step 2 gets the server answering requests with a mix of sync and async routes over an in-memory car list.
- Step 3 shapes and documents that data so Swagger UI tells the truth about the API.
- Step 4 fills in the remaining create, update and delete operations with correct status codes.
- Step 5 swaps the in-memory list for SQLModel tables and wires trips and mileage together through a real database session.
By the end, the car-sharing API will read, write, and document itself accurately.
info> If you get stuck, you can refer to the provided solution code for each task, available in the
solutionfolder. -
Challenge
Serve sync and async routes
Sync versus async routes
FastAPI lets a route be either a plain function or a coroutine, and the choice matters:
- A synchronous
defblocks the worker thread for its whole body, which is fine for quick, CPU-bound work like aggregating numbers already sitting in memory. - An
async defroute canawaitother coroutines, lettinguvicornserve other requests while this one waits on I/O.
You will use both deliberately in
app/main.py, starting with a synchronous/statsendpoint. ## Listing the fleet asynchronouslyWith stats working synchronously, the next endpoint has to hand back the whole fleet, which is exactly the kind of operation a real app would eventually back with an async database call. Declaring
list_carswithasync defnow, even against an in-memory list, sets up the shape you will reuse in Step 5 once a real session is involved. ## Filtering with query parametersListing everything is a start, but ops also needs to narrow results by manufacturer. FastAPI turns an optional function parameter into an optional query parameter automatically, so the
makeparameter is already in thesearch_carsstub; you just need to implement the filtering logic that respects it. - A synchronous
-
Challenge
Shape and document responses
Nesting related fields
A response that just dumps flat fields is hard to extend and harder to read in Swagger UI. Grouping related fields, like a car's
cityandzone, under a nestedlocationobject makes the schema self-documenting and gives you room to add computed fields, like astatuslabel, without cluttering the top level.app/models.pyis where these shaping functions live. ## Embedding related resourcesTrips are naturally related to cars, and a trip response that only includes a bare
car_idforces every client to make a second request just to show which car was used. Nesting the full car object inside the trip response, reusing theserialize_carhelper you just wrote, keeps that relationship visible in a single payload and in a single schema example. ## Customizing the OpenAPI schemaFastAPI generates a reasonable OpenAPI schema by default, but the generic title and missing tag descriptions don't tell a new developer anything about this car-sharing service specifically. Overriding
app.openapiwith a custom function lets you set the title, version and tag descriptions once, and FastAPI caches the result onapp.openapi_schemaso the override only costs you on the very first request. -
Challenge
Complete CRUD for cars
Creating resources
Reading the fleet is only half of CRUD. Creating a car means picking an id scheme that won't collide, and returning
201 Createdto signal that a new resource now exists. Thecreate_carroute inapp/main.pyalready has that status code wired into its decorator; your job is the logic that earns it. ## Updating and handling missing resourcesUpdates are where a missing resource first becomes a real problem: silently doing nothing would leave the client guessing. Raising an
HTTPExceptionwith a404and a specificdetailmessage turns "nothing happened" into "here's exactly why", which is what a well-behaved REST API owes its callers. ## Deleting resourcesDelete follows the same not-found logic as update, but a successful delete has nothing meaningful to return, which is exactly what a
204 No Contentstatus communicates. Getting this pair right completes the CRUD contract for cars:404on a missing id.204on a real deletion.
-
Challenge
Persist data with SQLModel
Request-scoped sessions
The in-memory
CARSlist has been a convenient stand-in, but it disappears every time the process restarts. SQLModel gives you table classes backed by a real engine, and FastAPI's dependency injection gives every request its own session so concurrent requests never step on each other's transactions.app/database.pyis where that session lifecycle lives. ## Writing to two tables in one transactionLogging a trip touches two tables at once:
- A new row in
trips. - An updated
mileagevalue on the matching row incars.
If either write fails, both should be rolled back rather than leaving the fleet's mileage out of sync with its trip history, which is exactly what committing them together in a single session accomplishes. ## Wiring the route
With the session dependency and the transactional write both ready, the last piece is the route that ties them together: accept the trip request, inject the session with
Depends(get_session), delegate the actual write tolog_trip, and translate its result into the right HTTP response. - A new row in
-
Challenge
Run the application
Every task is done, and each one was graded the moment you completed it. What you have not done yet is watch the whole application run at once -- which is the only place the pieces you wrote separately become a single working program.
Start the application
Open the Terminal tab and run:
python main.pyuvicornstarts the API on port8000and logs each request in the terminal. Leave it running.Explore the API in the browser
Open the Web Browser tab and load the lab's URL for port
8000. The root path/redirects to/docs, the Swagger UI page generated from the OpenAPI schema you customized in Step 3. From there you can:- Expand
GET /statsorGET /carsand choose Try it out, then Execute to call the routes from Step 2. - Create, update and delete a car with
POST /cars,PUT /cars/{car_id}andDELETE /cars/{car_id}and check the status codes from Step 4. - Log a trip with
POST /tripsagainst a car that exists in the database, and against a missingcar_idto see the404.
Every behaviour you see is code you wrote in the previous steps. When you are done, press
Ctrl+Cin the terminal to stop the server. ### Run the checks yourselfThe lab ran each task's test for you as you went, but they are ordinary tests and you can run them whenever you like. The whole suite:
python3 -m pytest -qOr one task at a time:
bash runTest.sh test_task_2_1Each failure names the task it belongs to, so the output tells you which step to go back to rather than which line to stare at. Two things worth trying before you finish: break something on purpose and watch the matching check fail, then put it back. Knowing what a failure looks like is worth as much as knowing what a pass looks like, and it costs you nothing here.
When you are done, everything you wrote is still in the editor tabs -- the lab is yours to keep reading.
- Expand
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.