Setting Up Multiple Accounts on Firebase Admin SDK in Python
When working with Firebase, there might be scenarios where you need to manage multiple Firebase projects within a single application. This is especially useful if you're handling different environments (development, staging, production) or multiple clients. The Firebase Admin SDK allows you to achieve this by creating multiple app instances.
Step 1: Install the Firebase Admin SDK
First, ensure that the Firebase Admin SDK is installed in your Python environment. You can install it using pip:
pip install firebase-admin
Step 2: Obtain Service Account Credentials
- Go to the Firebase Console.
- Select your project.
- Click on the Settings gear icon and select Project settings.
- Navigate to the Service accounts tab.
- Click on Generate new private key to download the JSON file containing your service account credentials.
Repeat this process for each project you intend to use.
Step 3: Initialize Multiple Firebase App Instances
You can initialize multiple Firebase app instances in your Python script using different service account credentials. Here's a basic example:
import firebase_admin
from firebase_admin import credentials
# Initialize the first Firebase app
cred1 = credentials.Certificate('/path/to/serviceAccountKey1.json')
app1 = firebase_admin.initialize_app(cred1, name='app1')
# Initialize the second Firebase app
cred2 = credentials.Certificate('/path/to/serviceAccountKey2.json')
app2 = firebase_admin.initialize_app(cred2, name='app2')
Step 4: Use the App Instances
Once you've initialized multiple app instances, you can interact with each Firebase project separately. For example, you can access Firestore from both app instances like this:
from firebase_admin import auth
# Access Firestore for app1
decoded_token = auth.verify_id_token(token, app=app1)
# Access Firestore for app2
decoded_token = auth.verify_id_token(token, app=app2)
Conclusion
By following these steps, you can effectively set up and manage multiple accounts on the Firebase Admin SDK using Python. This approach is particularly useful when working with different environments or handling multiple projects within a single application.
Always remember to handle errors and manage your service account credentials securely.