Firestore Emulator — Edit Docs with Python
This is a code dump of something I had to look around a bit for and didn’t find it readily or easily available — how to set/edit/read local Firestore collections and docs in the emulator.
When starting the emulator, you might want to pre-create some documents to bootstrap the app data. One way would be to restore earlier data. This can be done with:
firebase emulators:start --import=./emulator_data --export-on-exit
Alternatively, you might want to start afresh but seed some required data. You can use a variation of the below code to do that.
You need to set two environment variables FIRESTORE_EMULATOR_HOST and FIRESTORE_PROJECT_ID. You can see the port used by Firebase in the firebase.json file.
import os
import sys
import firebase_admin
from firebase_admin import auth, credentials, firestore
try:
os.environ["FIRESTORE_EMULATOR_HOST"] = "localhost:8080"
os.environ["FIRESTORE_PROJECT_ID"] = "my-project-id" # use the project id for your project
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred)
db = firestore.client()
# Create organization document
org_id = "org1"
org_data = {
'displayName': "Org1"
}
org_ref = db.collection(u'orgs').document(org_id)
org_ref.set(org_data)
print("Documents stored successfully.")
except Exception as e:
print('Error!', e)
sys.exit(1)
p.s. code is intentionally super simple without any error checking as it is used for local data updates.