Hey there, fellow code enthusiasts! Ready to dive into the world of Strava API integration? Whether you're building a fitness app or just want to play with some cool athlete data, you're in the right place. We'll be using the awesome goosfraba/strava-sdk package to make our lives easier. Let's get those wheels spinning!
Before we hit the ground running, make sure you've got:
First things first, let's get that SDK installed. Fire up your terminal and run:
composer require goosfraba/strava-sdk
Easy peasy, lemon squeezy!
Now, let's initialize our Strava client. It's as simple as:
use Strava\API\Client; use Strava\API\Service\REST; $adapter = new GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3/']); $service = new REST($token, $adapter); // We'll get the token in the next step $client = new Client($service);
Time to get that authentication flowing:
$options = [ 'clientId' => YOUR_CLIENT_ID, 'clientSecret' => 'YOUR_CLIENT_SECRET', 'redirectUri' => 'YOUR_REDIRECT_URI' ]; $oauth = new OAuth($options); // Get authorization URL $authorizationUrl = $oauth->getAuthorizationUrl(['scope' => 'read,activity:read_all,activity:write']); // After user authorizes, handle the callback $code = $_GET['code']; $token = $oauth->getAccessToken('authorization_code', [ 'code' => $code ]);
Now for the fun part - let's grab some data!
// Get athlete info $athlete = $client->getAthlete(); // Get activities $activities = $client->getAthleteActivities(); // Upload an activity $client->uploadActivity($filePath, 'ride', 'My awesome ride', 'A great day out!');
Don't forget to play nice with the API:
try { $result = $client->getAthleteActivities(); } catch (RateLimitExceededException $e) { sleep(15 * 60); // Wait for 15 minutes $result = $client->getAthleteActivities(); } catch (Exception $e) { // Handle other exceptions }
Want to level up? Check out webhooks for real-time updates:
$client->createSubscription($callbackUrl, $verifyToken);
Pro tip: Use Strava's Sandbox environment for testing. And don't forget to log everything - your future self will thank you!
$logger = new Monolog\Logger('strava'); $client->setLogger($logger);
And there you have it, folks! You're now armed and ready to create some killer Strava integrations. Remember, the sky's the limit - or in this case, maybe it's the road ahead. Happy coding, and may your segments always be tailwind!
For more in-depth info, check out the goosfraba/strava-sdk documentation and the official Strava API docs. Now go forth and build something awesome!