Home > OS >  Make a Request to Google Fit API in Python
Make a Request to Google Fit API in Python

Time:10-22

I am trying to call the Google Fit API with Python but the example for sessions is not working for me. The example provided by google:

GET https://fitness.googleapis.com/fitness/v1/users/me/sessions?activityType=97 HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json

My code

@api_view(['GET'])
def googleFitView(request):
    social_token = SocialToken.objects.get(account__user=2)
    token=social_token.token

    url_session= "https://fitness.googleapis.com/fitness/v1/users/me/sessions"
    
    headers = {
        "Authorization": "Bearer {}".format(token),
        "Accept": "application/json"
        }

    session_call = requests.post(url_session, headers=headers)

    return Response(session_call)

If I call another API of Google Fit, it is working. So, the authentication is not a problem. I followed the documentation and calling to the session endpoint does not require a body

@api_view(['GET'])
def googleFitView(request):
    social_token = SocialToken.objects.get(account__user=2)
    token=social_token.token
    url = "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate"

    headers = {
        "Authorization": "Bearer {}".format(token),
        "Content-Type": "application/json;encoding=utf-8",
        }

    body = {
        "aggregateBy": [{
            "dataTypeName": "com.google.activity.segment",
      
        }],

        "startTimeMillis": 1634767200000,
        "endTimeMillis": 1634853600000
        }
    
    
    respo = requests.post(url, data=json.dumps(body), headers=headers)

    return Response(respo)

CodePudding user response:

Look like you want to make a GET call but you are calling POST in below method googleFitView

@api_view(['GET'])
def googleFitView(request):
    social_token = SocialToken.objects.get(account__user=2)
    token=social_token.token

    url_session= "https://fitness.googleapis.com/fitness/v1/users/me/sessions"
    
    headers = {
        "Authorization": "Bearer {}".format(token),
        "Accept": "application/json"
        }
    # session_call = requests.post(url_session, headers=headers)  -- This is a post call.
    session_call = requests.get(url_session, headers=headers)

    return Response(session_call)
  • Related