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
- Request Processing: Takes each request that comes to your application
- Pre-processing: Can modify the request or run any needed code
- Pass Through: Passes the request to be processed by the rest of the application
- Response Processing: Takes the response generated by the application
- Post-processing: Can modify the response or run any needed code
- 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
requestobject - A
call_nextfunction 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 oftime.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:
- Check Response Headers: Look for the
X-Process-Timeheader in the response headers section - View Headers in UI: Response headers are displayed in the Test Endpoints tab
- Compare Endpoints: Notice how different endpoints have different processing times
- 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