簡體   English   中英

使用 Python 訪問 Google Fit REST API

[英]Accessing Google Fit REST API using Python

我想在服務器上使用 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"

但是每當我在 rest 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 中提到的所有可用數據源。

這里有什么問題?

花了很多小時后,問題的解決方案如下。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM