- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
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 Info
Table of Contents
-
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: aFastAPI()instance, a handful of@app.post/@app.getroutes that speak only JSON, and direct calls into SQLAlchemy inside the route bodies.app/models.pydefines the two tables you will work with all lab:Inspector(an account with a username and a password column) andInspection(a site, a status, an inspection date, and a foreign key back to the inspector who filed it). ## What's wrong with the prototypeFour 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
APIRouterand 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 throughUploadFile, 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 withpassliband 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 soTestClientcan 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
solutionfolder. -
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'sAPIRouterlets you group related paths -- everything about inspections -- into their own module, whichapp/main.pythen plugs in withinclude_router. Once the routes live in their own module, you can have them returntemplates.TemplateResponse(...)instead of a JSON dict, handing Jinja2 a.htmlfile plus a context dictionary so it can render a normal page from live database rows.app/routers/inspections.pyalready has the router, session dependency, and template engine wired up; thelist_inspectionsfunction just needs to actually query the database and render the list. ## Rendering a single recordA 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.pybuilds the actual running application insidecreate_app, and until that function callsapp.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. -
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 asmultipart/form-data-- FastAPI reads those fields withForm(...)parameters rather than a Pydantic body model. The same request can also carry a file: declaring a parameter asUploadFilegives 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 inThe 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.
CORSMiddlewareis that opt-in: it inspects theOriginheader 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 middlewareCORS 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
requestandcall_next, doing something before and afterawait call_next(request), and returning the resulting response -- exactly the shape you'll use to stamp every response with its processing time. -
Challenge
Passwords and authentication
Never store a plaintext password
Right now
Inspector.hashed_passwordholds whatever string was typed in at registration -- a direct hit if the database ever leaks.passlib'sCryptContextproduces 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 AuthHTTP 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'sHTTPBasicsecurity scheme extracts them into aHTTPBasicCredentialsobject, and a dependency function decides whether they're good enough to proceed. The delete route inapp/routers/inspections.pyalready depends onget_current_inspector_basic-- it just needs to actually check the credentials against the stored hash. ## Issuing a token for creationBasic 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. -
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
dbargument 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 NGINXFastAPI 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-Securityheader so browsers remember to always use HTTPS for this domain. -
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.pyUvicorn 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/docsshows the interactive OpenAPI docs, including the/tokenlogin and the routes you protected in Step 4.http://localhost:8000/inspections/summaryreturns the per-status counts frombuild_inspection_summary.
Every response also carries the
X-Process-Timeheader you added in Step 3. PressCtrl+Cin the terminal to stop the server when you're done. ### 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.
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.