Python requests: Making an HTTP request with a Bearer Token

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
3 min

banner

# Table of Contents

  1. Python requests: Making an HTTP request with a Bearer Token
  2. Using a custom class to issue Requests with a Bearer token in Python
  3. Using the urllib module to make a request with a Bearer token

# Python requests: Making an HTTP request with a Bearer Token

To make an HTTP request with a bearer token using requests in Python:

  1. Set the Authorization header in the headers dictionary.
  2. The value of the header should be the JWT token with the Bearer prefix.
  3. Issue the GET, POST, PUT, PATCH or DELETE request.
main.py
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 post request with bearer token

The code for this article is available on GitHub

Make sure you have the requests module installed to be able to run the code sample.

shell
pip install requests # or with pip3 pip3 install requests

We passed the following arguments to the requests.post() method:

  1. The complete URL (including the endpoint) to which we're making the POST request.
  2. The request body (the data) that we want to send over the network.
  3. The HTTP request headers. Notice that the Authorization header is set to a string that has the Bearer prefix.
  4. The timeout (in seconds) after which the request is canceled.

If you have the JWT token stored in a variable, append it to the Bearer prefix.

main.py
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.

main.py
JWT_TOKEN = 'eyjhcabc123' headers = { 'Authorization': f'Bearer {JWT_TOKEN}', } # {'Authorization': 'Bearer eyjhcabc123'} print(headers)
The code for this article is available on GitHub

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.

main.py
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 post request with bearer token

The code for this article is available on GitHub

# Using a custom class to issue Requests with a Bearer token in Python

You can also define a custom class that sets the Authorization header for you.

main.py
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())

issue request with bearer token using custom class

The code for this article is available on GitHub

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.

main.py
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'}

make post request with bearer token

The code for this article is available on GitHub

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.

# Using the urllib module to make a request with a Bearer token

You can also use the native urllib module to make a request with a Bearer token in Python.

main.py
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())

make request with bearer token using urllib

The code for this article is available on GitHub

The code sample makes a POST request with a Bearer token, however, the same approach can be used to make a GET request.

main.py
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev