Python Answers

How to get http headers in Python flask?

Spread the love

In Flask, we can access HTTP headers using the request.headers object.

To do this we write

from flask import Flask, request

app = Flask(__name__)

def index():
    # Get the headers from the request
    headers = request.headers

    # Print or process the headers
    print("Headers:", headers)

    # You can access specific headers using their keys
    user_agent = headers.get('User-Agent')
    print("User-Agent:", user_agent)

    return "Check the console for headers."

if __name__ == '__main__':

In this example, request.headers contains all the headers sent in the HTTP request.

We can access specific headers using their keys, such as User-Agent, Content-Type, etc.

And we can also iterate over request.headers to access all headers if needed.

When we run this Flask app and make a request to the / route, it will print the headers in the console, and you can process them as needed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *