Ryan Loggerythm
Ryan Loggerythm

Reputation: 3314

How to set the Doc Id with Firebase REST API

Is there a way to manually create a docId when inserting a document into Firestore?

The following Python3 code will insert a new document in Firestore with an auto-generated docId.

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]}')

In case anyone else wants to use this code in the future, to get a Web API key, go to Google Cloud Platform > APIs & Services > Credentials > Create Credentials > API key, then copy the value it generates here.

Thanks, Ryan

Upvotes: 1

Views: 1093

Answers (2)

krv
krv

Reputation: 41

answered in Google Cloud Firestore REST API createDocument auto genarates ID documentId should be added as a query parameter when document is created

So for the code in the question, just url should be changed with the same body:

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

Upvotes: 4

DIGI Byte
DIGI Byte

Reputation: 4164

To set a custom document ID, you only need to append the name to the URL path after the respective collection. This is similar to how the document reference works where the path must point to the desired location.

From the documentation:

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

Upvotes: 0

Related Questions