How to get http headers in flask?

244,600

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.

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

Share:
244,600

Related videos on Youtube

emil
Author by

emil

Updated on September 09, 2021

Comments

  • emil
    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.

  • Karthic Raghupathi
    Karthic Raghupathi over 8 years
    FYI: 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 or request.authorization.password.
  • Blairg23
    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
    Abhijeet over 7 years
    Adding if hasattr(request, 'authorization'): to code will help check for missing 'authorization' attribute in request.
  • Michael Scheper
    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') returns True but getattr(request, 'authorization') returns None. I'm not sure if this is the result of middleware or frameworks I'm using (Flask-Restful, for example).
  • Abhijeet
    Abhijeet about 7 years
    @MichaelScheper may using in operator check might help, it worked for me if 'authorization' in request:, other usage of in operator
  • Michael Scheper
    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
    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
    Michael Scheper almost 7 years
    @Abhijeet: ... or you could just use the code that I suggested in my previous comment. Much cleaner.
  • Pandem1c
    Pandem1c over 5 years
    Flask 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
    holdenweb about 5 years
    @MichaelScheper the second argument to get would seem to be redundant, since I believe None is the default.
  • Michael Scheper
    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 for request.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
    holdenweb about 5 years
    Me neither - just adding another acorn to your store of knowledge.
  • jasonrhaas
    jasonrhaas about 4 years
    @JamieLindsey This is not true. request.headers is actually an EnvironHeaders object that can be accessed like a dictionary. werkzeug.palletsprojects.com/en/1.0.x/datastructures/…
  • ribitskiyb
    ribitskiyb over 3 years
    well it's a default Python's mapping-classes behaviour
  • Tim Ludwinski
    Tim Ludwinski over 3 years
    Although @jasonrhass is correct in most cases, EnvironHeaders isn't a subclass of dict so it fails many times where a dict 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 is print(json.dumps(dict(flask.request.headers), indent=4)).
  • iam.Carrot
    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 type dict since it can be accessed/queried like a dict. The comment you see, is a response to that.
  • LUNA
    LUNA over 2 years
    What's the program in the screenshots?
  • Rayanth
    Rayanth over 2 years
    @LUNA that is Postman - postman.com
  • LUNA
    LUNA over 2 years
    Awesome thank you!
  • Heewoon
    Heewoon about 2 years
    Please add this as a comment of the accepted post above.