PYTHON

Securely Obtain OAuth 2.0 Access Token (Client Credentials)

Learn to securely obtain an OAuth 2.0 access token using the Client Credentials Flow, ideal for server-to-server API integrations in Python.

import requests
import os

# Environment variables are highly recommended for sensitive credentials
CLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'YOUR_CLIENT_ID')
CLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
TOKEN_URL = os.environ.get('OAUTH_TOKEN_URL', 'https://api.example.com/oauth/token')
SCOPE = 'read write' # Optional, depends on the API

def get_access_token():
    try:
        response = requests.post(
            TOKEN_URL,
            data={
                'grant_type': 'client_credentials',
                'client_id': CLIENT_ID,
                'client_secret': CLIENT_SECRET,
                'scope': SCOPE
            },
            headers={'Content-Type': 'application/x-www-form-urlencoded'}
        )
        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

if __name__ == "__main__":
    access_token = get_access_token()
    if access_token:
        print(f"Successfully obtained access token: {access_token[:10]}...")
        # Example: Use the token to make an authenticated API call
        # API_URL = 'https://api.example.com/data'
        # headers = {'Authorization': f'Bearer {access_token}'}
        # api_response = requests.get(API_URL, headers=headers)
        # print(api_response.json())
    else:
        print("Failed to obtain access token.")
How it works: This Python snippet demonstrates how to implement the OAuth 2.0 Client Credentials Grant Flow. It sends a POST request to the token endpoint with the `client_id`, `client_secret`, and `grant_type` to exchange credentials for an access token. This flow is ideal for server-to-server communication where there is no user involvement, providing secure authentication for your application to access protected API resources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs