PYTHON

Secure API Integrations with OAuth 2.0 Client Credentials Flow

Master server-to-server authentication for APIs using the OAuth 2.0 Client Credentials Grant flow in Python, ensuring secure and automated access without user interaction.

import requests
import os

# Configuration
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')
CLIENT_ID = os.getenv('OAUTH_CLIENT_ID', 'your_client_id')
CLIENT_SECRET = os.getenv('OAUTH_CLIENT_SECRET', 'your_client_secret')
SCOPE = os.getenv('OAUTH_SCOPE', 'read write')

class OAuthClientCredentialsApi:
    def __init__(self):
        self._access_token = None
        self._token_expiry = 0 # Unix timestamp

    def _get_access_token(self):
        if self._access_token and self._token_expiry > time.time() + 60: # Refresh 1 min before expiry
            return self._access_token

        print("Refreshing OAuth token...")
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {
            'grant_type': 'client_credentials',
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET,
            'scope': SCOPE
        }
        try:
            response = requests.post(TOKEN_URL, headers=headers, data=payload)
            response.raise_for_status() # Raise an exception for HTTP errors
            token_data = response.json()
            self._access_token = token_data['access_token']
            self._token_expiry = time.time() + token_data.get('expires_in', 3600)
            return self._access_token
        except requests.exceptions.RequestException as e:
            print(f"Error getting OAuth token: {e}")
            raise

    def make_api_request(self, method, endpoint, **kwargs):
        access_token = self._get_access_token()
        headers = kwargs.pop('headers', {})
        headers['Authorization'] = f'Bearer {access_token}'
        
        url = f"{API_BASE_URL}{endpoint}"
        try:
            response = requests.request(method, url, headers=headers, **kwargs)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error making API request to {url}: {e}")
            raise

# Usage:
# import time
# api = OAuthClientCredentialsApi()
# try:
#     # Example GET request
#     data = api.make_api_request('GET', '/users')
#     print("Users:", data)

#     # Example POST request
#     # new_user = {'name': 'John Doe', 'email': '[email protected]'}
#     # created_user = api.make_api_request('POST', '/users', json=new_user)
#     # print("Created User:", created_user)
# except Exception as e:
#     print(f"API interaction failed: {e}")
How it works: This Python code demonstrates how to authenticate with an API using the OAuth 2.0 Client Credentials Grant flow. This flow is ideal for server-to-server communication where no user interaction is involved. The `OAuthClientCredentialsApi` class handles obtaining and refreshing an access token automatically, abstracting away the authentication details so you can securely make requests to the protected API endpoints.

Need help integrating this into your project?

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

Hire DigitalCodeLabs