Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

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 platform
Lab Info
Level
Beginner
Last updated
Nov 26, 2026
Duration
45m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. 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.py holds the FastAPI app instance and every route handler, both synchronous and asynchronous.
    • app/models.py holds the Pydantic and SQLModel classes that shape requests and responses, along with helper functions that assemble nested payloads.
    • app/database.py holds the SQLModel engine, table setup, and the session plumbing that will eventually replace the in-memory CARS list with real persistence.

    Each file already has the imports and scaffolding in place; the TODO comments 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 solution folder.

  2. 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 def blocks the worker thread for its whole body, which is fine for quick, CPU-bound work like aggregating numbers already sitting in memory.
    • An async def route can await other coroutines, letting uvicorn serve other requests while this one waits on I/O.

    You will use both deliberately in app/main.py, starting with a synchronous /stats endpoint. ## Listing the fleet asynchronously

    With 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_cars with async def now, 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 parameters

    Listing 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 make parameter is already in the search_cars stub; you just need to implement the filtering logic that respects it.

  3. 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 city and zone, under a nested location object makes the schema self-documenting and gives you room to add computed fields, like a status label, without cluttering the top level. app/models.py is where these shaping functions live. ## Embedding related resources

    Trips are naturally related to cars, and a trip response that only includes a bare car_id forces every client to make a second request just to show which car was used. Nesting the full car object inside the trip response, reusing the serialize_car helper you just wrote, keeps that relationship visible in a single payload and in a single schema example. ## Customizing the OpenAPI schema

    FastAPI 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.openapi with a custom function lets you set the title, version and tag descriptions once, and FastAPI caches the result on app.openapi_schema so the override only costs you on the very first request.

  4. 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 Created to signal that a new resource now exists. The create_car route in app/main.py already has that status code wired into its decorator; your job is the logic that earns it. ## Updating and handling missing resources

    Updates are where a missing resource first becomes a real problem: silently doing nothing would leave the client guessing. Raising an HTTPException with a 404 and a specific detail message turns "nothing happened" into "here's exactly why", which is what a well-behaved REST API owes its callers. ## Deleting resources

    Delete follows the same not-found logic as update, but a successful delete has nothing meaningful to return, which is exactly what a 204 No Content status communicates. Getting this pair right completes the CRUD contract for cars:

    • 404 on a missing id.
    • 204 on a real deletion.
  5. Challenge

    Persist data with SQLModel

    Request-scoped sessions

    The in-memory CARS list 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.py is where that session lifecycle lives. ## Writing to two tables in one transaction

    Logging a trip touches two tables at once:

    • A new row in trips.
    • An updated mileage value on the matching row in cars.

    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 to log_trip, and translate its result into the right HTTP response.

  6. 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.py
    

    uvicorn starts the API on port 8000 and 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 /stats or GET /cars and 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} and DELETE /cars/{car_id} and check the status codes from Step 4.
    • Log a trip with POST /trips against a car that exists in the database, and against a missing car_id to see the 404.

    Every behaviour you see is code you wrote in the previous steps. When you are done, press Ctrl+C in the terminal to stop the server. ### Run the checks yourself

    The 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 -q
    

    Or one task at a time:

    bash runTest.sh test_task_2_1
    

    Each 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.

About the author

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

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.

Get started with Pluralsight