
MIDDLEWARE IN FASTAPI
Middleware in FastAPI
Middleware is a layer that works between the client and the application.
When a client sends a request to our application, the request first passes through the middleware. The middleware can check, process, modify, or block the request before it reaches the application.
After the application sends a response, the middleware can also process the response before sending it back to the client.
Simple Flow
Client → Middleware → Application → Middleware → Client
For example:
- The client sends a request.
- Middleware receives the request.
- Middleware checks or processes the request.
- The request goes to the application.
- The application processes the request and creates a response.
- Middleware receives the response.
- Middleware can process the response.
- The response is sent back to the client.
What Can Middleware Do?
Middleware can perform different tasks before or after a request.
1. Authentication
Middleware can check whether a user is logged in or has permission to access something.
Example:
A user tries to access a protected page.
Request → Middleware checks user → Application
If the user is allowed, the request continues.
If the user is not allowed, middleware can stop the request.
2. Logging
Middleware can record information about requests and responses.
For example:
- Which URL was requested?
- Which HTTP method was used?
- What was the response status?
- How long did the request take?
This information is useful for debugging and monitoring an application.
3. Request Timing
Middleware can calculate how much time a request takes.
Example:
Request starts
↓
Middleware records time
↓
Application processes request
↓
Middleware calculates time
↓
Response sent to client
This helps developers find slow requests.
4. CORS
Middleware can handle Cross-Origin Resource Sharing (CORS).
It controls whether a frontend running on one website or port is allowed to communicate with a backend running on another website or port.
For example:
Frontend → Backend
Middleware can check whether the frontend is allowed to make the request.
5. Modify Requests
Middleware can change or add information to a request before sending it to the application.
For example, it can add some information that the application needs.
6. Modify Responses
Middleware can also process a response before it reaches the client.
For example, it can add headers to the response.
7. Block Requests
Middleware can stop a request if it does not satisfy a required condition.
For example:
Client sends request
↓
Middleware checks request
↓
Not allowed
↓
Request is blocked
The request will not reach the application.
How Middleware Works
Think of middleware like a security/checking gate.
When you enter a building:
You
↓
Security Gate
↓
Building
The security gate checks you before allowing you inside.
Middleware works in a similar way:
Client
↓
Middleware
↓
Application
↓
Middleware
↓
Client
The middleware can check the request before the application receives it and can process the response before the client receives it.
Simple Example
Suppose we have a FastAPI application.
A user sends:
GET /users
The flow can be:
Client
↓
Middleware
↓
Check request
↓
Start timer
↓
FastAPI Application
↓
Get users
↓
Response
↓
Middleware
↓
Calculate time
↓
Client
So middleware can do something before the application and something after the application.
Middleware in FastAPI
FastAPI allows us to create middleware for tasks that need to be performed for many requests.
A simple example:
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def my_middleware(request: Request, call_next):
print("Before request")
response = await call_next(request)
print("After response")
return response
Here:
requestcontains the incoming request.call_next(request)sends the request to the next step, usually the application/route.responsecontains the response returned by the application.return responsesends the response back to the client.
In Short
Middleware is a layer between the client and the application.
It can:
- Check requests
- Allow or block requests
- Authenticate users
- Log requests
- Measure request time
- Handle CORS
- Modify requests
- Modify responses
- Process responses
Final Flow
REQUEST
Client ───────────→ Middleware
↓
Check / Process
↓
Application
↓
Create Response
↓
Middleware
↓
RESPONSE
Client ←───────────────
Join Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments