I am running a FastAPI backend application that saves data on Firestore. I would like to test using a test database, and want to use the Firebase Emulator Suite. My code is as follows:
from google.cloud import firestore
import firebase_admin
from firebase_admin import credentials
from dotenv import load_dotenv
load_dotenv()
cred = credentials.Certificate(
"my-project-firebase-adminsdk.json"
)
default_app = firebase_admin.initialize_app()
db = firestore.Client()
doc_ref = db.collection("business").document()
doc_ref.set({"name":"test"})
I have set the FIRESTORE_EMULATOR_HOST
,as instructed here (https://firebase.google.com/docs/emulator-suite/connect_firestore#admin_sdks) in my '.env' file, and can confirm the environment variables are loaded in.
GOOGLE_APPLICATION_CREDENTIALS="my-project.json"
FIRESTORE_EMULATOR_HOST="127.0.0.1:8080"
GCLOUD_PROJECT="my-project"
I have other GCP services (i.e. SecretManager), so I got service account credentials from GCP IAM.
I run the emulator just fine, and when I try to write data to the local Firestore instance, it gives me the following error in firestore-debug.log
file:
Multiple projectIds are not recommended in single project mode. Requested project ID google-cloud-firestore-emulator, but the emulator is configured for my-project. To opt-out of single project mode add/set the '"singleProjectMode": false' property in the firebase.json emulators config.
I don't have the project google-cloud-firestore-emulator
anywhere in my files. I have initialized firebase and the default project. The output of firebase use
shows:
Active Project: my-project
Project aliases for /user/code/dir:
* default (my-project)
Run firebase use --add to define a new project alias.
I can confirm that default_app
has the right project of my-project
:
However, for some reason, the db
has the project of google-cloud-firestore-emulator
.
I'm guessing it is because of this discrepancy that I am getting the error message and am unable to write data to the Firestore Emulator.
I realized that I needed to define the project within the Firestore Client instance.
db = firestore.Client("my-project")
I guess that if you specify:
FIRESTORE_EMULATOR_HOST="127.0.0.1:8080"
Then the client will default the project to google-cloud-firestore-emulator
and you have to respecify it.