Bird
Raised Fist0
Flaskframework~10 mins

After_request hooks in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - After_request hooks
Request received
↓
Route function runs
↓
Response object created
↓
After_request hook runs
↓
Modified or original response returned
↓
Response sent to client
After_request hooks run after the route function creates a response, allowing you to modify it before sending it back.
Execution Sample
Flask
from flask import Flask, request
app = Flask(__name__)

@app.after_request
def add_header(response):
    response.headers['X-Hello'] = 'World'
    return response
This code adds a custom header to every response after the route function finishes.
Execution Table
StepActionInput/StateOutput/StateNotes
1Request receivedClient sends GET /Request object createdFlask starts processing request
2Route function runsRequest objectResponse object createdRoute returns a response
3After_request hook runsResponse object without X-Hello headerResponse object with X-Hello: World headerHook adds custom header
4Response sentModified Response objectClient receives response with headerResponse sent back to client
💡 After_request hook modifies response, then response is sent to client
Variable Tracker
VariableStartAfter Step 2After Step 3Final
response.headers{}{...default headers...}{...default headers..., 'X-Hello': 'World'}{...default headers..., 'X-Hello': 'World'}
Key Moments - 3 Insights
Why does the after_request hook receive a response object?
Because after_request hooks run after the route function returns a response, so they get that response to modify or inspect before sending it out (see execution_table step 3).
Can the after_request hook change the response content?
Yes, the hook can modify headers, status code, or body by changing the response object before returning it (execution_table step 3 shows header added).
What happens if the after_request hook does not return the response?
Flask requires the hook to return a response object; otherwise, it will cause an error or no response will be sent (see code sample return statement).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does the after_request hook add to the response at step 3?
AA new cookie
BA new header 'X-Hello' with value 'World'
CChanges the response status code
DModifies the request object
💡 Hint
Check the 'Output/State' column at step 3 in the execution_table
At which step does the route function create the response object?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for when the response is created
If the after_request hook did not return the response object, what would happen?
AFlask would send the original response anyway
BThe request would be processed twice
CFlask would raise an error or fail to send a response
DNothing changes, the hook is optional
💡 Hint
Refer to key_moments about the importance of returning the response from the hook
Concept Snapshot
After_request hooks run after a route returns a response.
They receive the response object and can modify it.
Always return the response from the hook.
Used to add headers, cookies, or logging.
Runs before sending response to client.
Full Transcript
In Flask, after_request hooks run after the route function finishes and returns a response. The hook receives this response object and can modify it, for example by adding headers. The hook must return the response object, or Flask will error. The modified response is then sent to the client. This lets you change responses globally after routes run.

Practice

(1/5)
1. What is the main purpose of an after_request hook in Flask?
easy
A. To initialize the Flask app configuration
B. To handle incoming request data before routing
C. To define URL routes for the application
D. To modify the response before it is sent to the client

Solution

  1. Step 1: Understand the role of after_request hooks

    After_request hooks run after the view function but before the response is sent to the client.
  2. Step 2: Identify what after_request hooks modify

    They receive the response object and can modify it, such as adding headers or logging.
  3. Final Answer:

    To modify the response before it is sent to the client -> Option D
  4. Quick Check:

    After_request hooks modify response [OK]
Hint: Remember: after_request changes response, not request [OK]
Common Mistakes:
  • Confusing after_request with before_request hooks
  • Thinking after_request handles incoming data
  • Assuming after_request defines routes
2. Which of the following is the correct syntax to register an after_request hook in Flask?
easy
A. @app.after_request\ndef modify_response(response):\n return response
B. @app.route('/after')\ndef modify_response():\n return 'Done'
C. @app.before_request\ndef modify_response(response):\n return response
D. @app.after_response\ndef modify_response(response):\n return response

Solution

  1. Step 1: Identify the correct decorator for after_request

    The correct decorator is @app.after_request to register a function that modifies the response.
  2. Step 2: Check function signature

    The function must accept one argument (the response) and return it.
  3. Final Answer:

    @app.after_request\ndef modify_response(response):\n return response -> Option A
  4. Quick Check:

    Use @app.after_request with response param [OK]
Hint: after_request needs @app.after_request decorator [OK]
Common Mistakes:
  • Using @app.before_request instead of after_request
  • Missing the response parameter in the function
  • Using a non-existent decorator like @app.after_response
3. What will be the output headers after this Flask app runs a request?
from flask import Flask, Response
app = Flask(__name__)

@app.after_request
def add_header(response):
    response.headers['X-Custom'] = 'Hello'
    return response

@app.route('/')
def index():
    return Response('OK')
medium
A. Response with header 'X-Custom' set to 'Hello'
B. Response with no custom headers
C. Error because headers cannot be modified
D. Response with header 'X-Custom' set to 'OK'

Solution

  1. Step 1: Understand after_request modifies response headers

    The after_request function adds a header 'X-Custom' with value 'Hello' to the response.
  2. Step 2: Check the response returned by the route

    The route returns a Response with body 'OK' but no custom headers initially.
  3. Step 3: Confirm header addition

    The after_request hook adds the header before sending, so the final response includes 'X-Custom: Hello'.
  4. Final Answer:

    Response with header 'X-Custom' set to 'Hello' -> Option A
  5. Quick Check:

    after_request adds headers to response [OK]
Hint: after_request can add headers before sending response [OK]
Common Mistakes:
  • Thinking headers cannot be changed after response creation
  • Confusing response body with headers
  • Assuming after_request runs before route
4. Identify the error in this Flask after_request hook code:
from flask import Flask
app = Flask(__name__)

@app.after_request
def fix_response():
    print('Fixing response')
    return 'Fixed'
medium
A. The function should not return anything
B. The decorator should be @app.before_request
C. The function must accept a response parameter
D. The print statement is not allowed in after_request

Solution

  1. Step 1: Check function signature for after_request

    Functions registered with @app.after_request must accept one argument: the response object.
  2. Step 2: Analyze the return value

    The function returns a string instead of a response object, which is incorrect.
  3. Step 3: Identify the main error

    Missing the response parameter causes Flask to raise an error because it expects the response argument.
  4. Final Answer:

    The function must accept a response parameter -> Option C
  5. Quick Check:

    after_request functions need response param [OK]
Hint: after_request functions always take response argument [OK]
Common Mistakes:
  • Omitting the response parameter in after_request function
  • Returning a string instead of a response object
  • Confusing after_request with before_request
5. You want to add a security header X-Frame-Options: DENY to all responses except those from the /public route. How can you implement this using after_request hooks?
hard
A. Use before_request to add the header unconditionally
B. Use after_request to check request.path and add header only if path is not '/public'
C. Add the header inside each route function manually
D. Use after_request but always add the header regardless of path

Solution

  1. Step 1: Use after_request to modify all responses

    after_request hooks run after every request and can modify the response before sending.
  2. Step 2: Check the request path inside after_request

    By accessing request.path, you can conditionally add headers only when the path is not '/public'.
  3. Step 3: Implement conditional header addition

    Inside the after_request function, add the header only if request.path != '/public'.
  4. Final Answer:

    Use after_request to check request.path and add header only if path is not '/public' -> Option B
  5. Quick Check:

    Conditionally add headers in after_request using request.path [OK]
Hint: Check request.path in after_request to add headers conditionally [OK]
Common Mistakes:
  • Adding headers unconditionally ignoring route
  • Using before_request which can't modify response headers
  • Manually adding headers in every route instead of centralized hook
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard