Hey there, fellow code enthusiasts! Ready to dive into the world of Strava API integration? We'll be using the awesome stravalib package to make our lives easier. Whether you're building a fitness app or just want to play with your own running data, this guide will get you up and running in no time.
Before we jump in, make sure you've got:
Let's kick things off by installing stravalib:
pip install stravalib
Easy peasy, right?
Alright, time for the fun part - OAuth 2.0 flow. Don't worry, it's not as scary as it sounds:
from stravalib.client import Client client = Client() authorize_url = client.authorization_url(client_id=YOUR_CLIENT_ID, redirect_uri='http://localhost:8282/authorized') # Open this URL in a browser, authorize, and grab the 'code' from the redirect URL
Now, exchange that code for an access token:
token_response = client.exchange_code_for_token(client_id=YOUR_CLIENT_ID, client_secret=YOUR_CLIENT_SECRET, code=AUTHORIZATION_CODE) access_token = token_response['access_token']
With our token in hand, let's get some data:
client = Client(access_token=access_token) athlete = client.get_athlete() print(f"Hello, {athlete.firstname}!")
Want to see your recent adventures? Here's how:
activities = client.get_activities(limit=5) for activity in activities: print(f"{activity.name} - {activity.distance.num / 1000:.2f}km")
Feeling proud of that morning jog? Let's upload it:
client.upload_activity( activity_file=open('morning_run.gpx', 'rb'), data_type='gpx', name='Morning Run', description='Feeling pumped!' )
For the data nerds out there, let's grab some detailed activity data:
activity = client.get_activity(activity_id) streams = client.get_activity_streams(activity_id, types=['time', 'heartrate', 'watts'])
And how about checking out that segment you've been eyeing?
segment = client.get_segment(segment_id) leaderboard = client.get_segment_leaderboard(segment_id)
Remember to play nice with the API:
from stravalib import exc try: # Your API call here except exc.RateLimitExceeded as e: print(f"Oh no! Rate limit exceeded. Try again in {e.timeout} seconds.")
And there you have it! You're now equipped to build some seriously cool Strava integrations. Remember, the stravalib documentation is your best friend for diving deeper.
Now go forth and code something awesome! 🚴♂️🏃♀️💻