How to get http headers in flask?

Question:

Using Flask, how can I read HTTP headers? I want to check the authorization header which is sent by the client.

Asked By: emil

||

Answers:

from flask import request
request.headers.get('your-header-name')

request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:

request.headers['your-header-name']
Answered By: sanyi

just note, The different between the methods are, if the header is not exist

request.headers.get('your-header-name')

will return None or no exception, so you can use it like

if request.headers.get('your-header-name'):
    ....

but the following will throw an error

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

You can handle it by

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....
Answered By: cieunteung

If any one’s trying to fetch all headers that were passed then just simply use:

dict(request.headers)

it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy

Answered By: iam.Carrot

Let’s see how we get the params, headers and body in Flask.
I’m gonna explain with the help of postman.

enter image description here

The params keys and values are reflected in the API endpoint.
for example key1 and key2 in the endpoint :
https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

    key_1 = request.args.get('key1')
    key_2 = request.args.get('key2')
    print(key_1)
    #--> value1
    print(key_2)
    #--> value2

After params, let’s now see how to get the headers:

enter image description here

header_1 = request.headers.get('header1')
header_2 = request.headers.get('header2')
print(header_1)
#--> header_value1
print(header_2)
#--> header_value2

Now let’s see how to get the body

enter image description here

file_name = request.files['file'].filename
ref_id = request.form['referenceId']
print(ref_id)
#--> WWB9838yb3r47484

so we fetch the uploaded files with request.files and text with request.form

Answered By: Ajeet Verma