How to Use Firebase Admin with Python: Setup and Example
To use
firebase-admin with Python, first install the firebase-admin package and initialize the SDK with your Firebase service account credentials. Then, use the SDK to access Firebase services like authentication, database, or messaging securely from your Python code.Syntax
First, install the Firebase Admin SDK for Python using pip. Then, import the firebase_admin module and initialize the app with your service account key. This setup allows your Python code to securely interact with Firebase services.
- firebase_admin.initialize_app(): Initializes the SDK with credentials.
- credentials.Certificate(): Loads your service account JSON file.
python
import firebase_admin from firebase_admin import credentials cred = credentials.Certificate('path/to/serviceAccountKey.json') firebase_admin.initialize_app(cred)
Example
This example shows how to initialize Firebase Admin SDK and list all users in Firebase Authentication. It demonstrates secure setup and basic usage of the SDK.
python
import firebase_admin from firebase_admin import credentials, auth # Initialize the app with service account credentials cred = credentials.Certificate('path/to/serviceAccountKey.json') firebase_admin.initialize_app(cred) # List first 10 users page = auth.list_users(10) for user in page.users: print('User UID:', user.uid, 'Email:', user.email)
Output
User UID: abc123 Email: user1@example.com
User UID: def456 Email: user2@example.com
... (up to 10 users)
Common Pitfalls
Common mistakes include:
- Not using the correct path to the service account JSON file, causing initialization errors.
- Forgetting to initialize the app before calling Firebase services.
- Using client SDK credentials instead of admin service account credentials.
- Not handling exceptions when calling Firebase APIs.
python
import firebase_admin from firebase_admin import credentials, auth # Wrong: Missing initialization # auth.list_users() # This will fail because app is not initialized # Correct: cred = credentials.Certificate('path/to/serviceAccountKey.json') firebase_admin.initialize_app(cred) # Now you can call auth.list_users() safely
Quick Reference
Keep these tips in mind:
- Always use a service account JSON file for admin SDK authentication.
- Initialize the app once per script or application.
- Use
firebase_admin.authfor authentication tasks. - Use
firebase_admin.dbfor realtime database operations. - Handle exceptions to catch API errors gracefully.
Key Takeaways
Install and initialize Firebase Admin SDK with your service account JSON file before using Firebase services.
Use the admin SDK to securely manage Firebase Authentication, database, and messaging from Python.
Always verify the path to your service account file and handle exceptions in your code.
Initialize the Firebase app only once per script to avoid errors.
Use the appropriate Firebase Admin modules like auth or db depending on your needs.