Middleware is an application layer that intercepts requests and responses to apply shared behavior. In a FastAPI service, it can centralize API logging instead of repeating logging code in every endpoint. section 9.4
A logging middleware can progressively assemble an audit record:
- Register a function with @app.middleware("http"). section 9.4
- Pass the request to call_next and wait for the response. section 9.4
- Capture the client IP address, user agent, method, response status, and URL. section 9.4
- Write the assembled record through an audit-log utility. section 9.4
- Return the response so normal endpoint processing remains intact. section 9.4
Adding business-readable audit messages
A decorator can place a custom message in request.state, allowing an endpoint such as read_files to record “Retrieving ACH files” alongside the technical request details. Unannotated endpoints can use a default message. section 9.4
Listing 9.26 The middleware layer for logging
@app.middleware("http") #1
async def log_requests(request: Request, call_next): #2
response = await call_next(request) #3
log_message = getattr(request.state, 'log_message', #4
"Default audit log message") #5
log_record = AuditLogRecord( #5
ip_address=request.client.host, #5
user_agent=request.headers.get #5
➥('user-agent', 'unknown'), #5
http_request=request.method, #5
http_response=response.status_code, #5
url=str(request.url), #5
message=log_message, #5
) #5
logger = AuditLog() #6
logger.log_record(log_record) #6
return response #7
The listing shows the complete middleware path from request handling through response capture and audit-record creation. section 9.4









