Firebase Admin Python SDK enables server-side Python developers to integrate Firebase services into their applications from privileged environments.
—
Firebase Cloud Firestore integration providing complete access to Google Cloud Firestore database operations including document and collection management, queries, transactions, and batch operations. All functionality from the Google Cloud Firestore client is available.
Get a Firestore client instance for database operations with optional database ID specification for multi-database projects.
def client(app=None, database_id=None):
"""
Return a client for interacting with the Cloud Firestore database.
Args:
app: Firebase app instance (optional)
database_id: Database ID for multi-database projects (optional)
Returns:
google.cloud.firestore.Client: Firestore client instance with full API access
"""The Firebase Admin SDK provides direct access to the complete Google Cloud Firestore client. All operations available in the google.cloud.firestore library are accessible through the client returned by the client() function.
The Firestore client provides access to all standard Firestore operations:
import firebase_admin
from firebase_admin import firestore
# Get Firestore client
db = firestore.client()
# Document reference
doc_ref = db.collection('users').document('user123')
# Create/Set document
doc_ref.set({
'name': 'John Doe',
'email': 'john@example.com',
'age': 30
})
# Get document
doc = doc_ref.get()
if doc.exists:
print(f'Document data: {doc.to_dict()}')
# Update document
doc_ref.update({
'age': 31,
'last_login': firestore.SERVER_TIMESTAMP
})
# Delete document
doc_ref.delete()# Collection reference
users_ref = db.collection('users')
# Add document with auto-generated ID
doc_ref = users_ref.add({
'name': 'Jane Smith',
'email': 'jane@example.com'
})
# Query collection
query = users_ref.where('age', '>=', 18).limit(10)
docs = query.stream()
for doc in docs:
print(f'{doc.id} => {doc.to_dict()}')
# Order and pagination
query = (users_ref
.order_by('name')
.limit(5))
results = query.get()# Create batch
batch = db.batch()
# Add operations to batch
doc_ref1 = db.collection('users').document('user1')
batch.set(doc_ref1, {'name': 'User 1'})
doc_ref2 = db.collection('users').document('user2')
batch.update(doc_ref2, {'status': 'active'})
doc_ref3 = db.collection('users').document('user3')
batch.delete(doc_ref3)
# Commit batch
batch.commit()from google.cloud.firestore import transactional
@transactional
def update_balance(transaction, account_ref, amount):
# Read current balance
account = account_ref.get(transaction=transaction)
current_balance = account.get('balance', 0)
# Update balance
new_balance = current_balance + amount
transaction.update(account_ref, {'balance': new_balance})
return new_balance
# Use transaction
account_ref = db.collection('accounts').document('account123')
transaction = db.transaction()
new_balance = update_balance(transaction, account_ref, 100)def on_snapshot(doc_snapshot, changes, read_time):
for doc in doc_snapshot:
print(f'Received document snapshot: {doc.id}')
# Document listener
doc_ref = db.collection('users').document('user123')
doc_watch = doc_ref.on_snapshot(on_snapshot)
# Collection listener
def on_collection_snapshot(col_snapshot, changes, read_time):
for change in changes:
if change.type.name == 'ADDED':
print(f'New document: {change.document.id}')
elif change.type.name == 'MODIFIED':
print(f'Modified document: {change.document.id}')
elif change.type.name == 'REMOVED':
print(f'Removed document: {change.document.id}')
collection_watch = db.collection('users').on_snapshot(on_collection_snapshot)
# Stop listening
doc_watch.unsubscribe()
collection_watch.unsubscribe()# Reference to sub-collection
subcollection_ref = (db.collection('users')
.document('user123')
.collection('orders'))
# Add document to sub-collection
subcollection_ref.add({
'product': 'Widget',
'quantity': 2,
'price': 29.99
})
# Query sub-collection
orders = subcollection_ref.where('price', '>', 20).get()from google.cloud.firestore import Increment, ArrayUnion, ArrayRemove
# Increment numeric field
doc_ref.update({
'page_views': Increment(1)
})
# Array operations
doc_ref.update({
'tags': ArrayUnion(['new-tag']),
'old_tags': ArrayRemove(['old-tag'])
})
# Server timestamp
doc_ref.update({
'updated_at': firestore.SERVER_TIMESTAMP
})from google.cloud.firestore import GeoPoint
# Store location
doc_ref.set({
'name': 'Coffee Shop',
'location': GeoPoint(37.7749, -122.4194)
})
# Note: Geographic range queries require additional setup
# and are typically done using external libraries like GeoFireFor projects with multiple Firestore databases:
# Default database
default_db = firestore.client()
# Named database
named_db = firestore.client(database_id='my-other-database')
# Use named database
doc_ref = named_db.collection('data').document('doc1')
doc_ref.set({'info': 'This is in the named database'})Firestore operations can raise various exceptions from the Google Cloud library:
from google.cloud.exceptions import NotFound, PermissionDenied, FailedPrecondition
try:
doc = db.collection('users').document('nonexistent').get()
if not doc.exists:
print('Document does not exist')
except NotFound:
print('Collection or document path not found')
except PermissionDenied:
print('Insufficient permissions')
except FailedPrecondition as e:
print(f'Failed precondition: {e}')# The client() function returns google.cloud.firestore.Client
# which provides access to all Firestore types and operations:
# Core types from google.cloud.firestore:
# - Client: Main Firestore client
# - CollectionReference: Reference to a collection
# - DocumentReference: Reference to a document
# - DocumentSnapshot: Document data snapshot
# - Query: Query builder
# - Transaction: Transaction context
# - WriteBatch: Batch operation builder
# - GeoPoint: Geographic point
# - SERVER_TIMESTAMP: Server timestamp sentinel
# - DELETE_FIELD: Field deletion sentinel
# - Increment: Numeric increment transform
# - ArrayUnion: Array union transform
# - ArrayRemove: Array remove transformInstall with Tessl CLI
npx tessl i tessl/pypi-firebase-admin