Firebase Admin Python SDK

7.3.0 · active · verified Sun Apr 05

The Firebase Admin Python SDK enables server-side (backend) Python developers to integrate Firebase into their services and applications. It provides programmatic access to Firebase services from trusted environments, allowing for tasks such as custom authentication, managing user data, sending FCM messages, and accessing Cloud Firestore and Storage. The current version is 7.3.0, and it maintains a regular release cadence with frequent updates.

Warnings

Install

Imports

Quickstart

Initializes the Firebase Admin SDK using service account credentials (preferably from an environment variable) or Application Default Credentials. It then demonstrates connecting to Cloud Firestore, adding a new document to a collection, and reading all documents from that collection. Remember to replace placeholder project IDs and URLs, and secure your service account key.

import os
import firebase_admin
from firebase_admin import credentials, firestore

# Best practice: store service account key in an environment variable
# and load it, or use Application Default Credentials on Google Cloud.
# Replace 'path/to/your/serviceAccountKey.json' with actual path if not using env var.
SERVICE_ACCOUNT_KEY_PATH = os.environ.get('FIREBASE_SERVICE_ACCOUNT_KEY_PATH', '')

if SERVICE_ACCOUNT_KEY_PATH:
    cred = credentials.Certificate(SERVICE_ACCOUNT_KEY_PATH)
else:
    # Fallback for Google Cloud environments where ADC are available
    # or if you prefer not to use a file directly for local testing
    cred = credentials.ApplicationDefault()

# Initialize the app
firebase_admin.initialize_app(cred, {
    'projectId': os.environ.get('FIREBASE_PROJECT_ID', 'your-project-id'),
    'databaseURL': os.environ.get('FIREBASE_DATABASE_URL', 'https://your-project-id.firebaseio.com')
})

db = firestore.client()

# Add data to Firestore
doc_ref = db.collection('users').document('alovelace')
doc_ref.set({
    'first': 'Ada',
    'last': 'Lovelace',
    'born': 1815
})
print(f"Added document with ID: {doc_ref.id}")

# Read data from Firestore
users_ref = db.collection('users')
docs = users_ref.stream()

print("\nAll users:")
for doc in docs:
    print(f"{doc.id} => {doc.to_dict()}")

# Clean up (optional, for demonstration purposes)
# firebase_admin.delete_app(firebase_admin.get_app())

view raw JSON →