CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-firebase-admin

Firebase Admin Python SDK enables server-side Python developers to integrate Firebase services into their applications from privileged environments.

Pending
Overview
Eval results
Files

firestore.mddocs/

Cloud Firestore

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.

Capabilities

Client Access

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
    """

Google Cloud Firestore Integration

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.

Core Operations Available

The Firestore client provides access to all standard Firestore operations:

  • Document Operations: Create, read, update, delete individual documents
  • Collection Operations: List, query, and manage document collections
  • Batch Operations: Perform multiple operations atomically
  • Transaction Operations: Execute operations within ACID transactions
  • Query Operations: Complex filtering, ordering, and pagination
  • Real-time Listeners: Subscribe to document and query changes
  • Security Rules: Manage Firestore security rules

Common Usage Patterns

Document 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 and Query Operations

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

Batch Operations

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

Transactions

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)

Real-time Listeners

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

Advanced Features

Sub-collections

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

Field Transforms

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

Geographic Queries

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 GeoFire

Multi-Database Support

For 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'})

Error Handling

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}')

Performance Considerations

  • Batch Operations: Use batch writes for multiple operations
  • Transaction Limits: Transactions have size and time limits
  • Index Creation: Complex queries may require composite indexes
  • Real-time Listeners: Unsubscribe when no longer needed
  • Connection Pooling: Reuse the same client instance

Types

# 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 transform

Install with Tessl CLI

npx tessl i tessl/pypi-firebase-admin

docs

app-management.md

authentication.md

firestore.md

functions.md

index.md

machine-learning.md

messaging.md

project-management.md

realtime-database.md

remote-config.md

storage.md

tenant-management.md

tile.json