pythonapimulesoftcloudhub

How to Authorize myself to mulesoft/cloudhub account from python?


I have to download logs from mulesoft/cloudhub from python. I have tried fetching logs from command prompt and it was successfull. what I tried in CMD is -

   1. curl -d "username=<my_username>&password=<my_password>" https://anypoint.mulesoft.com/accounts/login
   2. curl -H "Authorization: Bearer <access token>" -H "X-ANYPNT-ENV-ID: <environment ID>" "https://anypoint.mulesoft.com/cloudhub/api/v2/applications/<domain>/instances/<instance ID>/log-file" 

I tried the following code in python-

import http.client

headers = {'X-ANYPNT-ENV-ID': '{env id}'}

conn = http.client.HTTPSConnection('anypoint.mulesoft.com')
conn.request('GET','/cloudhub/api/v2/applications/{domain}/instances/{instanceId}/logs', urlencode(headers))
res = conn.getresponse()

data = res.read()
print(res.status, res.reason)
print(data.decode('utf-8'))
print(res.getheaders())

But I got the following error-

{"error":"Unauthorized","message":"Failed to create session. You must provide a valid Authorization header"}

I am new to mulesoft, so a detailed answer would be appreciated. Thanks.


Solution

  • Finally after so many trails, i got the answer. I needed to encode my username and password and then pass it, as shown below-

    a = bytes('<my_usermame>:<my_password>', 'ascii')
    userAndPass = b64encode(a).decode("ascii")
    
    headers = {'Authorization' : 'Basic %s' %userAndPass , 'X-ANYPNT-ENV-ID': '<my_env_id> }
    
    conn = http.client.HTTPSConnection('anypoint.mulesoft.com')
    conn.request('GET','/cloudhub/api/v2/applications/{domain}/instances/{instanceId}/logs', headers=headers)
    res = conn.getresponse()
    data = res.read()
    print(res.status, res.reason)
    print(data.decode('utf-8'))
    

    Also added headers=headers instead of urlencode(headers) whiel making the request.