🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Response Headers

A response header adds a fact to the answer. The make_response call builds a response to change.

Make the app

This line imports Flask and make_response together. The route below builds a response.

from flask import Flask, make_response

app = Flask(__name__)

Set a header

The view builds a response from the page text. It then adds the X-Hint header to the response.

@app.route("/hint")
def hint():
    response = make_response("Hint page")
    response.headers["X-Hint"] = "look here"
    return response

Ask for the header

The test client asks for /hint. The prints show the header value and the page text.

client = app.test_client()
print(client.get("/hint").headers.get("X-Hint"))
print(client.get("/hint").data.decode())

Example

from flask import Flask, make_response

app = Flask(__name__)

@app.route("/hint")
def hint():
    response = make_response("Hint page")
    response.headers["X-Hint"] = "look here"
    return response

client = app.test_client()
print(client.get("/hint").headers.get("X-Hint"))
print(client.get("/hint").data.decode())

Key points

  • make_response turns text into a response object.
  • Set a header on the response, like response.headers["X-Hint"] = "look here".
  • Headers travel with the page, unseen by the reader.
  • Read a header back from the test response with .headers.get.

In this example, the view builds a response from "Hint page" and adds the X-Hint header. The test client asks for /hint twice. The first print shows the header value, and the second shows the page text.

Note

Header names use capital first letters by habit.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does a view add a header to a response?