简体   繁体   中英

Using Cloud Firestore REST API how to send data using http package with http.post() method

I have a collection called "txt" and would like to create a new document under that, with an auto-generated document Id, with the field 'test' and its value as 'title'.

I have the following code in Flutter which does not work:

Future<http.Response> _post() {
   
    String url =
        'https://firestore.googleapis.com/v1/projects/onebear-webapp/databases/(default)/documents/txt?key=AIzxSyAllNuEbN40DEvBPIQkcLIWn00c9TYWqY';
    return http.post(
      url,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        'test': 'title',
      }),
    );
  }

And it keeps giving errors as per below:

{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"test\" at 'document': Cannot find field.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "document",
            "description": "Invalid JSON payload received. Unknown name \"test\" at 'document': Cannot find field."
          }
        ]
      }
    ]
  }
}

I cant seem to figure out the error message and what the errors "Invalid JSON payload received." or "fieldViolations" mean - even though I'm encoding with jsonEncode.

Please any help or guidance on this very much appreciated. Thx!

I would suggest you have a look at these similar posts (1) (2) with other users running into similar issues.

If you want to update multiple fields and values, have you managed to try to specify each one separately? For example, your request body should look something like this:

{
"fields": {
   "field": {
   "stringValue": "Value1"
   },
"Field2": {
   "stringValue": "Value2"
  }
 }
}

Since it seems you are attempting to set up a string Hash. I would suggest you have a look at this documentation on map's field as it follows a different structure, for example: An object containing a list of "key": value pairs.

map (key: string, value: object (Value))

{ "name": "wrench", "mass": "1.3kg", "count": "3" }

Since jsonEncode looks to be a functionality specific to Flutter development, I would recommend bringing your question to the Flutter developers team as the they would be more knowledgeable of this implementation method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM