Module 8 Exercises: Mastering the Lifecycle

Module 8 Exercises: Mastering the Lifecycle

Practical exercises to challenge your understanding of middleware, CORS, and global request interceptors.

Module 8 Exercises: Mastering the Lifecycle

Middleware is the "Glue" that holds your infrastructure together. These exercises will test your ability to implement global features safely and efficiently.


Exercise 1: The CORS Configuration

A developer on your team just connected a React app (running at http://localhost:3000) to your FastAPI backend. They are seeing an error in their browser console: "Access to fetch at... has been blocked by CORS policy."

Write the FastAPI code needed in main.py to allow this React app to make requests, including allowing them to send Authorization headers.


Exercise 2: Implementing the Timing Header

Write a custom middleware function called process_timer that:

  1. Measures the time it takes for the request to be handled.
  2. Adds a custom header to the response called X-API-Latency containing the time in milliseconds.

Exercise 3: Dependency vs. Middleware

You are building a feature that checks if a user's API Key is valid. Decide whether you should use Middleware or a Dependency for each of the following scenarios:

  1. Scenario A: You have 100 endpoints, but only 5 of them require an API key.
  2. Scenario B: You want to log the IP address of every single person who hits any URL on your server.
  3. Scenario C: You want to check the API key, but you also need to use the resulting User object inside your route function to save data.

Self-Correction / Discussion

Exercise 1 Answer:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Exercise 2 Answer:

import time

@app.middleware("http")
async def process_timer(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = (time.time() - start) * 1000 # Convert to ms
    response.headers["X-API-Latency"] = f"{duration:.2f}ms"
    return response

Exercise 3 Answer:

  1. Dependency: Since only a few routes need it, middleware is overkill and adds unnecessary processing to the other 95 routes.
  2. Middleware: Since this is a global requirement, it's cleaner to handle it in one place via middleware.
  3. Dependency: Middleware cannot easily "Hand over" a Python object (like a User model) to your route function. Dependencies are designed for this exact "Injection" pattern.

Summary of Module 8

You have mastered the "Infrastructure" of your API.

  • Security: You can handle CORS and Trusted Hosts.
  • Performance: You can implement GZip compression.
  • Observability: You can intercept requests to add timing or IDs.

In Module 9: Authentication and Authorization, we will move into the most critical part of any production app: Keeping it Secure.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn