How to get http headers in flask?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow
--
Chapters
00:00 How To Get Http Headers In Flask?
00:24 Accepted Answer Score 494
00:39 Answer 2 Score 39
01:07 Answer 3 Score 45
01:24 Answer 4 Score 12
02:25 Thank you
--
Full question
https://stackoverflow.com/questions/2938...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #http #flask #httpheaders #authorization
#avk47
ACCEPTED ANSWER
Score 494
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']
ANSWER 2
Score 45
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
ANSWER 3
Score 39
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']
   ....
ANSWER 4
Score 12
Let's see how we get the params, headers, and body in Flask. I'm gonna explain with the help of Postman.
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:
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
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


