PYTHON

Secure API Calls with OAuth 2.0 Client Credentials

Learn to securely authenticate server-to-server API requests using the OAuth 2.0 Client Credentials flow in Python, obtaining an access token for protected resources.

import requests
import os

# Environment variables for client credentials
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_access_token():
    """
    Obtains an access token using the OAuth 2.0 Client Credentials flow.
    """
    if not CLIENT_ID or not CLIENT_SECRET:
        raise ValueError("OAUTH_CLIENT_ID and OAUTH_CLIENT_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_data = response.json()
        return token_data.get("access_token")
    except requests.exceptions.RequestException as e:
        print(f"Error obtaining access 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(f"{API_BASE_URL}/protected-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__":
    token = get_access_token()
    if token:
        print("Access token obtained successfully.")
        api_data = call_protected_api(token)
        if api_data:
            print("Protected API data:", api_data)
        else:
            print("Failed to retrieve data from protected API.")
    else:
        print("Failed to obtain access token.")
How it works: This snippet demonstrates the OAuth 2.0 Client Credentials flow, used for server-to-server authentication without user involvement. It first requests an access token from an OAuth provider using a client ID and secret. Once obtained, this bearer token is included in the `Authorization` header of subsequent API calls to access protected resources, ensuring secure communication between services.

Need help integrating this into your project?

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

Hire DigitalCodeLabs