### Install Dependencies Source: https://github.com/firebase/firebase-admin-python/blob/main/AGENTS.md Install project dependencies using pip from the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/firebase/firebase-admin-python/blob/main/CONTRIBUTING.md Clone the repository and install project dependencies using pip. Ensure you have Python 3.9+ installed. ```bash git clone https://github.com/firebase/firebase-admin-python.git cd firebase-admin-python # go to the firebase-admin-python directory pip install -r requirements.txt # Install additional tools and dependencies ``` -------------------------------- ### Reference.start_at Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Creates a query that starts the results from a specified value. ```APIDOC ## Reference.start_at ### Description Specifies the starting point for a query, including results that are equal to or greater than the provided value. This is typically used in conjunction with an ordering method. ### Signature ```python def start_at(self, value) -> Query ``` ### Parameters #### Query Parameters - **value** (any) - Required - The value to start the query from. ### Usage ```python users = db.reference('/users').order_by_child('age').start_at(18).get() ``` ``` -------------------------------- ### Error Handling Example Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Demonstrates how to handle potential errors, such as `NotFound` exceptions, when performing download operations. ```APIDOC ## Error Handling ```python from google.cloud.exceptions import NotFound from firebase_admin import storage bucket = storage.bucket() try: blob = bucket.blob('file.txt') blob.download_to_filename('local.txt') except NotFound: print("File not found in bucket") except Exception as e: print(f"Download failed: {e}") ``` ``` -------------------------------- ### Install Firebase Admin Python SDK Source: https://github.com/firebase/firebase-admin-python/blob/main/README.md Use this command to install the Firebase Admin Python SDK. Ensure you have pip installed. ```bash pip install firebase-admin ``` -------------------------------- ### Task Name Format Example Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/functions.md Illustrates the standard naming convention for Cloud Tasks, including project, location, queue, and task ID. ```text projects/myproject/locations/us-central1/queues/myFunction/tasks/7a8b9c0d ``` -------------------------------- ### Select Firestore Database Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Demonstrates how to get clients for the default Firestore database and named databases within a project. ```python from firebase_admin import firestore # Default database db = firestore.client() # Named database analytics_db = firestore.client(database_id='analytics') users_db = firestore.client(database_id='users') ``` -------------------------------- ### Initialize Firebase App with Custom Options Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/README.md Provides an example of initializing a Firebase app with specific configuration options, including database URL, storage bucket, project ID, and HTTP timeout. This allows for fine-grained control over app behavior. ```python import firebase_admin app = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://myproject.firebaseio.com', 'storageBucket': 'myproject.appspot.com', 'projectId': 'myproject', 'httpTimeout': 60, 'databaseAuthVariableOverride': {'uid': 'admin'} }) ``` -------------------------------- ### Usage Pattern: Upload and Get URL Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Illustrates the process of uploading a file and constructing its public URL. ```APIDOC ### Usage Patterns: Upload and Get URL ```python from firebase_admin import storage bucket = storage.bucket() # Upload file blob = bucket.blob('profile-photos/user1.jpg') blob.upload_from_filename('photo.jpg') # Get public URL (if bucket is public) url = f"https://storage.googleapis.com/{bucket.name}/{blob.name}" print(f"Public URL: {url}") ``` ``` -------------------------------- ### Get App Option Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Retrieves an option value from the app's configuration. Use this to get specific settings like storage bucket or HTTP timeout. ```python bucket = app.options.get('storageBucket') timeout = app.options.get('httpTimeout', 120) ``` -------------------------------- ### Example Pull Request Body Source: https://github.com/firebase/firebase-admin-python/blob/main/AGENTS.md Summarize the problem, solution, testing strategy, and context sources for pull requests. Include a list of all AGENTS.MD files used. ```text feat(fcm): Added support for multicast messages This change introduces a new `send_each_for_multicast` method to the messaging client, allowing developers to send a single message to multiple tokens efficiently. Testing: Added unit tests in `tests/test_messaging.py` with mock requests and an integration test in `integration/test_messaging.py`. Context Sources Used: - id: firebase-admin-python ``` -------------------------------- ### Implement pagination for Firebase Realtime Database results Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Shows how to fetch data in pages using `order_by_key()`, `limit_to_first()`, and `start_at()`. This example retrieves the first page and then subsequent pages based on the last key. ```python # Get first page page_size = 10 ref = db.reference('/posts').order_by_key() page1 = ref.limit_to_first(page_size).get() # Get next page (using last key as starting point) if page1: last_key = list(page1.keys())[-1] page2 = ref.start_at(last_key).limit_to_first(page_size + 1).get() # Skip first item (which is last_key) page2 = {k: v for k, v in page2.items() if k != last_key} ``` -------------------------------- ### Import Users with Scrypt Hashing Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Batch imports users from another system, supporting various password hash algorithms. This example uses scrypt with specified rounds and memory cost. ```python from firebase_admin import auth users_to_import = [ auth.ImportUserRecord( uid='user1', email='user1@example.com', password_hash=b'hashed_password', password_salt=b'salt' ), auth.ImportUserRecord( uid='user2', email='user2@example.com', password_hash=b'hashed_password2', password_salt=b'salt2' ) ] result = auth.import_users( users_to_import, hash_algorithm=auth.UserImportHash.scrypt(rounds=8, memory_cost=14) ) print(f"Imported {result.success_count} users") ``` -------------------------------- ### Example Commit Message Body Source: https://github.com/firebase/firebase-admin-python/blob/main/AGENTS.md Provides a brief explanation of code changes for commits. Include details about the functionality added or fixed. ```text feat(fcm): Added `send_each_for_multicast` support for multicast messages Added a new `send_each_for_multicast` method to the messaging client. This method wraps the `send_each` method and sends the same message to each token. ``` -------------------------------- ### Error Handling for Certificate Credentials Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Provides example error handling for initializing Certificate credentials, catching common issues like FileNotFoundError and ValueError. ```python from firebase_admin import credentials import google.auth.exceptions try: cred = credentials.Certificate('key.json') except FileNotFoundError: print("Certificate file not found") except ValueError as e: print(f"Invalid certificate: {e}") ``` -------------------------------- ### Initialize Single Default App Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Initializes the default Firebase app with provided credentials and database URL. This is the standard setup for most applications. ```python import firebase_admin from firebase_admin import credentials, auth, db cred = credentials.Certificate('serviceAccountKey.json') app = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://myproject.firebaseio.com' }) # Use services with default app user = auth.get_user('user-id') ref = db.reference('/path') ``` -------------------------------- ### Start Query Results at a Specific Value Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Use `start_at()` with an ordering method to filter results, including only those that are greater than or equal to a specified value. This is useful for range queries. ```python users = db.reference('/users').order_by_child('age').start_at(18).get() ``` -------------------------------- ### Use Cloud Tasks Emulator Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/configuration.md Get a task queue, which will automatically use the emulator if `CLOUD_TASKS_EMULATOR_HOST` is set. This allows for local testing of background tasks. ```python from firebase_admin import functions queue = functions.task_queue('myFunction') ``` -------------------------------- ### Usage Pattern: Clean Up Old Files Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Provides an example of how to delete files older than a specified duration, useful for managing temporary storage. ```APIDOC ### Usage Patterns: Clean Up Old Files ```python from datetime import datetime, timedelta from firebase_admin import storage bucket = storage.bucket() # Delete files older than 30 days in the 'temp/' prefix cutoff = datetime.utcnow() - timedelta(days=30) print("Deleting files older than 30 days...") for blob in bucket.list_blobs(prefix='temp/'): if blob.updated < cutoff: print(f"Deleting {blob.name} (updated: {blob.updated})") blob.delete() print("Cleanup complete.") ``` ``` -------------------------------- ### Run RTDB Emulator with Firebase CLI Source: https://github.com/firebase/firebase-admin-python/blob/main/CONTRIBUTING.md Execute integration tests against the RTDB emulator locally. Ensure the Firebase CLI is installed and configured. ```bash firebase emulators:exec --only database --project fake-project-id 'pytest integration/test_db.py' ``` -------------------------------- ### Initialize Firebase App with Service Account Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Initialize a Firebase app using a service account key file for authentication. This is a common setup for server-side applications. ```python import firebase_admin from firebase_admin import credentials # Initialize with service account cred = credentials.Certificate('serviceAccountKey.json') app = firebase_admin.initialize_app(cred) ``` -------------------------------- ### get() - Retrieve App Option Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Retrieves a specific option value from the app's configuration. If the option key is not found, it returns a specified default value. ```APIDOC ## get() ### Description Retrieves an option value from the app's configuration. ### Method `get(key: str, default=None)` ### Parameters #### Path Parameters * **key** (str) - Required - Option key name * **default** (any) - Optional - Value to return if key not found ### Usage: ```python bucket = app.options.get('storageBucket') timeout = app.options.get('httpTimeout', 120) ``` ``` -------------------------------- ### Atomic multi-document update with batch Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Perform atomic updates on multiple documents using a batch. This example increments user points and logs the activity. ```python batch = db.batch() # Update user and log activity atomically batch.update(db.collection('users').document('user1'), { 'points': firestore.Increment(10) }) batch.set(db.collection('activity_log').document(), { 'user': 'user1', 'action': 'earned_points', 'timestamp': firestore.SERVER_TIMESTAMP }) batch.commit() ``` -------------------------------- ### Get Firebase Admin Python Version Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Retrieves the currently installed version of the Firebase Admin Python SDK. Access this via the __version__ attribute. ```python import firebase_admin print(firebase_admin.__version__) ``` -------------------------------- ### Example Commit Title Source: https://github.com/firebase/firebase-admin-python/blob/main/AGENTS.md Follows Conventional Commits specification for commit messages. Use 'feat', 'fix', or 'chore' as the type and the service package as the scope. ```bash fix(auth): Resolved issue with custom token verification ``` -------------------------------- ### Initialize App with Local gcloud ADC Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Initializes the Firebase app using Application Default Credentials found locally via gcloud. This simplifies local development setup. ```python from firebase_admin import credentials, initialize_app cred = credentials.ApplicationDefault() app = initialize_app(cred) ``` -------------------------------- ### Get Cloud Storage Bucket Handle Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Obtain a handle to a Cloud Storage bucket. Use the default bucket configured in app options or specify a bucket name. ```python from firebase_admin import storage # Use default bucket from app options bucket = storage.bucket() # Use specific bucket other_bucket = storage.bucket('my-other-bucket') ``` -------------------------------- ### Decoded JWT Claims Example Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md An example of the structure of the decoded JWT claims returned by verify_id_token. ```json { 'iss': 'https://securetoken.google.com/myproject', 'aud': 'myproject', 'auth_time': 1234567890, 'user_id': 'user123', 'sub': 'user123', 'iat': 1234567890, 'exp': 1234571490, 'email': 'user@example.com', 'email_verified': True, 'firebase': { 'identities': {'email': ['user@example.com']}, 'sign_in_provider': 'password', 'sign_in_second_factor': None, 'second_factor_identifier': None, 'tenant': None } } ``` -------------------------------- ### Initialize Firebase App with Certificate Credential from File Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Initializes a Firebase app using a service account key file. Ensure the file path is correct. ```python cred = credentials.Certificate('/path/to/serviceAccountKey.json') app = firebase_admin.initialize_app(cred) ``` -------------------------------- ### DELETE_ATTRIBUTE Usage Example Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/types.md Example of how to use the DELETE_ATTRIBUTE sentinel to remove a user's photo URL. This is useful for updating user profiles. ```python auth.update_user(uid='user-id', photo_url=auth.DELETE_ATTRIBUTE) ``` -------------------------------- ### Get Firestore Client Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Obtain a Firestore client instance. You can get the default database client or specify a particular database ID or App instance. ```python from firebase_admin import firestore # Get default Firestore database db = firestore.client() # Get specific database db = firestore.client(database_id='my-db') # Get from named app db = firestore.client(app=secondary_app) ``` -------------------------------- ### Initialize Firebase App with Options Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Initialize a Firebase app with a service account credential and custom configuration options, such as database URL and storage bucket. ```python import firebase_admin from firebase_admin import credentials # Initialize with options cred = credentials.Certificate('serviceAccountKey.json') app = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://myproject.firebaseio.com', 'storageBucket': 'myproject.appspot.com' }) ``` -------------------------------- ### Retrieve Data from a Reference Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Use the `get()` method to retrieve data from a specific database location. This method returns the data at the location or `None` if it's empty. It's useful for fetching existing data to process or display. ```python users_ref = db.reference('/users') users_data = users_ref.get() if users_data: for uid, user in users_data.items(): print(f"{uid}: {user}") ``` -------------------------------- ### Get Database References Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Obtain references to specific locations within your Firebase Realtime Database. You can get a root reference, a reference to a specific path, or use a custom database URL. ```python from firebase_admin import db # Root reference root = db.reference() # Specific path users = db.reference('/users') # Nested path user = db.reference('/users/user123') # Custom database URL ref = db.reference(url='https://other-db.firebaseio.com') ``` -------------------------------- ### Pagination Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Illustrates how to implement pagination for retrieving large datasets in chunks using `limit_to_first` and `start_at`. ```APIDOC ## Pagination ### Description Demonstrates how to paginate through large datasets by retrieving data in smaller, manageable pages using query ordering and limiting. ### Get First Page ```python page_size = 10 ref = db.reference('/posts').order_by_key() first_page = ref.limit_to_first(page_size).get() ``` ### Get Next Page ```python # Assuming 'first_page' contains data from the previous call if first_page: # Get the last key from the current page to use as a starting point for the next last_key = list(first_page.keys())[-1] # Fetch the next page, including one extra item to easily identify the boundary next_page_with_boundary = ref.start_at(last_key).limit_to_first(page_size + 1).get() # Exclude the starting item (last_key) from the actual next page results next_page = {k: v for k, v in next_page_with_boundary.items() if k != last_key} print(next_page) ``` ``` -------------------------------- ### Listening to Changes Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Demonstrates how to set up real-time listeners for data changes and how to detach them. ```APIDOC ## Listening to Changes ### Description Shows how to subscribe to real-time updates for data at a specific database reference and how to stop listening when no longer needed. ### Setup Listener ```python # Callback function to process incoming data changes def on_user_update(event): user_data = event.data if user_data: print(f"User data updated: {user_data}") # Get a reference to the users node users_ref = db.reference('/users') # Attach the listener handle = users_ref.listen(on_user_update) ``` ### Stop Listening ```python # To stop listening, call the listen method with None users_ref.listen(None) ``` ``` -------------------------------- ### Get Realtime Database Reference with Custom URL Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/configuration.md Obtain a reference to a specific Realtime Database instance using a custom URL. This allows connecting to databases other than the default one associated with the initialized app. ```python from firebase_admin import db ref = db.reference(url='https://my-other-db.firebaseio.com') ``` -------------------------------- ### initialize_app() Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Initializes and returns a new Firebase App instance. It can be configured with credentials, options, and a unique name. ```APIDOC ## initialize_app() ### Description Initializes and returns a new Firebase App instance. It can be configured with credentials, options, and a unique name. ### Signature ```python def initialize_app(credential=None, options=None, name='[DEFAULT]') -> App ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **credential** (credentials.Base) - Optional - Credential for authentication. Defaults to ApplicationDefault(). - **options** (dict) - Optional - Configuration options. See [configuration.md](../configuration.md) for supported keys. Defaults to {}. - **name** (str) - Optional - Unique app identifier. Defaults to '[DEFAULT]'. ### Returns `App` - Newly initialized Firebase app instance ### Raises - `ValueError` - If app name already exists, or arguments invalid - `google.auth.exceptions.DefaultCredentialsError` - If credential is None and no default credentials available ### Usage Examples ```python import firebase_admin from firebase_admin import credentials # Initialize with service account cred = credentials.Certificate('serviceAccountKey.json') app = firebase_admin.initialize_app(cred) # Initialize with options app = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://myproject.firebaseio.com', 'storageBucket': 'myproject.appspot.com' }) # Initialize named app app2 = firebase_admin.initialize_app(cred, name='secondary') # Use Application Default Credentials app3 = firebase_admin.initialize_app() ``` ``` -------------------------------- ### Get all comments for a post Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Retrieve all comments associated with a specific post from its subcollection. ```python # Get all comments for post comments = db.collection('posts').document('post1')\ .collection('comments').get() ``` -------------------------------- ### Get user profile Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Retrieve a user profile document by its document ID. ```python # Get profile user = db.collection('users').document('user1').get() ``` -------------------------------- ### Get Data from Realtime Database Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/README.md Retrieves data from a specified location in the Firebase Realtime Database. ```python from firebase_admin import db # Get reference ref = db.reference('/users/user123') # Get data user_data = ref.get() ``` -------------------------------- ### Access Default Firestore Database Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/configuration.md Use this snippet to get a client for the default Firestore database. ```python from firebase_admin import firestore db = firestore.client() ``` -------------------------------- ### Handle Storage Not Found Errors Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Demonstrates how to catch `NotFound` exceptions when downloading files from a bucket. This is useful for gracefully handling cases where a file does not exist. ```python from google.cloud.exceptions import NotFound bucket = storage.bucket() try: bucket.blob('file.txt').download_to_filename('local.txt') except NotFound: print("File not found in bucket") except Exception as e: print(f"Download failed: {e}") ``` -------------------------------- ### Get SAML Provider Config Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Retrieves an existing SAML provider configuration using its provider ID. ```python def get_saml_provider_config(provider_id: str, app = None) -> SAMLProviderConfig ``` -------------------------------- ### Usage Pattern: Download and Process Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Demonstrates downloading a file (e.g., JSON) and processing its content. ```APIDOC ### Usage Patterns: Download and Process ```python import json from firebase_admin import storage bucket = storage.bucket() # Download JSON file blob = bucket.blob('config.json') content = blob.download_as_string() config = json.loads(content) print(f"Loaded config: {config}") ``` ``` -------------------------------- ### Initialize Firebase Admin SDK with Service Account Credentials Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/README.md Shows how to initialize the Firebase Admin SDK using a service account key file. This is a common method for server-side applications. ```python from firebase_admin import credentials # Service account cred = credentials.Certificate('path/to/serviceAccountKey.json') ``` -------------------------------- ### firebase_admin.db.reference Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Gets a database reference to a location in the Firebase Realtime Database. This is the entry point for all database operations. ```APIDOC ## firebase_admin.db.reference ### Description Gets a database reference to a location. This function is used to obtain a `Reference` object that represents a specific node in your database. ### Signature ```python def reference(path: str = '/', app = None, url: str = None) -> Reference ``` ### Parameters #### Path Parameters - **path** (str) - Optional - Path in database. Defaults to '/'. - **app** (App) - Optional - App instance to use. - **url** (str) - Optional - Custom database URL. ### Usage ```python from firebase_admin import db # Root reference root = db.reference() # Specific path users = db.reference('/users') # Nested path user = db.reference('/users/user123') # Custom database URL ref = db.reference(url='https://other-db.firebaseio.com') ``` ### Path Validation - Paths must be strings. - Cannot contain: `[].?#$` - Examples: `/users`, `/posts/post1`, `/messages` ``` -------------------------------- ### File Upload and Download Operations Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Demonstrates various methods for uploading and downloading file content to and from Cloud Storage, including from filenames, strings, and file objects. ```python # Upload from file bucket.blob('destination.txt').upload_from_filename('source.txt') # Upload from string bucket.blob('data.json').upload_from_string('{"key": "value"}') # Upload from file object with open('file.txt', 'rb') as f: bucket.blob('destination.txt').upload_from_file(f) # Download to file bucket.blob('source.txt').download_to_filename('destination.txt') # Download to string content = bucket.blob('source.txt').download_as_string() text = content.decode('utf-8') # Download to file object with open('destination.txt', 'wb') as f: bucket.blob('source.txt').download_to_file(f) ``` -------------------------------- ### Initialize App with Environment Configuration Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Initializes a Firebase app using default credentials and automatically loads configuration from environment variables like FIREBASE_CONFIG and GOOGLE_CLOUD_PROJECT. ```python # With FIREBASE_CONFIG env var app = firebase_admin.initialize_app(credentials.ApplicationDefault()) # Project ID from GOOGLE_CLOUD_PROJECT print(app.project_id) ``` -------------------------------- ### Get Document from Firestore Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/README.md Retrieves a document from a Firestore collection. Checks if the document exists and prints its data. ```python from firebase_admin import firestore db = firestore.client() # Get document doc = db.collection('users').document('user1').get() if doc.exists: print(doc.to_dict()) ``` -------------------------------- ### Counter with Transaction Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Example of using transactions to safely increment a counter, ensuring accuracy even with concurrent modifications. ```APIDOC ## Counter with Transaction ### Description Illustrates a common use case for transactions: safely incrementing a numerical value (like a counter) by ensuring the operation is atomic and handles potential conflicts. ### Usage Example ```python # Define the update function for the transaction def increment(current_value): if current_value is None: return 1 # Start at 1 if the value doesn't exist return current_value + 1 # Get a reference to the counter node ref = db.reference('/stats/pageviews') # Perform the transaction to increment the counter success, final_value = ref.transaction(increment) if success: print(f"Successfully updated page views to: {final_value}") else: print("Failed to update page views transactionally.") ``` ``` -------------------------------- ### Get OIDC Provider Config Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Retrieves an existing OpenID Connect provider configuration using its provider ID. ```python def get_oidc_provider_config(provider_id: str, app = None) -> OIDCProviderConfig ``` -------------------------------- ### Run Lint Script Source: https://github.com/firebase/firebase-admin-python/blob/main/CONTRIBUTING.md Use the provided bash script for linting, which handles both the main module and tests. Pass 'all' to lint all source files. ```bash ./lint.sh # Lint locally modified source files ``` ```bash ./lint.sh all # Lint all source files ``` -------------------------------- ### Initialize Firebase App with Service Account Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/README.md Initializes the Firebase Admin SDK using a service account key. Configure database URL, storage bucket, and project ID. ```python import firebase_admin from firebase_admin import credentials, auth, db, firestore # Initialize with service account cred = credentials.Certificate('serviceAccountKey.json') app = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://myproject.firebaseio.com', 'storageBucket': 'myproject.appspot.com', 'projectId': 'myproject' }) # Use services user = auth.get_user('user-id') ref = db.reference('/path') doc = firestore.client().collection('users').document('user-id').get() ``` -------------------------------- ### Get a document asynchronously Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Retrieve a document from Firestore using asynchronous operations. Requires an async-compatible Firestore client. ```python import asyncio from firebase_admin import firestore async def get_user(db, user_id): doc = await db.collection('users').document(user_id).get() return doc.to_dict() db = firestore.client() result = asyncio.run(get_user(db, 'user1')) ``` -------------------------------- ### Get Document Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Retrieves a single document or multiple documents from a collection. The retrieved document data can be accessed as a dictionary. ```APIDOC ## Get Document ### Description Retrieves a single document by its ID or all documents within a collection. The document data can be accessed using `to_dict()`. ### Method `db.collection('collection_name').document('document_id').get()` `db.collection('collection_name').get()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Get single document doc = db.collection('users').document('user1').get() if doc.exists: data = doc.to_dict() print(data) # Get multiple documents docs = db.collection('users').get() for doc in docs: print(doc.id, doc.to_dict()) ``` ### Response #### Success Response `DocumentSnapshot` or iterable of `DocumentSnapshot` #### Response Example None provided in source. ``` -------------------------------- ### RefreshToken Credential from File Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Initializes a RefreshToken credential using a token file. Ensure the file path is correct and the file contains valid JSON. ```python cred = credentials.RefreshToken('token.json') print(cred.client_id) ``` -------------------------------- ### get_app() Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Retrieves a previously initialized app by its name. If no name is provided, it returns the default app. ```APIDOC ## get_app() ### Description Retrieves a previously initialized app by its name. If no name is provided, it returns the default app. ### Signature ```python def get_app(name='[DEFAULT]') -> App ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **name** (str) - Optional - App name to retrieve. Defaults to '[DEFAULT]'. ### Returns `App` - The app instance with the given name. ### Raises - `ValueError` - If name is not a string or the app does not exist. ### Usage Examples ```python # Get default app app = firebase_admin.get_app() # Get named app secondary = firebase_admin.get_app('secondary') # Access properties project_id = app.project_id credential = app.credential ``` ``` -------------------------------- ### Get Google Auth Credential from Certificate Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Retrieves the underlying Google Auth credential object from a Certificate credential. ```python cred = credentials.Certificate('key.json') google_cred = cred.get_credential() ``` -------------------------------- ### Create User Account Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Creates a new user account with specified properties like email and password. Can also create with a custom UID. ```python # Create user with email and password user = auth.create_user( email='user@example.com', password='secretpassword', display_name='John Doe' ) print(f"Created user: {user.uid}") # Create with custom uid user = auth.create_user( uid='custom-user-id', email='user@example.com' ) ``` -------------------------------- ### Get User by Email Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Retrieves user data using their email address. This is an alternative to using the user ID for lookups. ```python auth.get_user_by_email('user@example.com') ``` -------------------------------- ### Connect to a custom database URL Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Use the `url` parameter in `db.reference()` to connect to a different Realtime Database instance than the one specified during app initialization. ```python ref = db.reference('/', url='https://other-db.firebaseio.com') ``` -------------------------------- ### Initialize Firebase Admin SDK with Application Default Credentials Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/README.md Demonstrates initializing the Firebase Admin SDK using Application Default Credentials. This is often used in Google Cloud environments. ```python from firebase_admin import credentials cred = credentials.ApplicationDefault() ``` -------------------------------- ### Get top 10 scores from leaderboard Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Retrieve the top 10 scores from the leaderboard, ordered by score in descending order. ```python # Get top 10 top_users = db.collection('leaderboard')\ .order_by('score', direction=firestore.Query.DESCENDING)\ .limit(10)\ .get() ``` -------------------------------- ### Get Document Data Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Retrieve a single document by its ID or all documents within a collection. Check `doc.exists` before accessing `doc.to_dict()`. ```python # Get single document doc = db.collection('users').document('user1').get() if doc.exists: data = doc.to_dict() print(data) # Get multiple documents docs = db.collection('users').get() for doc in docs: print(doc.id, doc.to_dict()) ``` -------------------------------- ### Initialize Firestore client with emulator Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Initialize the Firestore client after setting the emulator host. The client will automatically connect to the emulator. ```python from firebase_admin import firestore db = firestore.client() # Uses emulator ``` -------------------------------- ### Configure gcloud for Local Development Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Sets up Application Default Credentials locally by logging in with gcloud. This allows the SDK to automatically find credentials. ```bash gcloud auth application-default login ``` -------------------------------- ### Get a Firebase User by ID Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/README.md Retrieves a user's information from Firebase Authentication using their unique user ID. ```python from firebase_admin import auth # Get user user = auth.get_user('user-id') ``` -------------------------------- ### Initialize App with RefreshToken from File Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Demonstrates initializing the Firebase app using a RefreshToken credential loaded from a file. This is a common pattern for applications that use OAuth2 refresh tokens. ```python # From file cred = credentials.RefreshToken('~/.config/gcloud/application_default_credentials.json') app = firebase_admin.initialize_app(cred) ``` -------------------------------- ### Perform a transaction Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Execute a series of operations atomically within a transaction. This example transfers funds between accounts, ensuring data consistency. ```python def transfer_funds(transaction, from_uid, to_uid, amount): from_doc = db.collection('accounts').document(from_uid).get(transaction=transaction) to_doc = db.collection('accounts').document(to_uid).get(transaction=transaction) from_balance = from_doc.get('balance') to_balance = to_doc.get('balance') if from_balance < amount: raise ValueError("Insufficient funds") transaction.update(from_doc.reference, {'balance': from_balance - amount}) transaction.update(to_doc.reference, {'balance': to_balance + amount}) db.transaction()(lambda transaction: transfer_funds(transaction, 'user1', 'user2', 100)) ``` -------------------------------- ### Point to local Firestore emulator Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Configure the client to use the local Firestore emulator by setting the FIRESTORE_EMULATOR_HOST environment variable. ```bash export FIRESTORE_EMULATOR_HOST=127.0.0.1:8080 ``` -------------------------------- ### Get User by Phone Number Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Retrieves user data using their phone number. Ensure the phone number is in E.164 format. ```python auth.get_user_by_phone_number('+15555550100') ``` -------------------------------- ### Emulator Usage Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Shows how to configure and use the local Firebase Storage emulator for development and testing. ```APIDOC ## Emulator Point to local storage emulator: ```bash export FIREBASE_STORAGE_EMULATOR_HOST=127.0.0.1:4000 ``` ```python from firebase_admin import storage # Uses emulator when the environment variable is set bucket = storage.bucket() ``` ``` -------------------------------- ### List OIDC Provider Configs Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Lists all available OpenID Connect provider configurations. Supports pagination with an optional page token. ```python def list_oidc_provider_configs(page_token: str = None, app = None) -> ListProviderConfigsPage ``` -------------------------------- ### Create user profile Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Create a new user profile document with display name, email, and timestamps. Uses SERVER_TIMESTAMP for creation and update times. ```python from firebase_admin import firestore db = firestore.client() # Create user profile db.collection('users').document('user1').set({ 'displayName': 'John Doe', 'email': 'john@example.com', 'created': firestore.SERVER_TIMESTAMP, 'updated': firestore.SERVER_TIMESTAMP }) ``` -------------------------------- ### Example Pull Request Title Source: https://github.com/firebase/firebase-admin-python/blob/main/AGENTS.md Use Conventional Commits for pull request titles, focusing on the larger goal achieved by the included commits. ```bash feat(fcm): Added support for multicast messages ``` -------------------------------- ### Error Handling for Application Default Credentials Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Shows how to handle errors when initializing Application Default Credentials, specifically catching DefaultCredentialsError if credentials cannot be found. ```python from firebase_admin import credentials import google.auth.exceptions try: cred = credentials.ApplicationDefault() except google.auth.exceptions.DefaultCredentialsError: print("Could not find Application Default Credentials") ``` -------------------------------- ### List SAML Provider Configs Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Lists all available SAML provider configurations. Supports pagination with an optional page token. ```python def list_saml_provider_configs(page_token: str = None, app = None) -> ListProviderConfigsPage ``` -------------------------------- ### Cloud Function Receiving Task Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/functions.md Example of a Cloud Function designed to receive and process task data sent via HTTP POST requests. ```python # In Cloud Function def myFunction(request): data = request.get_data() # Process task data return 'Success', 200 ``` -------------------------------- ### Access Certificate Credential Properties Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Demonstrates accessing project ID and service account email from an initialized Certificate credential. ```python cred = credentials.Certificate('key.json') project_id = cred.project_id email = cred.service_account_email ``` -------------------------------- ### Initialize App with FIREBASE_CONFIG Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Initializes the Firebase app, automatically loading options from the FIREBASE_CONFIG environment variable if set. ```python app = firebase_admin.initialize_app(cred) # Loads options from FIREBASE_CONFIG ``` -------------------------------- ### Get the key of a database reference Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md The `key` property returns the last segment of the reference path. This is useful for identifying specific nodes within the database. ```python ref = db.reference('/users/user123/posts/post1') print(ref.key) # 'post1' ``` -------------------------------- ### Get Named Firebase App Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Retrieve a specific Firebase app instance by its unique name. Use this when you have initialized multiple apps with different names. ```python # Get named app secondary = firebase_admin.get_app('secondary') ``` -------------------------------- ### Handle App Initialization Errors Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Demonstrates how to catch and handle `ValueError` exceptions that may occur during Firebase app initialization. This helps in diagnosing issues with credentials or configuration. ```python try: app = firebase_admin.initialize_app(cred) except ValueError as e: # Handle invalid credential, options, or name print(f"Initialization failed: {e}") ``` -------------------------------- ### Initialize App with Service Account Key Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Initializes the Firebase app using a service account key file. This is a common method for development environments. ```python from firebase_admin import credentials, initialize_app # Download key from Firebase Console cred = credentials.Certificate('serviceAccountKey.json') app = initialize_app(cred) ``` -------------------------------- ### Get Access Token from Certificate Credential Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Fetches a Google OAuth2 access token from a Certificate credential. Ensure the credential is initialized before calling this method. ```python cred = credentials.Certificate('key.json') token_info = cred.get_access_token() print(f"Token: {token_info.access_token}") print(f"Expires: {token_info.expiry}") ``` -------------------------------- ### Listen to query results Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Set up a real-time listener for changes to documents matching a query. The callback iterates through the documents and prints their data. ```python def on_query_snapshot(docs, changes, read_time): for doc in docs: print(f"{doc.id}: {doc.to_dict()}") db.collection('users').where('active', '==', True).on_snapshot(on_query_snapshot) ``` -------------------------------- ### Configure Realtime Database Emulator Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/configuration.md Point the Firebase Realtime Database client to a local emulator by setting the environment variable. This allows for local testing. ```bash export FIREBASE_DATABASE_EMULATOR_HOST=localhost:9000 ``` -------------------------------- ### Handle Instance ID Deletion Errors Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/instance_id.md This example demonstrates how to catch specific Firebase errors that may occur during Instance ID deletion, such as 'NotFoundError' or 'PermissionDeniedError'. ```python from firebase_admin import instance_id, exceptions try: instance_id.delete_instance_id('instance-id-123') except exceptions.NotFoundError: print("Instance ID not found") except exceptions.PermissionDeniedError: print("Project mismatch or insufficient permissions") except exceptions.InvalidArgumentError: print("Malformed instance ID") except exceptions.ResourceExhaustedError: print("Request throttled - try again later") except exceptions.FirebaseError as e: print(f"Error: {e.code} - {e.message}") ``` -------------------------------- ### Use Local Storage Emulator Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Instantiate the Firebase Storage bucket client to connect to the local emulator. This requires the `FIREBASE_STORAGE_EMULATOR_HOST` environment variable to be set. ```python from firebase_admin import storage bucket = storage.bucket() # Uses emulator ``` -------------------------------- ### Get Multiple Users by Identifiers Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Retrieves multiple user records by providing a list of identifiers (UIDs or emails). Supports up to 100 identifiers per request. ```python from firebase_admin.auth import UidIdentifier, EmailIdentifier result = auth.get_users([ UidIdentifier('user1'), UidIdentifier('user2'), EmailIdentifier('user3@example.com') ]) for user in result.users: print(user.email) for identifier in result.not_found: print(f"Not found: {identifier}") ``` -------------------------------- ### Emulator Configuration Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md Configure the SDK to connect to a local Firebase Realtime Database emulator for development and testing. ```APIDOC ## Emulator Configuration ### Description Points the Firebase Admin SDK to a local Firebase Realtime Database emulator instance. This is typically done by setting an environment variable. ### Environment Variable `export FIREBASE_DATABASE_EMULATOR_HOST=localhost:9000` ### Usage Example ```python from firebase_admin import db # When the emulator host is set, db.reference() will automatically connect to it ref = db.reference() ``` ``` -------------------------------- ### Get User by ID Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Retrieves user data using their unique user ID. Useful for accessing user properties like email or custom claims. ```python user = auth.get_user('user123') print(user.email) print(user.email_verified) print(user.custom_claims) ``` -------------------------------- ### Client Access Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Obtain a Firestore client instance to interact with your database. You can get the default client or specify a particular database ID or Firebase App instance. ```APIDOC ## client() ### Description Returns a Firestore client. This client can be used to perform operations on your Firestore database. ### Method `client(app = None, database_id: str = None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from firebase_admin import firestore # Get default Firestore database db = firestore.client() # Get specific database db = firestore.client(database_id='my-db') # Get from named app db = firestore.client(app=secondary_app) ``` ### Response #### Success Response `google.cloud.firestore.Client` - Firestore client #### Response Example None provided in source. ``` -------------------------------- ### Create TaskQueue reference (fully qualified) Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/functions.md Create a TaskQueue reference using the fully qualified resource name, including project, location, and function name. ```python queue = functions.task_queue( 'projects/myproject/locations/us-central1/functions/myFunction' ) ``` -------------------------------- ### Upload File and Get Public URL Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/storage.md Uploads a local file to Firebase Storage and constructs its public URL. This assumes the bucket is configured for public access. ```python from firebase_admin import storage bucket = storage.bucket() # Upload file bucket.blob('profile-photos/user1.jpg').upload_from_filename('photo.jpg') # Get public URL (if bucket is public) url = f"https://storage.googleapis.com/{bucket.name}/profile-photos/user1.jpg" ``` -------------------------------- ### create_user() Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/auth.md Creates a new user account with specified properties. Supports setting UID, email, display name, phone number, and more. ```APIDOC ## create_user() ### Description Creates a new user account with specified properties. Supports setting UID, email, display name, phone number, and more. ### Signature ```python def create_user(uid: str = None, email: str = None, email_verified: bool = False, display_name: str = None, phone_number: str = None, photo_url: str = None, password: str = None, disabled: bool = False, app = None) -> UserRecord ``` ### Parameters #### Path Parameters - **uid** (str) - Optional - User ID (1-128 chars) - **email** (str) - Optional - Email address - **email_verified** (bool) - Optional - Email verification status - **display_name** (str) - Optional - Display name - **phone_number** (str) - Optional - Phone (E.164 format) - **photo_url** (str) - Optional - Photo URL - **password** (str) - Optional - Raw password (hashed server-side) - **disabled** (bool) - Optional - Account disabled flag - **app** (App) - Optional - App instance to use ### Returns `UserRecord` - Created user ### Raises - `ValueError` - If properties invalid - `UidAlreadyExistsError` - If uid taken - `EmailAlreadyExistsError` - If email taken - `PhoneNumberAlreadyExistsError` - If phone taken - `FirebaseError` - If creation fails ### Usage ```python user = auth.create_user( email='user@example.com', password='secretpassword', display_name='John Doe' ) print(f"Created user: {user.uid}") # Create with custom uid user = auth.create_user( uid='custom-user-id', email='user@example.com' ) ``` ``` -------------------------------- ### Get Default Firebase App Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/app.md Retrieve the default Firebase app instance that was initialized without a specific name. This is the most common way to access the app after initialization. ```python # Get default app app = firebase_admin.get_app() ``` -------------------------------- ### Get Access Token Info Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/credentials.md Retrieves access token information, including the token string and its expiration time. This is useful for making manual API calls. ```python cred = credentials.Certificate('key.json') token_info = cred.get_access_token() if token_info.expiry > datetime.utcnow(): print(f"Token valid until {token_info.expiry}") # Use token_info.access_token for manual API calls ``` -------------------------------- ### Initialize App with Project ID Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/functions.md Initialize the Firebase Admin SDK with a specific project ID to use the Functions module. ```python app = firebase_admin.initialize_app(cred, {'projectId': 'my-project'}) from firebase_admin import functions queue = functions.task_queue('myFunction') queue.enqueue(b'data') ``` -------------------------------- ### Pagination Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/firestore.md Implement pagination for queries to retrieve results in manageable chunks, using `start_after` with the last document of the previous page. ```APIDOC ## Pagination ### Description Enables fetching query results in pages by using `limit` and `start_after` to paginate through documents. ### Method `db.collection('collection_name').start_after(last_document).limit(page_size).get()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Get first page page_size = 10 first_page = db.collection('posts').limit(page_size).get() # Get next page using last document if first_page: last_doc = first_page[-1] next_page = db.collection('posts') .start_after(last_doc) .limit(page_size) .get() ``` ### Response #### Success Response Iterable of `DocumentSnapshot` #### Response Example None provided in source. ``` -------------------------------- ### Get the full path of a database reference Source: https://github.com/firebase/firebase-admin-python/blob/main/_autodocs/api-reference/database.md The `path` property returns the full path of the database reference. This is useful for understanding the location of data within the database structure. ```python ref = db.reference('/users/user123') print(ref.path) # '/users/user123' ```