使用Python访问Google Fit REST API

时间:2017-01-19 03:54:45

标签: android python rest google-api google-fit

我想在服务器上使用Google Fit REST API并对Fit数据执行CRUD操作。用户已通过身份验证,https://www.googleapis.com/auth/fitness.activity.write,https://www.googleapis.com/auth/fitness.body.read,https://www.googleapis.com/auth/fitness.body.write的权限已被授予适合应用的数据。用户通过身份验证后,服务器将收到UID和OAUTH_TOKEN。

UID = "XYZ"
OAUTH_TOKEN="FOO_BAR"
APP_SECRET_KEY = "XXX"
CLIENT_ID = "AAA"

但每当我在其他API上获取/发布时,它都会抛出401错误。

import requests
url = "https://www.googleapis.com/fitness/v1/users/%s/dataSources"% UID

headers = {'content-type': 'application/json','Authorization': "Bearer %s" % token}
r = requests.get(url, headers=headers)

print r.status_code
print r.content

输出

401
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

这应该列出https://developers.google.com/fit/rest/v1/get-started中提到的所有可用数据源。

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

花了很多时间后,解决问题的方法如下:

UserId应该是 me ,而access_token应该是最新的,因为访问令牌会在60分钟后到期。

UID = "XYZ"
OAUTH_TOKEN="FOO_BAR"
APP_SECRET_KEY = "XXX"
CLIENT_ID = "AAA"

import requests
url = "https://www.googleapis.com/fitness/v1/users/me/dataSources"

headers = { 'content-type': 'application/json',
            'Authorization': 'Bearer %s' % OAUTH_TOKEN }
r = requests.get(url, headers=headers)

print r.status_code
print r.content