0
0
Flaskframework~5 mins

After_request hooks in Flask

Choose your learning style9 modes available
Introduction

After_request hooks let you run code right after your web app sends a response. This helps you change or add things to the response before it goes to the user.

Add custom headers to every response, like security or tracking info.
Log details about the response for debugging or analytics.
Modify the response content or status code before sending it.
Close or clean up resources after handling a request.
Set cookies or session data after processing a request.
Syntax
Flask
@app.after_request
def function_name(response):
    # modify response
    return response
The function must accept one argument: the response object.
Always return the response object, even if you don't change it.
Examples
This adds a custom header to every response sent by the app.
Flask
@app.after_request
def add_header(response):
    response.headers['X-Custom-Header'] = 'MyValue'
    return response
This prints the response status code to the console after each request.
Flask
@app.after_request
def log_response(response):
    print(f"Response status: {response.status}")
    return response
Sample Program

This Flask app adds a security header to every response using an after_request hook. When you visit the home route, the JSON response will include the extra header.

Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.after_request
def add_security_header(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    return response

@app.route('/')
def home():
    return jsonify(message='Hello, world!')

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

After_request hooks run after the view function but before the response is sent.

If you forget to return the response, the client will get an error.

You can have multiple after_request hooks; they run in the order they are registered.

Summary

After_request hooks let you change or add to responses before sending.

They always receive and must return the response object.

Useful for adding headers, logging, or cleanup tasks after requests.