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:
- You're using the BubbleWrap HTTP library.
- 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!
Written by Tom Milewski
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#