Last updated: Apr 11, 2024
Reading timeยท3 min
To make an HTTP request with a bearer token using requests in Python:
Authorization
header in the headers
dictionary.Bearer
prefix.import requests url = 'https://jsonplaceholder.typicode.com/users' data = {'id': 1, 'name': 'bobby hadz'} headers = { 'Authorization': 'Bearer YOUR_JWT_TOKEN', } response = requests.post( url, data=data, headers=headers, timeout=30 ) print(response.status_code) # ๐๏ธ 201 result = response.json() print(result) # ๐๏ธ {'id': 11, 'name': 'bobby hadz'}
Make sure you have the requests module installed to be able to run the code sample.
pip install requests # or with pip3 pip3 install requests
We passed the following arguments to the requests.post()
method:
Bearer
prefix.If you have the JWT token stored in a variable, append it to the Bearer
prefix.
JWT_TOKEN = 'eyjhcabc123' headers = { 'Authorization': 'Bearer ' + JWT_TOKEN, } # {'Authorization': 'Bearer eyjhcabc123'} print(headers)
You can also use a formatted string literal to achieve the same result.
JWT_TOKEN = 'eyjhcabc123' headers = { 'Authorization': f'Bearer {JWT_TOKEN}', } # {'Authorization': 'Bearer eyjhcabc123'} print(headers)
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with f
.
Make sure to wrap expressions in curly braces - {expression}
.
You can call the json()
method on the Response object to view the server's
response.
import requests url = 'https://jsonplaceholder.typicode.com/users' data = {'id': 1, 'name': 'bobby hadz'} headers = { 'Authorization': 'Bearer YOUR_JWT_TOKEN', } response = requests.post( url, data=data, headers=headers, timeout=30 ) print(response.status_code) # ๐๏ธ 201 result = response.json() print(result) # ๐๏ธ {'id': 11, 'name': 'bobby hadz'}
You can also define a custom class that sets the Authorization
header for you.
import requests class BearerAuth(requests.auth.AuthBase): def __init__(self, token): self.token = token def __call__(self, r): r.headers['Authorization'] = 'Bearer ' + self.token return r url = 'https://jsonplaceholder.typicode.com/users' JWT_TOKEN = 'eyjhcabc123' response = requests.get( url, auth=BearerAuth(JWT_TOKEN), timeout=30 ) print(response.status_code) # ๐๏ธ 200 print(response.json())
The BearerAuth
class takes the JWT token as a parameter and sets the
Authorization
header for you (including the Bearer
prefix).
The code sample issues a GET request with a Bearer token, but the same approach can be used to issue a POST request.
import requests class BearerAuth(requests.auth.AuthBase): def __init__(self, token): self.token = token def __call__(self, r): r.headers["authorization"] = "Bearer " + self.token return r url = 'https://jsonplaceholder.typicode.com/users' data = {'id': 1, 'name': 'bobby hadz'} JWT_TOKEN = 'eyjhcabc123' response = requests.post( url, data=data, auth=BearerAuth(JWT_TOKEN), timeout=30 ) print(response.status_code) # ๐๏ธ 201 print(response.json()) # ๐๏ธ {'id': 11, 'name': 'bobby hadz'}
We simply called requests.post()
instead of request.get()
and set the data
keyword argument.
Notice that we are setting the auth
keyword argument when using the
BearerAuth
class, and not the headers
argument directly.
You can also use the native urllib
module to make a request with a Bearer
token in Python.
import urllib.request import json url = 'https://jsonplaceholder.typicode.com/users' data = {'id': 1, 'name': 'bobby hadz'} encoded_data = json.dumps(data).encode() JWT_TOKEN = 'eyjhcabc123' req = urllib.request.Request( url, data=encoded_data, headers={"Authorization": f"Bearer {JWT_TOKEN}"}, ) response = urllib.request.urlopen(req) print(response.read())
The code sample makes a POST request with a Bearer token, however, the same approach can be used to make a GET request.
import urllib.request url = 'https://jsonplaceholder.typicode.com/users' JWT_TOKEN = 'eyjhcabc123' req = urllib.request.Request( url, None, headers={"Authorization": f"Bearer {JWT_TOKEN}"}, ) response = urllib.request.urlopen(req) print(response.read())
However, using the requests
third-party module is much more intuitive than
using the built-in urllib
module.
You can learn more about the related topics by checking out the following tutorials: