🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Request Headers

Request headers carry extra facts about a request. The request.headers dict holds them.

Make the app

This line imports Flask and request together. The route below reads headers.

from flask import Flask, request

app = Flask(__name__)

Read two headers

The view reads the User-Agent, keeping only its first eight letters. It also reads a header that never arrives, so the default shows.

@app.route("/agent")
def agent():
    who = request.headers.get("User-Agent", "unknown")[:8]
    test = request.headers.get("X-Test", "missing")
    return who + "\n" + test

Ask for the headers

The test client sends its own User-Agent. The print shows its start and the default for the missing header.

client = app.test_client()
print(client.get("/agent").data.decode())

Example

from flask import Flask, request

app = Flask(__name__)

@app.route("/agent")
def agent():
    who = request.headers.get("User-Agent", "unknown")[:8]
    test = request.headers.get("X-Test", "missing")
    return who + "\n" + test

client = app.test_client()
print(client.get("/agent").data.decode())

Key points

  • Headers travel with every request.
  • request.headers.get("User-Agent", "unknown") reads one header.
  • The User-Agent names the program that sent the request.
  • A missing header returns the default value.

In this example, the view reads the User-Agent header and keeps its first eight letters, Werkzeug. It also reads the X-Test header, which never arrives, so the default missing shows. The test client asks for /agent and prints both lines.

Note

Header names are not case sensitive.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does request.headers.get("X-Test", "missing") return when X-Test never arrives?