Last Updated: February 25, 2016
·
1.335K
· tmilewski

Retrieving and using Heroku API keys in RubyMotion

I've been playing around with the Heroku API and ran into some trouble with making authenticated calls through RubyMotion.

I've pulled out and simplified two methods that I'm using to both retrieve a user's API key and then use it to list applications they own.

I make two assumptions along the way:

  1. You're using the BubbleWrap HTTP library.
  2. You prefer JSON over XML.

The code

Here's how to retrieve a user's API key by providing their username and password:

def retrieve_api_key(username, password)
  opts = {
    headers: {
      Accept: 'application/json'
    },
    payload: {
      username: username,
      password: password
    }
  }

  BW::HTTP.post("https://api.heroku.com/login", opts) do |res|
    if res.ok?
      json = BW::JSON.parse(res.body.to_s)
      puts json['api_key']
    else
      App.alert('Error')
    end
  end
end

You may now use the provided API key to make authenticated calls to Heroku on behalf of the user.

def retrieve_apps(api_key)
  encoded_auth = ":#{[api_key]}".pack('m0')

  opts = {
    headers: {
      Accept:         "application/json",
      Authorization:  "Basic #{encoded_auth}"
    }
  }

  BW::HTTP.get("https://api.heroku.com/apps", opts) do |res|
    puts res.body.to_s
  end
end

Hopefully this helps!