PYTHON

Implementing OAuth 2.0 Client Credentials Flow

Authenticate your server-side applications with external APIs using the OAuth 2.0 Client Credentials flow for secure, application-level access.

import requests
import os

# Configuration (store securely, e.g., in environment variables)
CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")
CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")
TOKEN_URL = "https://api.example.com/oauth/token"
API_BASE_URL = "https://api.example.com/data"

def get_oauth_token():
    """Fetches an OAuth 2.0 access token using client credentials."""
    if not CLIENT_ID or not CLIENT_SECRET:
        raise ValueError("OAuth client ID and secret must be set as environment variables.")

    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET
    }

    try:
        response = requests.post(TOKEN_URL, headers=headers, data=data)
        response.raise_for_status() # Raise an exception for HTTP errors
        token_info = response.json()
        return token_info.get("access_token")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching OAuth token: {e}")
        return None

def call_protected_api(access_token):
    """Calls a protected API endpoint using the obtained access token."""
    if not access_token:
        print("No access token available to call the API.")
        return None

    headers = {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json"
    }

    try:
        response = requests.get(API_BASE_URL + "/resource", headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error calling protected API: {e}")
        return None

if __name__ == "__main__":
    # Example usage:
    # Set environment variables:
    # export OAUTH_CLIENT_ID="your_client_id"
    # export OAUTH_CLIENT_SECRET="your_client_secret"

    token = get_oauth_token()
    if token:
        print("Access Token obtained successfully.")
        api_data = call_protected_api(token)
        if api_data:
            print("API Data received:")
            # print(api_data) # Uncomment to see actual data
        else:
            print("Failed to retrieve API data.")
    else:
        print("Failed to obtain access token.")
How it works: This snippet demonstrates how a backend application can securely authenticate with an external API using the OAuth 2.0 Client Credentials flow. It fetches an access token by sending client ID and secret, then uses this bearer token to authorize subsequent calls to protected API endpoints, ensuring server-to-server communication remains secure and authorized.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs