Granting authorization to the API with Python

Heading over to Python, you will now create a program to grant authorization to the API. Begin by running the following command in your command line/terminal to install the required python package.

python -m pip install requests

This command may vary by operating system, you may need to change 'python' to 'python3'. Also, ensure your PATH environment variable is properly set for python.

  1. Create a new python program under fetchtoken.py name.
  2. Import the requests package with the following command.
import requests
  1. Define the tokenURL, clientid, and clientsecret variables by running the following.
tokenURL = 'http://your-openiam-instance/idp/oauth2/token'
clientid = 'yourclientid'
clientsecret = 'yourclientsecret'
  1. Create a function for obtaining an authentication token by the following program.
def getToken():
# Config
token_url = tokenURL
client_id = clientid
client_secret = clientsecret
# Request token
response = requests.post(token_url, data={
'grant_type': 'client_credentials'
}, auth=(client_id, client_secret))
if response.status_code == 200:
token_data = response.json()
access_token = token_data.get('access_token')
if not access_token:
print('Error: Access token not found in the response')
else:
print(f'Error: {response.status_code}, {response.text}')
return access_token
  1. An optional step is printing the authentication token to the terminal for testing by running the following command.
print(getToken())

When you run the file, you should get an auth token printed to your terminal, e.g.

PS C:\Users\maxim\OneDrive\Desktop\openiam\restapi> python fetchtoken.py
INwAgD9qSmS-EOlD-YF9JDUheohKk.cR0WCvW--Y.oxoxgR8SNw6m

The finished program should look as follows.

import requests
tokenURL = 'http://192.168.86.28:8080/idp/oauth2/token'
clientid = 'D051B01D50B14096AB1F3D91B2ED7EF3'
clientsecret ='5a0db7b3f7b8ff31b9a55cf5c16a7afa502d933021d1744b8e3941dea3f56d1a'
def getToken():
# Config
token_url = tokenURL
client_id = clientid
client_secret = clientsecret
# Request token
response = requests.post(token_url, data={
'grant_type': 'client_credentials'
}, auth=(client_id, client_secret))
if response.status_code == 200:
token_data = response.json()
access_token = token_data.get('access_token')
if not access_token:
print('Error: Access token not found in the response')
else:
print(f'Error: {response.status_code}, {response.text}')
return access_token