Unable to Access Genesys through Python Script

import PureCloudPlatformClientV2

def Authenicate():
apiclient = PureCloudPlatformClientV2.api_client.ApiClient().get_client_credentials_token(os.environ['Genesys_Client'], os.environ['Genesys_Secret'])
authApi = PureCloudPlatformClientV2.AuthorizationApi(apiclient)
print(authApi.get_authorization_permissions())

Output:
Traceback (most recent call last):
File "C:\XXXX\Genesys-Flask.py", line 28, in
Authenicate()
File "C:\XXXX\Genesys-Flask.py", line 19, in Authenicate
os.environ['Genesys_Client'],
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 679, in getitem
KeyError: 'Genesys_Client'

Hi,

Your environment variable names are most likely incorrect, I was able to replicate this by using environment variable that did not exist on my machine. The function works correctly for me with environment variables that exist.

Regards,
Declan

I've copied the Client ID and Secret ID, but it giving me the same error. Is there a port that require for this connection?

Hi,

As far as I know there's no ports involved. I don't think this is a problem with our code but I could be wrong. It's possible that even though the environment variable exists on your machine but your code can't access it. Try do a check to see if your code knows about the environment variables before you try to access them. Something like this:

if environment_variable_name in os.environ:
    print(f"The environment variable exists.")
else:
    print(f"The environment variable does not exist.")

Regards,
Declan

Where do i insert that if and else statement?
import PureCloudPlatformClientV2

apiclient = PureCloudPlatformClientV2.api_client.ApiClient().get_client_credentials_token(os.environ['GENESYS_ID'], os.environ['GENESYS_SECRET'])
authApi = PureCloudPlatformClientV2.AuthorizationApi(apiclient)
print(authApi.get_authorization_permissions())

Output:
Traceback (most recent call last):
File "C:\Users\XXXX\Python\Python\Genesys-Flask.py", line 9, in
apiclient = PureCloudPlatformClientV2.api_client.ApiClient().get_client_credentials_token(os.environ['GENESYS_ID'], os.environ['GENESYS_SECRET'])
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 679, in getitem
KeyError: 'GENESYS_ID'

Replace your code with this:

oauth_id_env_name = "GENESYS_ID"
oauth_secret_env_name = "GENESYS_SECRET"

try:
  if oauth_id_env_name in os.environ and oauth_secret_env_name in os.environ:
      apiclient = PureCloudPlatformClientV2.api_client.ApiClient().get_client_credentials_token(
          os.environ[oauth_id_env_name], os.environ[oauth_secret_env_name])
      authApi = PureCloudPlatformClientV2.AuthorizationApi(apiclient)
      print(authApi.get_authorization_permissions())
  else:
      raise Exception("The environment variable does not exist.")

except Exception as error:
  print("Error: " + repr(error))

This will throw an exception if one or both of the environment variables is not set

I've tried the code, but I got this error below. I've made sure that OAuth have Client Credentials and with Developer Roles.

"
Error: Exception('The environment variable does not exist.')
"

fyi- I am using Pycharm to run the code

The issue is not with your OAuth credentials or the Developer roles. Your python code can't find the environment variables that you are trying to access. The code sample I gave checks to see if your environment variables exist before it tries to access them. If the exception is being thrown it means the environment variables are not set or python can't find them for some reason.

How do i add the environment variable to Pycharm for it to search?

I found these steps by googling for "how to set environment variable in pycharm": python - How to set environment variables in PyCharm? - Stack Overflow

I've updated the environment in pycharm and did the sample code. CLIENT_ID and CLIENT_SECRET is correct in OAuth. I got this sample code from: https://developer.genesys.cloud/devapps/sdk/python

import PureCloudPlatformClientV2
from PureCloudPlatformClientV2 import ApiClient, Configuration
import base64, requests, sys, os

apiclient = PureCloudPlatformClientV2.api_client.ApiClient().get_client_credentials_token(os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'])
authApi = PureCloudPlatformClientV2.AuthorizationApi(apiclient)
print(authApi.get_authorization_permissions())

Output:
Traceback (most recent call last):
File "C:\Users\XXX\Python\Python\Genesys-Flask.py", line 5, in
apiclient = PureCloudPlatformClientV2.api_client.ApiClient().get_client_credentials_token(os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\XXX\AppData\Local\Programs\Python\Python311\Lib\site-packages\PureCloudPlatformClientV2\api_client.py", line 128, in get_client_credentials_token
response = self.request("POST", url,
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\XXX\AppData\Local\Programs\Python\Python311\Lib\site-packages\PureCloudPlatformClientV2\api_client.py", line 627, in request
return self.rest_client.POST(url,
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\XXX\AppData\Local\Programs\Python\Python311\Lib\site-packages\PureCloudPlatformClientV2\rest.py", line 225, in POST
return self.request("POST", url,
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\XXX\AppData\Local\Programs\Python\Python311\Lib\site-packages\PureCloudPlatformClientV2\rest.py", line 197, in request
raise ApiException(http_resp=r)
PureCloudPlatformClientV2.rest.ApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Date': 'Fri, 12 Apr 2024 14:27:00 GMT', 'Content-Type': 'application/json', 'Content-Length': '109', 'Connection': 'keep-alive', 'Critical-Origin-Trial': 'Tpcd', 'Inin-Correlation-Id': 'd31fdb5f-7480-4864-49eb-028a6710dee4', 'Origin-Trial': 'AqOjJ0UPIDlFmiW3hQcsQiGOIaWIXZRDDWLBHSQfBL84febGHre2kEqyi7ODn67QBfDd2AReJYkBe/YBEEFezgAAAABgeyJvcmlnaW4iOiJodHRwczovL215cHVyZWNsb3VkLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHBjZCIsImV4cGlyeSI6MTczNTM0Mzk5OSwiaXNTdWJkb21haW4iOnRydWV9', 'Strict-Transport-Security': 'max-age=31536000', 'Vary': 'Accept-Encoding'})
HTTP response body: {"error":"invalid_client","description":"authentication failed","error_description":"authentication failed"}

This means that authentication has failed and your client ID and/or secret are not valid in the region to which you're connecting. That means either you have a bug in your code, a typo in your id or secret, or you're using credentials from a different region. Your code example doesn't show setting the region, so if you're in a region other that us-east-1 (mypurecloud.com), you need to set it.

Thank you all. The issue has been resolved after add environment in the pycharm