FastAPIInteractiveAll tracks

Lesson 38 of 45 ยท FastAPI Basics

Middleware Basics

Learn how to create and use middleware to process requests and responses in FastAPI applications.

Open this lesson in the editor โ†’

What you'll learn

  • Understand what middleware is and how it works
  • Create custom middleware using the @app.middleware decorator
  • Add processing before and after request handling
  • Understand middleware execution order

Middleware Basics

๐ŸŽฏ What You'll Learn

  • Understand what middleware is and how it works
  • Create custom middleware using the @app.middleware decorator
  • Add processing before and after request handling
  • Understand middleware execution order

๐Ÿ“š Theory

Middleware is a function that works with every request before it is processed by any specific path operation, and also with every response before returning it.

How Middleware Works

  1. Request Processing: Takes each request that comes to your application
  2. Pre-processing: Can modify the request or run any needed code
  3. Pass Through: Passes the request to be processed by the rest of the application
  4. Response Processing: Takes the response generated by the application
  5. Post-processing: Can modify the response or run any needed code
  6. Return: Returns the final response

Creating Middleware

To create middleware, use the @app.middleware("http") decorator on top of a function. The middleware function receives:

  • The request object
  • A call_next function that passes the request to the corresponding path operation
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

๐Ÿ”ง Key Concepts

  • @app.middleware("http"): Decorator to create HTTP middleware
  • call_next: Function that calls the next middleware or path operation
  • Request Processing: Code before call_next() runs before the request is handled
  • Response Processing: Code after call_next() runs after the response is generated
  • Custom Headers: Can add custom headers with 'X-' prefix for proprietary headers

๐Ÿ’ก Best Practices

  • Use time.perf_counter() instead of time.time() for precise timing measurements
  • Add custom headers with 'X-' prefix for proprietary headers
  • Keep middleware lightweight to avoid performance impacts
  • Consider middleware execution order when adding multiple middlewares

๐Ÿ” Testing Your Middleware

To see your middleware in action:

  1. Check Response Headers: Look for the X-Process-Time header in the response headers section
  2. View Headers in UI: Response headers are displayed in the Test Endpoints tab
  3. Compare Endpoints: Notice how different endpoints have different processing times
  4. Test Different Methods: Try GET, POST, and other HTTP methods to see consistent timing

๐Ÿ”— Additional Resources

Hint

Middleware functions run for every request and can modify both requests and responses. Use time.perf_counter() for precise timing measurements.

Now write it

The editor runs a real FastAPI server and grades your code against this lesson's own endpoints.

Start Middleware Basics