【问题标题】:How to set the Doc Id with Firebase REST API如何使用 Firebase REST API 设置文档 ID
【发布时间】:2021-07-18 03:08:28
【问题描述】:

有没有办法在将文档插入 Firestore 时手动创建 docId?

以下 Python3 代码将使用自动生成的 docId 在 Firestore 中插入一个新文档。

import requests
import json

project_id = 'MY_PROJECT_NAME'
web_api_key = 'MY_WEB_API_KEY'
collection_name = 'MY_COLLECTION_NAME'
url = f'https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{collection_name}/?key={web_api_key}'

payload = {
    'fields': {
        'title': { 'stringValue': 'myTitle' },
        'category': { 'stringValue': 'myCat' },
        'temperature': { 'doubleValue': 75 }
    }
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.post(url, data=json.dumps(payload), headers=headers)

response_dict = json.loads(response.content)
for i in response_dict:
    print(f'{i}: {response_dict[i]}')

如果其他人想在将来使用此代码,要获取 Web API 密钥,请转到 Google Cloud Platform > APIs & Services > Credentials > Create Credentials > API key,然后在此处复制它生成的值。

谢谢, 瑞恩

【问题讨论】:

    标签: python firebase rest google-cloud-firestore


    【解决方案1】:

    要设置自定义文档 ID,您只需要将名称附加到相应集合之后的 URL 路径。这类似于文档引用的工作方式,其中路径必须指向所需位置。

    来自文档:

    https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA
    

    【讨论】:

    • 我收到错误“错误:{'code': 400, 'message': 'Document parent name "projects/fore-3610f/databases/(default)/documents/SensorData" 缺少"/ “在索引 60 处。','状态':'INVALID_ARGUMENT'}”。我在哪里... url = f'firestore.googleapis.com/v1/projects{project_id}/databases/(default)/documents/SensorData/abc123/?key={web_api_key}'
    • 对我有用:你应该仔细检查你的路径结构,并确保你在需要的地方有/
    • 在正常使用下,“...databases/(default)/documents/cities/LA”可以工作,但它不适用于我的 REST API
    • 你试过不带尾随/吗?阅读诸如engineering.flosports.tv/… 之类的文档不会在末尾显示/,因此它可能会假设第二个路径名
    【解决方案2】:

    Google Cloud Firestore REST API createDocument auto genarates ID中回答的文档ID应该在创建文档时作为查询参数添加

    所以对于问题中的代码,只需将 url 更改为相同的正文:

    url = f'https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/{collection_name}?documentId={your_custom_doc_id}&key={web_api_key}'
    

    【讨论】:

    • @Yunnosch 您是对的,但是,您希望 DIDI Byte 的上述评论或示例可以算作一个完整的答案,但也许我错了,它丰富了人们的选择寻求答案。
    • 不是说它好,只是指出这上面的标志可能会被拒绝。
    猜你喜欢
    • 1970-01-01
    • 2013-12-21
    • 2012-06-03
    • 2022-01-04
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多