What is Middleware?
Middleware is a component that sits between the client and your application. Every incoming request passes through the middleware before reaching the route handler, and every outgoing response passes through the middleware before being sent back to the client. Middleware is commonly used for application-wide processing.Request-Response Flow
- Before the request reaches the route handler.
- After the route handler returns the response.
Working Principle
A middleware receives two arguments:requestcall_next
Example 1 - Logging Requests
Example 2 - Measure Request Processing Time
Example 3 - Global Exception Handling
Frequently Used Built-in Middleware
CORSMiddleware
Allows browser applications from trusted origins to access your API.GZipMiddleware
Compresses large responses to reduce network usage.Middleware vs Dependencies
Common Use Cases
- Logging requests and responses.
- Measuring request processing time.
- Global exception handling.
- CORS configuration.
- Session management.
- Response compression.
Although authentication and authorization can be implemented using middleware, FastAPI recommends using dependencies (Depends) because different routes often require different authentication and authorization rules.
Key Points
- Middleware intercepts every request and response.
- It executes before and after the route handler.
call_next()forwards the request to the next middleware or route handler.- FastAPI provides several built-in middleware through Starlette.
- Use middleware for application-wide concerns and dependencies for route-specific logic.