DEV Community


Posted on • Updated on

Add document ID to the firestore document in Python

Hi guys,
Today I want to share with you how to add the document ID to the firestore document before you push the data to firebase.
I think I can just skip the part where I explain you how to import firebase_admin to python, but I'll copy it anyways.

This is what you need to import ro make it work

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

Also you will need to set up your serviceAccountKey.json document. Find in the followig Link
She explains really nice how to set up firestore.

This part I really just copied it from that video and you can find it on firebase
cred = credentials.Certificate("serviceAccountKey.json")

db = firestore.client()

Here is what's important, we need to reference the document that is being created.

doc_ref = db.collection('plans').document('docName').collection('collection-name').document()

Now we are going to get the ID ONLY

docId =

Now we can set up out data using the docId variable to set up the id we need.

data = {
    'id': docId,
    'date': firestore.SERVER_TIMESTAMP,
    'bedroomLocation': 'Down',
    'bedrooms': 2,
    'category': 'Townhomes',
    'depth': 56,
    'garage': 'Yes',
    'garageType': 'Standard',
    'name': 'TEST PLAN FROM PYTHON',
    'sqf': 1460,
    'stories': 1,
    'width': 30,
Enter fullscreen mode Exit fullscreen mode

In my case I will be adding a test plan information.

At last, we need to push this data to the document we created previously.


Let me know if you find it useful or you think this could be done in a better way, I'm only a begginer :)

Discussion (0)