Hey there, fellow code wranglers! Ready to get your hands dirty with the Runkeeper API? We're about to embark on a journey to integrate this fitness powerhouse into your Ruby project. Buckle up, because by the end of this guide, you'll be pulling and pushing fitness data like a pro.
Before we dive in, make sure you've got:
httparty
and oauth2
gems (your new best friends)Let's kick things off:
mkdir runkeeper_integration cd runkeeper_integration bundle init
Now, crack open that Gemfile and add:
gem 'httparty' gem 'oauth2'
Run bundle install
, and we're off to the races!
Runkeeper uses OAuth 2.0, so let's get that sorted:
require 'oauth2' client = OAuth2::Client.new( 'YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', site: 'https://runkeeper.com', authorize_url: '/apps/authorize', token_url: '/apps/token' ) # Generate the authorization URL auth_url = client.auth_code.authorize_url(redirect_uri: 'YOUR_REDIRECT_URI') # After user authorizes, you'll get a code. Use it to get the access token: token = client.auth_code.get_token('AUTHORIZATION_CODE', redirect_uri: 'YOUR_REDIRECT_URI')
Now that we're authenticated, let's make some requests:
require 'httparty' class RunkeeperAPI include HTTParty base_uri 'https://api.runkeeper.com' def initialize(access_token) @headers = { 'Authorization' => "Bearer #{access_token}" } end def get_user_info self.class.get('/user', headers: @headers) end # Add more methods for other endpoints end api = RunkeeperAPI.new(token.token) user_info = api.get_user_info
Let's add some meat to our API wrapper:
class RunkeeperAPI # ... previous code ... def get_activities(page = 0, limit = 20) self.class.get("/fitnessActivities?page=#{page}&limit=#{limit}", headers: @headers) end def post_activity(activity_data) self.class.post('/fitnessActivities', headers: @headers, body: activity_data.to_json) end end
Parsing the JSON is a breeze with Ruby:
activities = api.get_activities activities['items'].each do |activity| # Do something with each activity puts "Activity type: #{activity['type']}, Duration: #{activity['duration']}" end
Want to get fancy? Let's set up a webhook:
post '/webhook' do # Verify the signature # Process the incoming data # Respond with a 200 OK end
Don't forget to test! Here's a quick example using RSpec:
RSpec.describe RunkeeperAPI do it 'fetches user info' do api = RunkeeperAPI.new('fake_token') allow(RunkeeperAPI).to receive(:get).and_return({ 'name' => 'John Doe' }) expect(api.get_user_info['name']).to eq('John Doe') end end
When deploying, remember:
And there you have it! You've just built a solid Runkeeper API integration in Ruby. You're now equipped to create some seriously cool fitness apps. Remember, the Runkeeper API docs are your friend for diving deeper.
Now go forth and code something awesome! πͺπΌπββοΈπ