How to Access Request Headers and Query Parameters in Flask
In Flask web applications, you often need to access information sent by the client, such as HTTP headers and query parameters.
This guide explains how to access these values using the request object provided by Flask.
Accessing Request Headers
The request object in Flask (imported from the flask module) provides access to incoming request data. The request.headers attribute is a dictionary-like object that contains the HTTP headers.
Using request.headers.get() (Recommended)
The safest and recommended way to access headers is to use the .get() method:
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def home_route():
print(request.headers) # Prints all headers
auth_header = request.headers.get('Authorization')
content_type = request.headers.get('Content-Type')
accept_header = request.headers.get('Accept')
print('------')
print(auth_header)
print(content_type)
print(accept_header)
return "<p>Home: tutorialreference.com</p>"
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=8000)
- The code imports the
requestobject fromflask, and creates a simple route that handles requests sent to/URI.
request.headers.get('Header-Name'): This attempts to retrieve the header named'Header-Name'. Crucially, if the header is not present in the request,.get()returnsNoneby default (or you can specify a different default value as the second argument).- The header names are case-insensitive.
Example request (using curl):
curl -H "Authorization: Bearer mytoken" -H "Content-Type: application/json" -H "Accept: text/html" http://localhost:8000/
- The
-Hflags incurlspecify request headers. - You can use different tools to send HTTP requests, such as
curl,Postmanorhttpie.
The output in your Flask application's console would be (the exact EnvironHeaders output will vary):
EnvironHeaders([('Host', 'localhost:8000'), ('Connection', 'keep-alive'), ('Authorization', 'Bearer mytoken'), ('Content-Type', 'application/json'), ('Accept', 'text/html'), ('User-Agent', 'curl/7.81.0'), ('Sec-Fetch-Mode', 'cors')])
------
Bearer mytoken
application/json
text/html
To specify a default if the header does not exist use second parameter:
@app.route("/")
def home_route():
# ...
# With a default value
print(request.headers.get('Authorization', 'default value'))
print(request.headers.get('Content-Type', 'default value'))
print(request.headers.get('Accept', 'default value'))
return "<p>Home: tutorialreference.com</p>"
If the header is not provided, instead of None, a default value is returned.
Accessing Headers with Bracket Notation (Avoid)
You can also access headers using bracket notation like a dictionary (e.g., request.headers['Authorization']), but this is strongly discouraged:
# ⛔️ AVOID THIS:
# print(request.headers['Authorization']) # Raises KeyError if header is missing
- This approach will throw a
KeyErrorexception if header is not in the request. - Always use
.get()to avoid unexpected errors. The only exception is if you're absolutely certain the header will always be present and you want an error if it's missing.
Converting request.headers to a Dictionary
If you want to get the headers in a dictionary, pass the request.headers to the dict() constructor:
# Convert the headers object to a native Python dictionary
print(dict(request.headers))
Accessing Query Parameters
Query parameters (the part of the URL after the ?) are accessed via request.args:
Using request.args.get()
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def home_route():
page = request.args.get('page') # Get the 'page' parameter
limit = request.args.get('limit', default='10') # Get 'limit', default to '10'
print('page:', page)
print('limit:', limit)
return "<p>Home: tutorialreference.com</p>"
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=8000)
-
request.argsis a dictionary. -
request.args.get('page'): Gets the value of thepageparameter. ReturnsNoneifpageis not in the URL. -
request.args.get('limit', default='10'): Gets thelimitparameter, but returns'10'(as a string!) iflimitis not provided.
Example URLs and outputs:
-
http://localhost:8000/?page=5&limit=20:pagewill be'5',limitwill be'20'. -
http://localhost:8000/?page=5:pagewill be'5',limitwill be'10'(the default). -
http://localhost:8000/:pagewill beNone,limitwill be'10'. -
Type Conversions: Remember that query parameters are always strings. If you need an integer, use
int(request.args.get('page', '0')). Always handle potentialValueErrorexceptions if you convert to a number:try:
page = int(request.args.get('page', '1')) # Default to page 1
if page < 1: # Validate values
page = 1
except ValueError:
page = 1