Sam Rosenberg
Sam Rosenberg

Reputation: 31

How do I get an access token using stravalib?

Using the sample code of stravalib I have worked on understanding how the program works what I have is as follows:

    from stravalib import Client

    code = request.args.get('code') # e.g.
    client = Client()
    access_token = client.exchange_code_for_token(client_id="Mas Rosenberg",
    client_secret="***********************************",
                                          code='code')

    client = Client(access_token)
    athlete = client.get_athlete()

    print("Hello, {}".format(athlete.firstname))

The 'code' with the # e.g. next to it, what should that be?

Upvotes: 1

Views: 1038

Answers (1)

wombat
wombat

Reputation: 21

In case anyone else had trouble with this I followed this slightly different tutorial: link here (so full credits to the guy!). Here you first refresh the access token:

import requests
from datetime import datetime
from stravalib.client import Client
import urllib3
urllib3.disable_warnings()


auth_url ="https://www.strava.com/oauth/token"
payload = {
    'client_id' : CLIENT_ID,
    'client_secret' : CLIENT_SECRET,
    'refresh_token' : REFRESH_TOKEN,
    'grant_type' : "refresh_token",
    'f':'json'
}
print("Requesting the token...\n")
res = requests.post(auth_url,data=payload,verify=False)
print(res.json())
print()

access_token = res.json()['access_token']
expiry_ts = res.json()['expires_at']
print("New token will expire at: ",end='\t')
print(datetime.utcfromtimestamp(expiry_ts).strftime('%Y-%m-%d %H:%M:%S'))

client = Client(access_token=access_token)
athlete = client.get_athlete() 
print(f'Hello {athlete.firstname} {athlete.lastname}')

The tokens CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN can be accessed once logged in from https://www.strava.com/settings/api

Upvotes: 2

Related Questions