Google Cloud Firestore Python Client
The `google-cloud-firestore` client library provides a Pythonic interface for interacting with Google Cloud Firestore. Firestore is a fully-managed, scalable NoSQL document database for mobile, web, and server development, offering real-time data synchronization and offline support. It is currently at version 2.26.0 and receives regular updates as part of the broader `google-cloud-python` client libraries.
Warnings
- breaking Version 2.0.0 introduced significant interface changes due to a next-gen code generator. Method calls shifted from positional/keyword parameters to a single `request` parameter. Code using `google.cloud.firestore_v1.gapic` namespaces will likely be incompatible. Python 3.6+ became a hard requirement.
- gotcha The Firestore client can hang indefinitely on authentication errors, especially when local `gcloud CLI` authentication tokens expire. This can manifest as scripts freezing without clear error messages.
- gotcha Queries involving multiple fields or specific operators (like `array-contains-any`, `in`) often require a composite index to be created in the Firestore console. Failing to do so results in a `FailedPrecondition: 400 The query requires an index` error at runtime.
- gotcha Confusing `google-cloud-firestore` with `firebase-admin`. While `firebase-admin` internally uses `google-cloud-firestore` for its Firestore interactions, they serve different purposes. `google-cloud-firestore` is the lower-level client for general GCP projects, while `firebase-admin` is tailored for Firebase-specific services and authentication, particularly for server-side code in a Firebase project.
- deprecated Support for older Python versions is progressively dropped. As of `firebase-admin` v7.0.0, Python 3.7 and 3.8 were dropped, and 3.9 was deprecated. `google-cloud-firestore` itself requires Python >= 3.7.
Install
-
pip install --upgrade google-cloud-firestore
Imports
- firestore.Client
from google.cloud import firestore db = firestore.Client()
Quickstart
import os
from google.cloud import firestore
# Ensure GOOGLE_APPLICATION_CREDENTIALS environment variable is set
# e.g., export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service_account_key.json"
# Or set programmatically (less secure for production):
# from google.oauth2 import service_account
# credentials = service_account.Credentials.from_service_account_file('path/to/your/service_account_key.json')
# db = firestore.Client(credentials=credentials)
def quickstart_firestore():
# Initialize Firestore DB client. It automatically uses Application Default Credentials.
# Make sure you have created a Firestore database in your GCP project first.
db = firestore.Client()
# Add a new document to a collection 'users'
doc_ref = db.collection('users').document('alovelace')
doc_ref.set({
'first': 'Ada',
'last': 'Lovelace',
'born': 1815
})
print(f"Added document: {doc_ref.id}")
# Read a single document
doc = doc_ref.get()
if doc.exists:
print(f"Document data: {doc.to_dict()}")
else:
print("No such document!")
# Query for documents
users_ref = db.collection('users')
docs = users_ref.where('born', '<', 1900).stream()
print("Users born before 1900:")
for doc in docs:
print(f"{doc.id} => {doc.to_dict()}")
if __name__ == '__main__':
# Placeholder for environment variable setup for local testing
# In production environments (e.g., GCE, Cloud Functions), credentials are often auto-discovered.
if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS'):
print("WARNING: GOOGLE_APPLICATION_CREDENTIALS environment variable not set. "
"Using default credentials if available, or client might fail.")
quickstart_firestore()