Google Cloud Firestore Python Client

2.26.0 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Firestore client, add a new document to a collection, retrieve a single document, and perform a basic query for documents. It assumes 'Application Default Credentials' are set up (e.g., via `gcloud auth application-default login` or by setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a service account key file path).

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()

view raw JSON →