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

Securing a FastAPI Service Deployment

A civil engineering firm runs an internal service for tracking site inspections. Inspectors currently POST JSON to a flat, single-file FastAPI app with no browser UI, no file support, and no authentication -- anyone with network access can create, read, or delete an inspection record. You are hardening this site inspection service so field inspectors can submit reports and photos from a browser, only authenticated inspectors can modify records, the service's behavior is provable with automated tests instead of manual curl calls, and operations can deploy it behind NGINX with HTTPS in production.

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

    Welcome to the site inspection service

    The site inspection service is a civil engineering firm's internal tool for tracking site inspections: an inspector visits a bridge, a foundation pour, or a scaffolding rig, and logs what they found. Right now that logging happens by POSTing raw JSON to a single-file FastAPI prototype -- there is no browser page to look at, no way to attach a photo of a cracked beam, and no login of any kind. Anyone who can reach the service on the network can create, read, or delete an inspection record for any site.

    Open site_inspection_portal/app/main.py. You will find the whole application in one module: a FastAPI() instance, a handful of @app.post/@app.get routes that speak only JSON, and direct calls into SQLAlchemy inside the route bodies. app/models.py defines the two tables you will work with all lab: Inspector (an account with a username and a password column) and Inspection (a site, a status, an inspection date, and a foreign key back to the inspector who filed it). ## What's wrong with the prototype

    Four gaps separate this prototype from something you could actually deploy:

    • No browser UI. Every response is JSON, so an inspector standing at a job site with a phone browser has nothing to look at.
    • No forms or file uploads. There is no way to submit a report from an HTML form, and no way to attach a photo of the site.
    • No authentication. The delete and create endpoints run for anyone who can reach the port -- there is no concept of a logged-in inspector.
    • No tests, no production story. The prototype has never been exercised by an automated check, and it has no plan for running behind HTTPS.

    Each of the next four steps closes one of these gaps, in the order a real hardening pass would tackle them: structure and render, then accept input safely, then authenticate, then verify and deploy. ## Where you're headed

    You will move the inspection endpoints into their own APIRouter and render them through Jinja2 templates so an inspector can browse records in a normal browser tab. Then you will let inspectors submit new reports through an HTML form, attach a site photo through UploadFile, and configure CORS plus a custom middleware so a partner dashboard on another origin can call the service safely. After that you will hash inspector passwords with passlib and put HTTP Basic Auth and an OAuth2/JWT login in front of the two operations that matter most: deleting a record and creating one. Finally you will pull the summary logic out of its route so TestClient can exercise it against a mocked database session, and generate the NGINX configuration the service will run behind in production.

    The scenario stays the same throughout: the site inspection service needs to go from "anyone can do anything over plain JSON" to "only authenticated inspectors can change records, over HTTPS, with the behavior proven by tests."

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

  2. Challenge

    Routers and Jinja templates

    Structuring routes and rendering them

    A single-file app doesn't scale past a handful of routes, and it certainly doesn't give an inspector anything to look at in a browser. FastAPI's APIRouter lets you group related paths -- everything about inspections -- into their own module, which app/main.py then plugs in with include_router. Once the routes live in their own module, you can have them return templates.TemplateResponse(...) instead of a JSON dict, handing Jinja2 a .html file plus a context dictionary so it can render a normal page from live database rows.

    app/routers/inspections.py already has the router, session dependency, and template engine wired up; the list_inspections function just needs to actually query the database and render the list. ## Rendering a single record

    A list page is only half the picture -- an inspector clicking into one record expects to see its full detail, plus context the raw stored fields don't give you directly, like how long ago the inspection happened. That means looking up a single row by its primary key, handling the case where the id doesn't exist, and computing a derived value before handing everything to the template. ## Making the routes reachable

    Defining a router is not the same as serving it. app/main.py builds the actual running application inside create_app, and until that function calls app.include_router(...) with your new router object, none of the paths you just wrote will respond to anything -- they simply don't exist on the live app.

  3. Challenge

    Forms, uploads, and CORS

    Accepting input from a browser

    JSON endpoints assume a client that builds request bodies programmatically. A field inspector filling out a page instead submits an HTML <form>, which arrives as multipart/form-data -- FastAPI reads those fields with Form(...) parameters rather than a Pydantic body model. The same request can also carry a file: declaring a parameter as UploadFile gives you an async, streaming handle to the uploaded bytes, which you read and write to disk yourself before linking the saved path to the database record. ## Letting another origin call in

    The partner dashboard runs on a different domain from the site inspection service, and browsers block cross-origin requests by default unless the server explicitly opts in. CORSMiddleware is that opt-in: it inspects the Origin header on incoming requests and, when it matches an allowed origin, adds the response headers that let the browser's fetch or XHR call succeed instead of silently failing. ## Writing your own middleware

    CORS is built-in middleware; sometimes you need behavior FastAPI doesn't ship, like recording how long each request took. A custom HTTP middleware is just an async function taking request and call_next, doing something before and after await call_next(request), and returning the resulting response -- exactly the shape you'll use to stamp every response with its processing time.

  4. Challenge

    Passwords and authentication

    Never store a plaintext password

    Right now Inspector.hashed_password holds whatever string was typed in at registration -- a direct hit if the database ever leaks. passlib's CryptContext produces a one-way hash: you can verify a guess against it later, but you can't recover the original plaintext from the hash itself. Every place that currently compares passwords needs to go through this hash instead of a plain string equality check. ## Guarding deletion with Basic Auth

    HTTP Basic Auth is the simplest way to require credentials on a route: the browser (or httpx) sends a username and password on every request, FastAPI's HTTPBasic security scheme extracts them into a HTTPBasicCredentials object, and a dependency function decides whether they're good enough to proceed. The delete route in app/routers/inspections.py already depends on get_current_inspector_basic -- it just needs to actually check the credentials against the stored hash. ## Issuing a token for creation

    Basic Auth resending a password on every request is fine for one sensitive route, but creating records is better protected by a proper login: the OAuth2 password flow. An inspector posts a username and password once to a token endpoint, the server verifies them and signs a JWT with python-jose, and the client attaches that token as a bearer credential on subsequent requests. The create-inspection route already expects a valid token from this endpoint -- your job is to make the endpoint issue one correctly.

  5. Challenge

    Harden for production

    Testing against a mocked database

    A route function tangled together with a live SQLAlchemy session is hard to unit test -- you'd need a real database just to check some counting logic. Pulling the aggregation into its own function that simply takes a db argument means a test can hand it a mocked session object instead, call the function directly, and assert on the dict it returns, with no HTTP layer or real database involved. ## Deploying behind NGINX

    FastAPI and Uvicorn don't terminate TLS themselves in production -- that job belongs to a reverse proxy like NGINX, which listens on 443, decrypts HTTPS traffic using a certificate and key on disk, and forwards plain HTTP internally to Uvicorn. A hardened config also redirects any stray HTTP traffic on port 80 straight to HTTPS, and adds a Strict-Transport-Security header so browsers remember to always use HTTPS for this domain.

  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 service on port 8000 and logs each request in the terminal.

    See it in the browser

    Open the Web Browser tab and go to http://localhost:8000. The site root redirects to /inspections, the page you rendered with Jinja2 in Step 2, which lists every inspection currently stored in the database. On a fresh database the list is empty until a record is created. A few other places to look:

    • http://localhost:8000/docs shows the interactive OpenAPI docs, including the /token login and the routes you protected in Step 4.
    • http://localhost:8000/inspections/summary returns the per-status counts from build_inspection_summary.

    Every response also carries the X-Process-Time header you added in Step 3. Press Ctrl+C in the terminal to stop the server when you're done. ### 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