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

FastAPI Inventory Service API

A mid-size distribution warehouse needs an internal API so pickers and stock clerks can look up items, adjust stock levels, and add new SKUs without touching the database directly. You are building that service: a FastAPI app backed by SQLAlchemy, with routers for items, validated inputs so bad requests never reach the database, custom exceptions so failures like insufficient stock or missing SKUs come back as clear, consistent JSON, and documented response schemas so the warehouse's other tools can integrate against a stable contract.

Lab platform
Lab Info
Level
Beginner
Last updated
Nov 25, 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 inventory service

    A distribution warehouse needs an inventory API

    In a mid-size distribution warehouse, pickers and stock clerks currently edit spreadsheets and, worse, sometimes the database directly to look up items, adjust stock counts, and add new SKUs. You're building the internal API that replaces that: a FastAPI service backed by a real SQL database, with validated inputs, consistent error responses, and a documented contract other warehouse tools can integrate against. ## A tour of the starter project

    The inventory_service/ package already has the shape of a small production API:

    • main.py builds the FastAPI app and will mount the items router.
    • database.py configures the SQLAlchemy engine and will hand out sessions.
    • models.py defines the Item ORM model mapped to the items table.
    • schemas.py defines the Pydantic models that describe request and response bodies.
    • exceptions.py defines domain-specific exceptions and the handlers that turn them into JSON.
    • routers/items.py will hold every /items endpoint.

    Nothing runs yet -- several of these pieces are stubs you'll complete over the next four steps. ## How a request will flow

    Once wired up, a request to create an item will travel: router function -> Depends(get_db) session -> a models.Item row written through SQLAlchemy -> validated on the way in by a Pydantic schema, and serialized on the way out by another. If something goes wrong -- a missing SKU, an impossible stock adjustment -- a custom exception interrupts that flow and a handler turns it into a predictable JSON error instead of a stack trace. You'll build each link in that chain, starting with the app itself.

    info> If you get stuck, you can refer to the provided solution code for each task, available in the solution folder.

  2. Challenge

    Bring the service online

    Standing up the FastAPI app

    Every FastAPI service starts with a single FastAPI() instance that carries metadata (title, version) used to generate the interactive docs at /docs, plus whatever routes and routers you attach to it. A /health endpoint is the smallest useful route: it gives you and any load balancer a fast way to confirm the process is up before worrying about the database or business logic. ## Mounting the first router

    A bare app with only a health check isn't an inventory service yet. FastAPI routers let you group related endpoints -- everything under /items -- in their own module and attach them to the app with a single include_router call. configure_app is where that assembly happens, so the app's identity (its docs metadata) and its routes come from the same place.

  3. Challenge

    Persist data with SQLAlchemy

    Sessions and dependency injection

    SQLAlchemy talks to the database through a Session, and FastAPI's dependency injection is the idiomatic way to hand a fresh session to whichever endpoint needs one: declare a parameter as db: Session = Depends(get_db) and FastAPI calls get_db for you, injects whatever it yields, and runs any cleanup after the response is sent. Get this dependency right once, and every router that uses it inherits correct session handling for free. ## Writing rows through the ORM

    Creating a row with the SQLAlchemy ORM is a short, repeatable sequence: build a model instance from validated data, add it to the session, commit to write it, then refresh so any database-generated values (like an autoincrement id) come back onto the object. create_item is the first endpoint that needs this sequence, and every other write in this service will follow the same shape. ## Reading rows back out

    Listing rows is the read half of the same session: build a query against the model, execute it, and return whatever comes back. FastAPI's response_model on the route already knows how to serialize a list of ORM objects into JSON, as long as the endpoint hands it real rows.

  4. Challenge

    Validate inputs and errors

    Tightening input rules with Pydantic

    Pydantic validators run before your endpoint code does, so they're the right place to reject requests that are syntactically fine but semantically nonsense -- like a stock adjustment that changes nothing. A field_validator on a schema field can inspect the incoming value and raise ValueError to reject it, which FastAPI turns into a 422 response automatically. ## Constrained path parameters and custom exceptions

    Path(gt=0) rejects nonsensical ids like 0 or -1 before your function body even runs, but a syntactically valid id can still point at a row that doesn't exist. That's a domain error, not a validation error, and it deserves its own exception type -- ItemNotFoundError -- so the registered handler in exceptions.py can turn it into a consistent 404 payload no matter which endpoint raises it. ## Combining validation and domain errors

    adjust_stock is where both pieces come together: the incoming delta has already been checked by StockAdjustment.validate_delta, so by the time it reaches your endpoint code the only remaining question is whether applying it is safe. That's a second domain error -- InsufficientStockError -- following the same raise-and-let-the-handler-respond pattern as a missing item.

  5. Challenge

    Document the API contract

    Computed fields on response schemas

    A response schema doesn't have to mirror the database row field for field -- Pydantic's @computed_field lets you derive a value from other fields at serialization time, so every response carries information the caller shouldn't have to recompute. Flagging low stock directly on ItemRead means any client reading /items already knows what needs reordering. ## Documenting filter bounds with Query

    Query(..., ge=0, description=...) does two jobs at once: it rejects out-of-range values before your code runs, and it documents those bounds in the OpenAPI schema so other teams integrating against this API can see the valid range without reading your source. search_items puts that to use for filtering by quantity. ## Finishing the lifecycle

    Create, read, and adjust are only useful if a mistaken SKU can also be removed. delete_item closes the loop, and it should feel familiar: the same db.get lookup and ItemNotFoundError you already used in get_item and adjust_stock, this time followed by a delete instead of a read or a write.

  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, make sure you are in the workspace root (the directory that holds the top-level main.py and the inventory_service/ package), and start the server:

    cd /home/ps-user/workspace
    python main.py
    

    Uvicorn serves the API on port 8000 and logs each request in the terminal. In a second terminal, try the endpoints you built:

    curl http://localhost:8000/health
    curl -X POST http://localhost:8000/items/ -H "Content-Type: application/json" -d '{"sku": "SKU-001", "name": "Pallet wrap", "quantity": 3}'
    curl http://localhost:8000/items/
    curl "http://localhost:8000/items/search?min_quantity=0&max_quantity=10"
    

    Opening the server root redirects to the interactive docs at /docs, where you can call every endpoint from the browser. Every behaviour you see is code you wrote in the previous steps -- that is the whole lab, working as one program. Press Ctrl+C in the server's terminal to stop it. ### 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