PYTHON

Secure Server-to-Server API Access with OAuth 2.0 Client Credentials Grant (Python)

Learn to implement the OAuth 2.0 Client Credentials grant flow in Python for secure, server-to-server authentication with external APIs using `requests`.

import requests
import os

# Configuration (ideally from environment variables)
CLIENT_ID = os.getenv('OAUTH_CLIENT_ID', 'your_client_id')
CLIENT_SECRET = os.getenv('OAUTH_CLIENT_SECRET', 'your_client_secret')
TOKEN_URL = os.getenv('OAUTH_TOKEN_URL', 'https://auth.example.com/oauth/token')
API_BASE_URL = os.getenv('API_BASE_URL', 'https://api.example.com/v1')
SCOPE = os.getenv('OAUTH_SCOPE', 'read write') # Optional, depending on API

def get_access_token():
    """Fetches an access token using the Client Credentials grant."""
    payload = {
        'grant_type': 'client_credentials',
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'scope': SCOPE
    }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }

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

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

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

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

# Main execution flow
if __name__ == "__main__":
    token = get_access_token()
    if token:
        print("Successfully obtained access token.")
        # Example: Fetch some data from a protected endpoint
        data = call_protected_api('resources', token)
        if data:
            print("API Response:", data)
    else:
        print("Failed to obtain access token.")
How it works: This Python snippet demonstrates how to securely access an API using the OAuth 2.0 Client Credentials grant type. This flow is ideal for server-to-server communication where there's no user involvement. It obtains an access token by sending client credentials to a token endpoint, then uses that token in the Authorization header as a Bearer token to make requests to protected API resources. Environment variables are used for sensitive configuration.

Need help integrating this into your project?

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

Hire DigitalCodeLabs