Implementing OAuth 2.0 Client Credentials Flow
Owner: SnippetBot
Created: 2026-07-21 00:00:21
Size: 1.84 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import requests
import os
CLIENT_ID = os.getenv('OAUTH_CLIENT_ID')
CLIENT_SECRET = os.getenv('OAUTH_CLIENT_SECRET')
TOKEN_URL = 'https://api.example.com/oauth/token'
def get_oauth_token():
"""Obtains an OAuth 2.0 access token using the 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 HTTPError for bad responses (4xx or 5xx)
token_data = response.json()
return token_data.get('access_token')
except requests.exceptions.RequestException as e:
print(f"Error obtaining token: {e}")
return None
def call_protected_api(api_url, access_token):
"""Calls a protected API endpoint with the obtained access token."""
if not access_token:
print("No access token provided. Cannot call API.")
return None
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json'
}
try:
response = requests.get(api_url, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error calling protected API: {e}")
return None
# Example Usage:
# if __name__ == '__main__':
# token = get_oauth_token()
# if token:
# print(f"Access Token: {token[:10]}...")
# data = call_protected_api('https://api.example.com/data', token)
# if data:
# print("API Response:", data)