alfheim
alfheim

Reputation: 350

Google fit data not retrieved with python

I created a service account in Google API to retrieve fit data.

If I try in the API playground it works fine (I could see the different data sources available)

If I try with the following code:

from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/fitness.activity.read']
SERVICE_ACCOUNT_FILE = 'api-project-248165331787-5a2b3821f120.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
fit = googleapiclient.discovery.build('fitness', 'v1', credentials=credentials)

response = fit.users().dataSources().list(userId='me').execute()

print(response)

I get an empty list as response. What am I missing?

Thanks

Upvotes: 0

Views: 1085

Answers (1)

alfheim
alfheim

Reputation: 350

For anyone else that is searching a way to use python from a script to access fit data:

Go to google api console: https://console.cloud.google.com/apis/credentials?project=\<your project> :

  • click on "Create Credentials" -> OAuthClientId -> Application Type -> Desktop App
  • Download json credentials
  • run the following script:
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/fitness.activity.read']

def main():
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_console()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    fit = build('fitness', 'v1', credentials=creds)

    # Call the Drive v3 API
    response = fit.users().dataSources().list(userId='me').execute()
    ...

if __name__ == '__main__':
    main()

The script prompts an url, put that in the browser and write back the returned code in the script input.

Thanks @DalmTo for the tips provided

Upvotes: 2

Related Questions