Hardening an API

Get an API ready for the open internet: decide which web pages may call it, slow down anyone guessing passwords, add security headers, keep secrets out of your code and out of GitHub, and refuse the attacks every API sees. Then you'll harden a coffee club's API before it goes online.

Updated

Browsers and Traffic

  1. CORS: Which Web Pages May Call Your API (Journeyman): A browser lets a web page read answers only from its own origin unless the API allows it, and FastAPI's CORSMiddleware with an allow-list of origins lets the club's own pages in, which protects people's browsers but never stops a script or a tool.
  2. Rate Limits and Security Headers (Journeyman): A sign-in route that answers every guess lets a script try thousands of passwords, so a rate limit counts each address's tries in a window of time and answers 429 with Retry-After, slowapi puts one on a FastAPI route, and a small middleware adds security headers to every answer.

Secrets and Attacks

  1. Keeping Secrets Out of Your Code (Journeyman): A secret typed into the code goes wherever the code goes, GitHub included, so an API reads its secrets from environment variables, keeps them in a .env file that .gitignore leaves out, commits a .env.example instead, stops at startup when one is missing, and rotates any secret that was ever pushed.
  2. The Attacks to Expect: Injection and Mass Assignment (Journeyman): An API online gets requests no app of yours would send, so it keeps typed text out of its SQL with placeholders, takes only the fields a person may change with a model that forbids extras, answers errors without their inner details, and checks its packages for known holes with pip-audit.

Exercise: Harden the Coffee Club API

  1. Exercise: Harden the Coffee Club API (Journeyman): Harden Bean There Coffee Club's working FastAPI app before it goes online, with CORS for the club's two web pages, security headers from a middleware, a slowapi rate limit on sign-in, an update model that can't set role, and the JWT secret read from the environment, and let the tests check every job.

Up Next: Professional Python APIs

  1. Up Next: Professional Python APIs (Journeyman): Look back at what Module 4 taught you, see a project that puts all of it to work, a community center's room bookings API with members and staff, and see the gaps Module 5 closes, with settings checked at startup, logs, a health check, tests on every push and your API online at a link.