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

393 views Asked by At

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.

2

There are 2 answers

0
Vidhya Dhara On BEST ANSWER

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.

0
aled On

The Python script is missing the first call to get the access token that is needed for the API request. The first curl request is for that. You need to add a conn.request to get the token, extract it and add the authorization header to the log request.