How to get http headers in flask?
Solution 1
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']
Solution 2
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']
....
Solution 3
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
Solution 4
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
Related videos on Youtube
emil
Updated on September 09, 2021Comments
-
emil over 2 years
I am newbie to python and using Python Flask and generating REST API service.
I want to check authorization header which is sent the client.
But I can't find way to get HTTP header in flask.
Any help for getting HTTP header authorization is appreciated.
-
Martijn Pieters over 8 years
-
Martijn Pieters over 8 yearsAlso, see the Flask Quickstart and API documentation.
-
-
Karthic Raghupathi over 8 yearsFYI: I'm looking at flask.pocoo.org/snippets/8 and it appears you could also access the username and password for basic authentication like so:
request.authorization.username
orrequest.authorization.password
. -
Blairg23 over 7 years@Karthic Raghupathi, as long as the header doesn't have illegal characters like dashes, which most headers do (i.e., X-Api-Key), in which case you need to access it like a dictionary with keys.
-
Abhijeet over 7 yearsAdding
if hasattr(request, 'authorization'):
to code will help check for missing 'authorization' attribute in request. -
Michael Scheper about 7 years@Abhijeet: It seems this isn't always the case. When I use
curl
without specifying authorisation headers,hasattr(request, 'authorization')
returnsTrue
butgetattr(request, 'authorization')
returnsNone
. I'm not sure if this is the result of middleware or frameworks I'm using (Flask-Restful, for example). -
Abhijeet about 7 years@MichaelScheper may using
in
operator check might help, it worked for meif 'authorization' in request:
, other usage of in operator -
Michael Scheper about 7 years@Abhijeet: Again, that checks whether the key exists, but not whether the value exists. A safer way would be
if request.headers.get('your-header-name', None)
—this will pass only if 'your-header-name' exists and the value is non-null. -
Abhijeet about 7 years@MichaelScheper that's a fact, the logic needs to have few conditional together to take-care of
Non-Existence & None value
i.e.,if 'headers' in request and request.header is not None and 'authorization' in request.headers and request.headers['authorization'] is not None:
-
Michael Scheper almost 7 years@Abhijeet: ... or you could just use the code that I suggested in my previous comment. Much cleaner.
-
Pandem1c over 5 yearsFlask headers are not a dict, yeah?... i see them coming back as werkzeug.datastructures.EnvironHeaders in my tests. werkzeug.pocoo.org/docs/0.14/datastructures/…
-
holdenweb about 5 years@MichaelScheper the second argument to
get
would seem to be redundant, since I believeNone
is the default. -
Michael Scheper about 5 years@holdenweb: Thanks—you're right. I thought the second parameter was necessary to prevent a
KeyError
, but that's only true forrequest.headers['your-header-name']
. (I should've known that.) But it's been a while since I've looked at this, so I'm not sure if that resolves Abhijeet's and Pandem1c's concerns. -
holdenweb about 5 yearsMe neither - just adding another acorn to your store of knowledge.
-
jasonrhaas about 4 years@JamieLindsey This is not true.
request.headers
is actually anEnvironHeaders
object that can be accessed like a dictionary. werkzeug.palletsprojects.com/en/1.0.x/datastructures/… -
ribitskiyb over 3 yearswell it's a default Python's mapping-classes behaviour
-
Tim Ludwinski over 3 yearsAlthough @jasonrhass is correct in most cases,
EnvironHeaders
isn't a subclass ofdict
so it fails many times where adict
would succeed (isinstance(flask.request.headers, dict) == False
). For example, the following code produces an error:print(json.dumps(flask.request.headers, indent=4))
. The fix isprint(json.dumps(dict(flask.request.headers), indent=4))
. -
iam.Carrot over 3 years@TimLudwinski You're maybe missing out on the context. There was a deleted comment which claimed that the
request.headers
would be of typedict
since it can be accessed/queried like adict
. The comment you see, is a response to that. -
LUNA over 2 yearsWhat's the program in the screenshots?
-
Rayanth over 2 years@LUNA that is Postman - postman.com
-
LUNA over 2 yearsAwesome thank you!
-
Heewoon about 2 yearsPlease add this as a comment of the accepted post above.