0
# Firebase Admin Python SDK
1
2
The Firebase Admin Python SDK enables server-side (backend) Python developers to integrate Firebase services into their applications and services from privileged environments like servers or cloud platforms. It provides comprehensive access to Firebase Authentication, Cloud Firestore, Realtime Database, Cloud Messaging, Cloud Storage, Remote Config, Cloud Functions, App Check, Machine Learning, and Project Management APIs.
3
4
## Package Information
5
6
- **Package Name**: firebase-admin
7
- **Language**: Python 3.9+
8
- **Installation**: `pip install firebase-admin`
9
10
## Core Imports
11
12
```python
13
import firebase_admin
14
from firebase_admin import credentials
15
```
16
17
Common service imports:
18
19
```python
20
from firebase_admin import auth
21
from firebase_admin import firestore
22
from firebase_admin import db
23
from firebase_admin import messaging
24
from firebase_admin import storage
25
from firebase_admin import tenant_mgt
26
```
27
28
## Basic Usage
29
30
```python
31
import firebase_admin
32
from firebase_admin import credentials
33
from firebase_admin import auth
34
35
# Initialize the SDK with a service account
36
cred = credentials.Certificate("path/to/serviceAccountKey.json")
37
firebase_admin.initialize_app(cred, {
38
'databaseURL': 'https://your-project-default-rtdb.firebaseio.com/',
39
'storageBucket': 'your-project.appspot.com'
40
})
41
42
# Use Firebase Authentication
43
user = auth.get_user('user-uid')
44
print(f'Successfully fetched user data: {user.display_name}')
45
46
# Create custom token
47
custom_token = auth.create_custom_token('user-uid')
48
print(f'Custom token: {custom_token.decode()}')
49
```
50
51
## Architecture
52
53
Firebase Admin SDK follows a service-oriented architecture:
54
55
- **App Management**: Central application instances managing credentials and configuration
56
- **Service Modules**: Individual modules for each Firebase service (auth, firestore, db, etc.)
57
- **Credential System**: Multiple authentication methods including service accounts and application default credentials
58
- **Error Handling**: Comprehensive exception hierarchy for different error conditions
59
60
Each service module provides both high-level convenience functions and access to underlying client objects for advanced operations.
61
62
## Capabilities
63
64
### App Management
65
66
Core application lifecycle management including initialization, configuration, and cleanup. Manages credentials and provides the foundation for all Firebase service access.
67
68
```python { .api }
69
def initialize_app(credential=None, options=None, name='[DEFAULT]'):
70
"""
71
Initializes and returns a new App instance.
72
73
Args:
74
credential: A credential object (optional)
75
options: Configuration options dict (optional)
76
name: Name of the app (optional)
77
78
Returns:
79
App: A newly initialized App instance
80
"""
81
82
def get_app(name='[DEFAULT]'):
83
"""
84
Retrieves an App instance by name.
85
86
Args:
87
name: Name of the App instance to retrieve
88
89
Returns:
90
App: An App instance with the given name
91
"""
92
93
def delete_app(app):
94
"""
95
Gracefully deletes an App instance.
96
97
Args:
98
app: The app instance to be deleted
99
"""
100
```
101
102
[App Management](./app-management.md)
103
104
### Authentication and User Management
105
106
Comprehensive user authentication and management capabilities including custom token generation, ID token verification, user CRUD operations, and multi-tenant authentication.
107
108
```python { .api }
109
def create_custom_token(uid, developer_claims=None, app=None):
110
"""Create a custom token for the given UID."""
111
112
def verify_id_token(id_token, app=None, check_revoked=False, clock_skew_seconds=0):
113
"""Verify a Firebase ID token."""
114
115
def get_user(uid, app=None):
116
"""Get a user by UID."""
117
118
def create_user(**kwargs):
119
"""Create a new user."""
120
121
def update_user(uid, **kwargs):
122
"""Update an existing user."""
123
124
def delete_user(uid, app=None):
125
"""Delete a user."""
126
```
127
128
[Authentication](./authentication.md)
129
130
### Cloud Firestore
131
132
Complete Cloud Firestore database integration providing access to the full Google Cloud Firestore client with document and collection operations, queries, transactions, and batch operations.
133
134
```python { .api }
135
def client(app=None, database_id=None):
136
"""
137
Return a client for interacting with the Cloud Firestore database.
138
139
Args:
140
app: Firebase app instance (optional)
141
database_id: Database ID (optional)
142
143
Returns:
144
google.cloud.firestore.Client: Firestore client instance
145
"""
146
```
147
148
[Cloud Firestore](./firestore.md)
149
150
### Realtime Database
151
152
Firebase Realtime Database operations including data reading, writing, querying, transactions, and real-time listeners for JSON tree-structured data.
153
154
```python { .api }
155
def reference(path='/', app=None, url=None):
156
"""
157
Return a database reference for the specified path.
158
159
Args:
160
path: Database path (default: '/')
161
app: Firebase app instance (optional)
162
url: Database URL (optional)
163
164
Returns:
165
Reference: Database reference instance
166
"""
167
```
168
169
[Realtime Database](./realtime-database.md)
170
171
### Cloud Messaging
172
173
Firebase Cloud Messaging (FCM) for sending push notifications and managing topic subscriptions across Android, iOS, and web platforms.
174
175
```python { .api }
176
def send(message, dry_run=False, app=None):
177
"""Send a message to Firebase Cloud Messaging."""
178
179
def send_each(messages, dry_run=False, app=None):
180
"""Send multiple messages to Firebase Cloud Messaging."""
181
182
def subscribe_to_topic(tokens, topic, app=None):
183
"""Subscribe registration tokens to a topic."""
184
185
def unsubscribe_from_topic(tokens, topic, app=None):
186
"""Unsubscribe registration tokens from a topic."""
187
```
188
189
[Cloud Messaging](./messaging.md)
190
191
### Cloud Storage
192
193
Firebase Cloud Storage integration providing access to Google Cloud Storage buckets for file upload, download, and management operations.
194
195
```python { .api }
196
def bucket(name=None, app=None):
197
"""
198
Return a handle to a Cloud Storage bucket.
199
200
Args:
201
name: Bucket name (optional, uses default from config)
202
app: Firebase app instance (optional)
203
204
Returns:
205
google.cloud.storage.Bucket: Storage bucket instance
206
"""
207
```
208
209
[Cloud Storage](./storage.md)
210
211
### Cloud Functions
212
213
Firebase Cloud Functions integration for enqueueing tasks in Cloud Task queues associated with callable functions.
214
215
```python { .api }
216
def task_queue(function_name, extension_id=None, app=None):
217
"""
218
Get a TaskQueue instance for the specified function.
219
220
Args:
221
function_name: Name of the Cloud Function
222
extension_id: Extension ID (optional)
223
app: Firebase app instance (optional)
224
225
Returns:
226
TaskQueue: Task queue instance
227
"""
228
```
229
230
[Cloud Functions](./functions.md)
231
232
### Machine Learning
233
234
Firebase ML model management for deploying and managing custom machine learning models in Firebase projects.
235
236
```python { .api }
237
def create_model(model, app=None):
238
"""Create a new ML model in Firebase."""
239
240
def get_model(model_id, app=None):
241
"""Get an ML model by ID."""
242
243
def list_models(list_filter=None, page_size=None, page_token=None, app=None):
244
"""List ML models in the project."""
245
```
246
247
[Machine Learning](./machine-learning.md)
248
249
### Remote Config
250
251
Firebase Remote Config server-side template management for dynamic app configuration without requiring app updates.
252
253
```python { .api }
254
class ServerTemplate:
255
"""Server-side Remote Config template management."""
256
257
def evaluate(self, context=None):
258
"""Evaluate the template with optional context."""
259
260
def load(self):
261
"""Load the current Remote Config template."""
262
```
263
264
[Remote Config](./remote-config.md)
265
266
### Project Management
267
268
Firebase project management for creating and managing Android and iOS app configurations within Firebase projects.
269
270
```python { .api }
271
def create_android_app(package_name, display_name=None, app=None):
272
"""Create a new Android app in the Firebase project."""
273
274
def create_ios_app(bundle_id, display_name=None, app=None):
275
"""Create a new iOS app in the Firebase project."""
276
277
def list_android_apps(app=None):
278
"""List all Android apps in the project."""
279
280
def list_ios_apps(app=None):
281
"""List all iOS apps in the project."""
282
```
283
284
[Project Management](./project-management.md)
285
286
### Tenant Management
287
288
Multi-tenant authentication management using Google Cloud Identity Platform (GCIP), enabling isolated authentication environments within a single project.
289
290
```python { .api }
291
def auth_for_tenant(tenant_id, app=None):
292
"""Get an Auth client scoped to a specific tenant."""
293
294
def get_tenant(tenant_id, app=None):
295
"""Get a tenant by ID."""
296
297
def create_tenant(display_name, allow_password_sign_up=None, enable_email_link_sign_in=None, app=None):
298
"""Create a new tenant."""
299
300
def update_tenant(tenant_id, display_name=None, allow_password_sign_up=None, enable_email_link_sign_in=None, app=None):
301
"""Update an existing tenant."""
302
303
def delete_tenant(tenant_id, app=None):
304
"""Delete a tenant."""
305
306
def list_tenants(page_token=None, max_results=100, app=None):
307
"""List tenants with pagination."""
308
```
309
310
[Tenant Management](./tenant-management.md)
311
312
## Types
313
314
```python { .api }
315
class App:
316
"""Firebase application instance."""
317
318
@property
319
def name(self):
320
"""The name of this App instance."""
321
322
@property
323
def credential(self):
324
"""The credential used to initialize this App."""
325
326
@property
327
def options(self):
328
"""The configuration options for this App."""
329
330
@property
331
def project_id(self):
332
"""The Google Cloud project ID associated with this App."""
333
334
class FirebaseError(Exception):
335
"""Base exception for all Firebase-related errors."""
336
337
def __init__(self, code, message, cause=None, http_response=None):
338
"""
339
Initialize FirebaseError.
340
341
Args:
342
code: Error code string
343
message: Error message
344
cause: Underlying cause exception (optional)
345
http_response: HTTP response object (optional)
346
"""
347
348
@property
349
def code(self):
350
"""The error code."""
351
352
@property
353
def cause(self):
354
"""The underlying cause of this error."""
355
356
@property
357
def http_response(self):
358
"""The HTTP response that caused this error."""
359
```