Search code examples
pythonapioauthibm-cloudcloud-foundry

How to authenticate to Bluemix CF API using Python


Let me preface by saying I'm probably overlooking something simple.

I'm attempting to script some manipulation of my Bluemix account with Python and the CF API.

First get to https://api.ng.bluemix.net/info to get the authorization_endpoint, https://login.ng.bluemix.net/UAALoginServerWAR/

response = requests.get('https://api.ng.bluemix.net/info')

Then post to authorization_endpoint to get oauth token.

results = response.json()
auth_endpoint = results['authorization_endpoint'] + 'oauth/token?grant_type=password&client=cf'
http_payload = {
    'username': id,
    'password': pw,
    'client_id': 'cf'
    }
auth = ('cf', '')
response = requests.post(auth_endpoint, data=http_payload, auth=auth)

Then use the returned oauth token to call the CF API, in this case https://api.ng.bluemix.net/v2/organizations.

results = response.json()
url = 'https://api.ng.bluemix.net/v2/organizations'
authorization = results['token_type'] + ' ' + results['access_token']
http_headers = {
    'accept': 'application/json',
    'content-type': 'application/json',
    'authorization': authorization
    }
response = requests.get(url, headers=http_headers)

But this results in a 404, {"description": "Unknown request", "error_code": "CF-NotFound", "code": 10000}. Is this the right approach? What am I overlooking?


Solution

  • This works for me:

    id = 'changeme'
    pw = 'changeme'
    
    import json
    import urllib
    import requests
    
    response = requests.get('https://api.ng.bluemix.net/info')
    results = response.json()
    auth_endpoint = results['authorization_endpoint'] + '/oauth/token'
    
    data = 'grant_type=password&username={0}&password={1}'.format(id, pw)
    auth = ('cf', '')
    headers = {
        'accept': 'application/json',
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        }
    response = requests.post(auth_endpoint, data=data, headers=headers, auth=auth)
    
    results = response.json()
    url = 'https://api.ng.bluemix.net/v2/organizations'
    authorization = results['token_type'] + ' ' + results['access_token']
    http_headers = {
        'accept': 'application/json',
        'content-type': 'application/json',
        'authorization': authorization
        }
    response = requests.get(url, headers=http_headers)
    
    print(response.text)
    

    Returns:

    {
      "total_results": 6,
      "total_pages": 1,
      "prev_url": null,
      "next_url": null,
      "resources": [
      ...
    }