将 POST 正文发送到 Firestore REST API 时出现问题

旺普拉特

我想使用 REST API 在 Firestore 中创建一个新文档。

这里使用 Axios 发送带有某些字段的 POST 请求的非常好的示例:https :
//www.jeansnyman.com/posts/google-firestore-rest-api-examples/

axios.post(
"https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/<COLLECTIONNAME>", 
    { 
        fields: { 
            title: { stringValue: this.title }, 
            category: { stringValue: this.category }, 
            post: { stringValue: this.post }, 
            summary: { stringValue: this.description }, 
            published: { booleanValue: this.published }, 
            created: { timestampValue: new Date() }, 
            modified: { timestampValue: new Date() } 
        } 
    }
    ).then(res => { console.log("Post created") })

这里有一个使用 Python 请求的示例:
使用 Firestore REST API 更新文档字段
(这是一个 PATCH 请求,但字段格式与 POST 请求中的相同)

import requests
import json

endpoint = "https://firestore.googleapis.com/v1/projects/[PROJECT_ID]/databases/(default)/documents/[COLLECTION]/[DOCUMENT_ID]?currentDocument.exists=true&updateMask.fieldPaths=[FIELD_1]"

body = {
    "fields" : {
        "[FIELD_1]" : {
            "stringValue" : "random new value"
        }
    }
}

data = json.dumps(body)

headers = {"Authorization": "Bearer [AUTH_TOKEN]"}
print(requests.patch(endpoint, data=data,  headers=headers).json())

我正在使用 Google Apps Script UrlFetchApp.fetch 发送我的请求。我可以毫无问题地使用 GET 请求。例如,要获取集合中的所有文档(在 Google Apps 脚本中):

function firestore_get_documents(){
  var options = {
    headers: { 'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken() },
    method:'GET'
  }
  var response = UrlFetchApp.fetch('https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/myCollection', options);
  var parsed = JSON.parse(response.getContentText());
  return parsed;
}

这很好用。并将“方法”更改为“POST”会按预期在 myCollection 中创建一个新文档。然后我尝试添加一个带有一些字段(或只有一个字段)的 POST 正文:

function firestore_create_new_document(){
  
  var options = {
    headers: { 'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken() },
    method:'POST',
    payload: {fields: { title: { stringValue: 'newTitle' } } }, // If you comment out this line, it works as expected
    muteHttpExceptions:true
  }
  var response = UrlFetchApp.fetch('https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/myCollection', options);
  var contentText = response.getContentText();
  var parsed = JSON.parse(response.getContentText());
  return parsed;
}

我收到以下错误:

code: 400 message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"
details[0][@type]: "type.googleapis.com/google.rpc.BadRequest"
details[0][fieldViolations][0][field]: "{title={stringValue=newTitle}}"
details[0][fieldViolations][0][description]: "Error expanding 'fields' parameter. Cannot find matching fields for path '{title={stringValue=newTitle}}'."

文档可在此处获得:
https : //firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents/createDocument https://firebase.google.com/docs/firestore/reference/rest/ v1/projects.databases.documents#Document

  1. 问题可能是我的“字段”对象的格式 - 我已经尝试了文档和示例中的几种不同格式
  2. 问题可能是这些字段还不存在?我想我应该能够创建一个包含新字段的新文档
  3. 问题可能与 UrlFetchApp.fetch 发送我的 JSON 正文的方式有关。我曾尝试使用 payload = JSON.stringify(payload_object) 并且这也不起作用。

我认为 UrlFetchApp 正在做一些与 Axios 或 Python 请求略有不同的事情 - 正文的发送方式不同,并且没有按预期进行解析。

Tanaike

下面的修改怎么样?

从:

var options = {
  headers: { 'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken() },
  method:'POST',
  payload: {fields: { title: { stringValue: 'newTitle' } } }, // If you comment out this line, it works as expected
  muteHttpExceptions:true
}

到:

var options = {
  headers: { 'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken() },
  method:'POST',
  payload: JSON.stringify({fields: { title: { stringValue: 'newTitle' } } }),
  contentType: "application/json",
  muteHttpExceptions:true
}
  • 当我测试上述修改后的请求时,我可以确认它有效。但如果发生其他错误,请告诉我。

参考:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将文件发送到API时出现问题

使用 Laravel 和 Guzzle 包将 Web API 发送到 Spotify 时出现问题

将DOCX发送到DocuSign REST API时出错

如何将请求正文中的列表值发送到Rest Api

尝试通过函数参数将正文发送到 API 时出现 KeyError

使用Django Rest Framework将输入文件从Vue.js发送到Django时出现问题

使用JQuery Mobile使用PHP,POST和JSON将数据发送到服务器时出现问题

在Redhat 7.5上将大尺寸的POST请求发送到R中的Plumber API端点时出现问题

使用Karate框架发送嵌套JSON作为请求以验证POST REST API方法时出现问题

将 JSON 字符串发送到需要对象数组的 API 时出现问题

使用 Java 将 Cucumber.json 文件发送到 Jira 的 Rest API post 请求

将JSON POST请求发送到PHP中的REST API

将对象的POST数组发送到REST API

PHP | 将JSON POST发送到API URL时出错

如何将 multipart/form-data 中的 HTTP POST 数据发送到 Perl 中的 REST API

将参数发送到 php rest api 调用

将路径变量发送到REST API

通过使用Axios.post将数据发送到后端,数据格式出现问题

将http post发送到ocr space api

使用 redux 将图像从 react 发布到 Django Rest API 时出现问题

将SOAP UI用于Marklogic SPARQL REST API时出现问题

在Django Rest框架中使用POST方法发送信息时出现问题

将HTTP请求发送到graphql API时出现“问题解析JSON”

通过$ .post问题将数组发送到PHP

在将经过身份验证的请求发送到OAuth2.0 Django rest Framwork时出现权限问题

从curl将数据发布到Firestore时出现问题

curl命令将压缩的POST正文发送到apache服务器

无法使用Java将POST请求中的ArrayList发送到REST服务器

将数据发送到Firestore很慢