【问题标题】:Authenticated API access to Firebase via REST API通过 REST API 对 Firebase 的经过身份验证的 API 访问
【发布时间】:2016-07-06 12:46:29
【问题描述】:
这出人意料地令人难以忍受。新的 Firebase + Python 没有任何文档。所以我正在尝试使用 REST API,它需要一种特殊的身份验证。
如您所见,他们说这可能是 应用程序的秘密(在新控制台中找不到)或 身份验证令牌(没有为 python 记录)。如果我单击 REST 身份验证文档,我会得到一个 Java 示例。
我已经下载了服务帐户的 JSON 密钥文件,并尝试应用在其他地方找到的代码片段,不幸的是没有成功。
任何人都可以提供有关如何进行此操作的提示吗?
【问题讨论】:
标签:
google-app-engine
firebase
firebase-realtime-database
service-accounts
【解决方案1】:
您需要使用Google API Python client library 从服务帐户 JSON 密钥文件生成访问令牌,然后将其添加到请求的标头中。
这是一个使用requests的示例
from oauth2client.service_account import ServiceAccountCredentials
import requests
import json
import httplib2
scopes = [
'https://www.googleapis.com/auth/firebase',
'https://www.googleapis.com/auth/userinfo.email',
"https://www.googleapis.com/auth/cloud-platform"
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'/pathto/json_file.json', scopes)
headers = {"content-type": "application/json; charset=UTF-8"}
headers['Authorization'] = 'Bearer ' + credentials.get_access_token().access_token
firebase_url = "https://docs-examples.firebaseio.com/rest/saving-data/fireblog/users/alanisawesome/name.json"
data = {
"name": "Alan Turing",
"birthday": "June 23, 1912"}
requests.put(firebase_url, headers=headers, data=json.dumps(data).encode("utf-8"))
您可以使用 pip 安装 google python api 客户端库:
pip install --upgrade google-api-python-client