API Navigator Logo

Python Requests with Bearer Token

Author: Newtum

This guide explains how to send an API request with a Bearer Token for authentication using the Python Requests library. This is a common pattern for authenticating with OAuth 2.0 protected APIs.

What is a Bearer Token?

A Bearer Token is a type of access token used in token-based authentication. The client includes this token in the `Authorization` header of the request to access protected resources. The server then validates the token to grant access.

Sending a Bearer Token in Headers

To send a Bearer Token, you must construct a custom `Authorization` header with the format `Bearer <YOUR_TOKEN>`.

import requests

# This is a sample endpoint that would typically be protected
url = 'https://api.github.com/user'
my_token = 'YOUR_SECRET_GITHUB_TOKEN' # Replace with a real token

headers = {
    'Authorization': f'Bearer {my_token}'
}

response = requests.get(url, headers=headers)

print('Status Code:', response.status_code)
if response.status_code == 200:
    print('Successfully authenticated.')
    print(response.json())
else:
    print('Failed to authenticate.')
    print(response.text)