PYTHON
Authenticate API Requests with Bearer Tokens in Python using `requests`
Securely interact with protected APIs in Python by adding Bearer token authentication to your HTTP requests using the popular `requests` library for authorization.
import requests
import json
def make_authenticated_api_request(url, token, method='GET', data=None, params=None):
"""Makes an authenticated API request with a Bearer token.
Args:
url (str): The API endpoint URL.
token (str): The Bearer token for authentication.
method (str, optional): The HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE'). Defaults to 'GET'.
data (dict, optional): Dictionary of data to send in the request body (for POST, PUT).
params (dict, optional): Dictionary of query parameters.
Returns:
dict or None: The JSON response data if successful, None otherwise.
"""
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json' # Assuming JSON payload for POST/PUT
}
try:
if method.upper() == 'GET':
response = requests.get(url, headers=headers, params=params)
elif method.upper() == 'POST':
response = requests.post(url, headers=headers, json=data, params=params)
elif method.upper() == 'PUT':
response = requests.put(url, headers=headers, json=data, params=params)
elif method.upper() == 'DELETE':
response = requests.delete(url, headers=headers, params=params)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err} - Response: {http_err.response.text}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An error occurred: {req_err}")
except ValueError as val_err:
print(f"Invalid input: {val_err}")
return None
# --- Example Usage ---
# Replace with your actual token and API endpoint
# YOUR_BEARER_TOKEN = "your_secret_bearer_token_here"
# API_BASE_URL = "https://api.example.com"
# # Example GET request
# print("
--- GET Request ---")
# data = make_authenticated_api_request(f"{API_BASE_URL}/users", YOUR_BEARER_TOKEN)
# if data:
# print("Fetched data:", json.dumps(data, indent=2))
# # Example POST request
# print("
--- POST Request ---")
# new_item = {"name": "Test Item", "value": 100}
# post_response = make_authenticated_api_request(f"{API_BASE_URL}/items", YOUR_BEARER_TOKEN, method='POST', data=new_item)
# if post_response:
# print("POST response:", json.dumps(post_response, indent=2))
How it works: This Python snippet demonstrates how to make authenticated API requests using the popular `requests` library by including a Bearer token in the `Authorization` header. Bearer tokens are a common method for securing REST APIs, indicating that the bearer of the token has been authorized. The `make_authenticated_api_request` function simplifies sending GET, POST, PUT, and DELETE requests, handling the header setup and basic error handling for various network and HTTP issues, ensuring secure and reliable communication with protected API endpoints.