Search code examples
pythonpython-3.xpython-requestsmulesoftcloudhub

Received Authentication Denied as Response while trying to get the access token (for Cloudhub.io) with requests library


I'm tying to get the data from the Cloudhub API which resides on Mulesoft.

I tried to access through postman (With the same Client Credentials - Bearer Authorization) and it's working fine (I can able to get the result with proper get requests).

But when I tried to do the same with Python requests library I ran into issues. Here is my piece of code:

import requests
import json, os
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
headers = {'Accept': '*/*',
           'Cache-Control':'no-cache',
           'Accept-Encoding': 'gzip, deflate',
           'Content-Type':'application/json, application/x-www-form-urlencoded',
           'Connection': 'keep-alive'}
url='https://<domain-name>-api.us-w2.cloudhub.io/api/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET), headers= headers)
token_raw = json.loads(response.text)
print(token_raw)

Result: {'error': 'Authentication denied.'}

All I need to know is How it's working fine with Postman but why I'm not able to connect with python code?

Is there anything I've to change in my code or any additional information needed for this request? or am I passing the correct endpoint in receiving the access token for Cloudhub API?

Please post your suggestions or any documentation that I need to refer. Hope the information that I gave is clear and Thanks in Advance !!


Solution

  • I found the answer of my own question. I can get it from the postman itself.

    Here is my code for API Call with Python.

    import http.client
    import os
    conn = http.client.HTTPSConnection("<domain-name>-api.us-w2.cloudhub.io")
    payload = ''
    headers = {
      'client_id': os.environ['CLIENT_ID'],
      'client_secret': os.environ['CLIENT_SECRET']
    }
    conn.request("GET", "/api/<Query that you want to pass - endpoint>", payload, headers)
    response = conn.getresponse()
    resp_data = response.read()
    print(resp_data.decode("utf-8"))