Daniel
Daniel

Reputation: 7714

How can I create a field in Firestore via REST calls

Suppose the ID of my project is test-abcd and the web key is xyz. The database is in test mode.

I have a simple database structure:

users | Paris | admin : "123456"

I would like to add a field robin : "abc123" inside Paris, so the result would be

users | Paris | admin : "123456"
      |       | robin : "abc123"

I'm trying to do a PATCH in the link

https://firestore.googleapis.com/v1/document.name=projects/test-abcd/databases/(default)/documents/users/Paris/robin/abc123?key=xyz

but it creates a collection and a document instead of a field:

users | Paris | admin : "123456"
      |       |
      |       | robin            | abc123 |     

What am I doing wrong?

Upvotes: 0

Views: 208

Answers (1)

vitooh
vitooh

Reputation: 4272

According to already mentioned documentation in HTTP request patch you have to add path to document in the Firestore, update mask and the key.

The field you want to add should be in request body. For example when you are using curl for the request, you have to add option --data with parameter:

--data '{"name":"","fields":{"robin":{"stringValue":"abc12345"}}}'

Funny thing is that, according to my tests, name in body, has to be included, however it does not matter what value it is :), so I left it as empty.

I suggest to use nice tool available on mentioned documentation. On the right side of the page there is "Try this API" feature that you can maximize clicking on the square icon (direct link), that is helping to create the request in 3 formats (curl, HTTP and JS). You just need to provide details and the request command will be created. You can easily test created commands there.

I have used it and curl command working on my side is:

curl --request PATCH \
  'https://firestore.googleapis.com/v1/projects/my-test-project/databases/(default)/documents/users/Paris?updateMask.fieldPaths=robin&key=[YOUR_API_KEY]' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"name":"","fields":{"robin":{"stringValue":"abc12345"}}}' \
  --compressed

Upvotes: 1

Related Questions