PYTHON
Implementing OAuth 2.0 Client Credentials Flow for API Access (Python)
Securely obtain an access token using the OAuth 2.0 Client Credentials grant type in Python for server-to-server API integrations, demonstrating token request and usage.
import requests
import os
def get_oauth_token(token_url, client_id, client_secret, scope=None):
"""
Obtains an OAuth 2.0 access token using the Client Credentials grant type.
Args:
token_url (str): The URL of the authorization server's token endpoint.
client_id (str): The client ID provided by the API provider.
client_secret (str): The client secret provided by the API provider.
scope (str, optional): The scope of the access request. Defaults to None.
Returns:
str: The access token string, or None if token acquisition fails.
"""
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
}
if scope:
data["scope"] = scope
try:
response = requests.post(token_url, headers=headers, data=data)
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
token_data = response.json()
return token_data.get("access_token")
except requests.exceptions.RequestException as e:
print(f"Error obtaining OAuth token: {e}")
return None
def make_authenticated_api_call(api_url, access_token):
"""
Makes an API call with an OAuth 2.0 Bearer token.
"""
if not access_token:
print("No access token provided. Cannot make authenticated call.")
return None
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
try:
response = requests.get(api_url, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error making authenticated API call: {e}")
return None
# Example Usage (replace with your actual credentials and URLs)
# CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID", "your_client_id")
# CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET", "your_client_secret")
# TOKEN_URL = "https://your-oauth-provider.com/oauth/token"
# PROTECTED_API_URL = "https://your-api.com/data"
# if __name__ == "__main__":
# token = get_oauth_token(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, scope="read write")
# if token:
# print("Access Token obtained successfully.")
# api_data = make_authenticated_api_call(PROTECTED_API_URL, token)
# if api_data:
# print("API data fetched:", api_data)
# else:
# print("Failed to obtain access token.")
How it works: This Python snippet illustrates the OAuth 2.0 Client Credentials flow, commonly used for server-to-server communication where a user's explicit consent isn't required. It demonstrates how to send a `POST` request to a token endpoint with client credentials to receive an access token, then how to use this token in subsequent API calls via the `Authorization: Bearer` header, securing your API interactions.