if 'your-header-name' in request. headers: customHeader = request. headers['your-header-name'] .... Please add this as a comment of the accepted post above.
To set response headers in Flask and Python, we set the headers property of the response object. to call make_response to create response object that returns a string response. Finally, we return the resp object in the home route.
Headers is class within the flask. app module of the Flask web framework that is imported from the datastructures module of the Werkzeug project. Headers handles the HTTP headers from requests and responses for Flask web applications.
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']
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']
....
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With