0
0
FlaskHow-ToBeginner · 3 min read

How to Use after_request in Flask for Response Processing

In Flask, use the @app.after_request decorator to register a function that runs after each request and receives the response object. This function can modify or log the response before it is sent to the client and must return the response object.
📐

Syntax

The @app.after_request decorator registers a function that takes the response object as an argument. This function runs after the view function completes but before the response is sent to the client. You must return the response object from this function.

  • @app.after_request: Decorator to register the function.
  • def function_name(response):: Function that receives the response.
  • return response: Return the (possibly modified) response.
python
from flask import Flask, Response

app = Flask(__name__)

@app.after_request
def modify_response(response: Response) -> Response:
    # Modify response here
    return response
💻

Example

This example shows how to add a custom header to every response using @app.after_request. The function adds a header named X-Custom-Header with a value before sending the response.

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

@app.after_request
def add_custom_header(response):
    response.headers['X-Custom-Header'] = 'MyValue'
    return response

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the app and visiting http://localhost:5000/ returns 'Hello, Flask!' with the HTTP response header 'X-Custom-Header: MyValue'.
⚠️

Common Pitfalls

  • Not returning the response object from the after_request function will cause errors or no response sent.
  • Modifying the response incorrectly (e.g., changing its type) can break the response.
  • Using after_request for error handling is incorrect; use errorhandler instead.
  • Remember after_request runs only if no unhandled exceptions occur during the request.
python
from flask import Flask

app = Flask(__name__)

# Wrong: Not returning response
@app.after_request
def wrong_modify(response):
    response.headers['X-Test'] = 'Fail'
    # Missing return statement

# Correct way
@app.after_request
def correct_modify(response):
    response.headers['X-Test'] = 'Pass'
    return response
📊

Quick Reference

ConceptDescription
@app.after_requestDecorator to register a function that runs after each request.
Function argumentReceives the response object to modify or inspect.
Return valueMust return the response object to continue processing.
Use casesAdd headers, log responses, modify cookies.
LimitationsDoes not run if an exception is unhandled during request.

Key Takeaways

Use @app.after_request to run code after each request but before sending the response.
Always return the response object from your after_request function.
Modify response headers or content safely without changing the response type.
after_request functions do not run if an unhandled exception occurs.
Use after_request for response processing, not for error handling.