0
# Cloud Messaging
1
2
Firebase Cloud Messaging (FCM) capabilities for sending push notifications to Android, iOS, and web applications. Supports individual messaging, batch messaging, multicast messaging, and topic-based messaging.
3
4
## Capabilities
5
6
### Message Sending
7
8
Send individual and batch messages to Firebase Cloud Messaging with comprehensive platform-specific customization options.
9
10
```python { .api }
11
def send(message, dry_run=False, app=None):
12
"""
13
Send a message to Firebase Cloud Messaging.
14
15
Args:
16
message: A Message instance
17
dry_run: Whether to send in dry-run mode (optional)
18
app: Firebase app instance (optional)
19
20
Returns:
21
str: Message ID of the sent message
22
23
Raises:
24
QuotaExceededError: If the FCM quota is exceeded
25
SenderIdMismatchError: If the sender ID is mismatched
26
ThirdPartyAuthError: If there's a third-party authentication error
27
UnregisteredError: If the registration token is invalid
28
"""
29
30
def send_each(messages, dry_run=False, app=None):
31
"""
32
Send multiple messages to Firebase Cloud Messaging.
33
34
Args:
35
messages: List of Message instances
36
dry_run: Whether to send in dry-run mode (optional)
37
app: Firebase app instance (optional)
38
39
Returns:
40
BatchResponse: Response containing individual message results
41
"""
42
43
def send_each_async(messages, dry_run=False, app=None):
44
"""
45
Send multiple messages asynchronously to Firebase Cloud Messaging.
46
47
Args:
48
messages: List of Message instances
49
dry_run: Whether to send in dry-run mode (optional)
50
app: Firebase app instance (optional)
51
52
Returns:
53
BatchResponse: Response containing individual message results
54
"""
55
```
56
57
### Multicast Messaging
58
59
Send messages to multiple registration tokens efficiently using multicast operations.
60
61
```python { .api }
62
def send_each_for_multicast(multicast_message, dry_run=False, app=None):
63
"""
64
Send a multicast message to multiple registration tokens.
65
66
Args:
67
multicast_message: A MulticastMessage instance
68
dry_run: Whether to send in dry-run mode (optional)
69
app: Firebase app instance (optional)
70
71
Returns:
72
BatchResponse: Response containing results for each token
73
"""
74
75
def send_each_for_multicast_async(multicast_message, dry_run=False, app=None):
76
"""
77
Send a multicast message asynchronously to multiple registration tokens.
78
79
Args:
80
multicast_message: A MulticastMessage instance
81
dry_run: Whether to send in dry-run mode (optional)
82
app: Firebase app instance (optional)
83
84
Returns:
85
BatchResponse: Response containing results for each token
86
"""
87
```
88
89
### Topic Management
90
91
Manage device subscriptions to messaging topics for broadcasting messages to groups of devices.
92
93
```python { .api }
94
def subscribe_to_topic(tokens, topic, app=None):
95
"""
96
Subscribe registration tokens to a topic.
97
98
Args:
99
tokens: List of registration token strings or single token string
100
topic: Topic name string
101
app: Firebase app instance (optional)
102
103
Returns:
104
TopicManagementResponse: Response with success/failure counts
105
"""
106
107
def unsubscribe_from_topic(tokens, topic, app=None):
108
"""
109
Unsubscribe registration tokens from a topic.
110
111
Args:
112
tokens: List of registration token strings or single token string
113
topic: Topic name string
114
app: Firebase app instance (optional)
115
116
Returns:
117
TopicManagementResponse: Response with success/failure counts
118
"""
119
```
120
121
## Message Construction
122
123
### Basic Message
124
125
```python { .api }
126
class Message:
127
"""A message that can be sent to Firebase Cloud Messaging."""
128
129
def __init__(self, data=None, notification=None, android=None, apns=None, webpush=None, token=None, topic=None, condition=None, fcm_options=None):
130
"""
131
Initialize a message.
132
133
Args:
134
data: Dict of data payload (optional)
135
notification: Notification instance (optional)
136
android: AndroidConfig instance (optional)
137
apns: APNSConfig instance (optional)
138
webpush: WebpushConfig instance (optional)
139
token: Registration token string (optional)
140
topic: Topic name string (optional)
141
condition: Condition string (optional)
142
fcm_options: FCMOptions instance (optional)
143
"""
144
```
145
146
### Multicast Message
147
148
```python { .api }
149
class MulticastMessage:
150
"""A message that can be sent to multiple registration tokens."""
151
152
def __init__(self, tokens, data=None, notification=None, android=None, apns=None, webpush=None, fcm_options=None):
153
"""
154
Initialize a multicast message.
155
156
Args:
157
tokens: List of registration token strings
158
data: Dict of data payload (optional)
159
notification: Notification instance (optional)
160
android: AndroidConfig instance (optional)
161
apns: APNSConfig instance (optional)
162
webpush: WebpushConfig instance (optional)
163
fcm_options: FCMOptions instance (optional)
164
"""
165
```
166
167
### Cross-Platform Notification
168
169
```python { .api }
170
class Notification:
171
"""Cross-platform notification payload."""
172
173
def __init__(self, title=None, body=None, image=None):
174
"""
175
Initialize notification.
176
177
Args:
178
title: Notification title string (optional)
179
body: Notification body string (optional)
180
image: Image URL string (optional)
181
"""
182
```
183
184
## Platform-Specific Configuration
185
186
### Android Configuration
187
188
```python { .api }
189
class AndroidConfig:
190
"""Android-specific message configuration."""
191
192
def __init__(self, collapse_key=None, priority=None, ttl=None, restricted_package_name=None, data=None, notification=None, fcm_options=None, direct_boot_ok=None):
193
"""
194
Initialize Android configuration.
195
196
Args:
197
collapse_key: Collapse key string (optional)
198
priority: Priority ('normal' or 'high') (optional)
199
ttl: Time to live as datetime.timedelta (optional)
200
restricted_package_name: Package name string (optional)
201
data: Dict of data payload (optional)
202
notification: AndroidNotification instance (optional)
203
fcm_options: AndroidFCMOptions instance (optional)
204
direct_boot_ok: Whether message can be received in direct boot (optional)
205
"""
206
207
class AndroidNotification:
208
"""Android-specific notification configuration."""
209
210
def __init__(self, title=None, body=None, icon=None, color=None, sound=None, tag=None, click_action=None, body_loc_key=None, body_loc_args=None, title_loc_key=None, title_loc_args=None, channel_id=None, ticker=None, sticky=None, event_time=None, local_only=None, notification_priority=None, default_sound=None, default_vibrate_timings=None, default_light_settings=None, vibrate_timings=None, visibility=None, notification_count=None, light_settings=None, image=None):
211
"""Initialize Android notification configuration."""
212
213
class AndroidFCMOptions:
214
"""Android-specific FCM options."""
215
216
def __init__(self, analytics_label=None):
217
"""
218
Initialize Android FCM options.
219
220
Args:
221
analytics_label: Analytics label string (optional)
222
"""
223
```
224
225
### APNS Configuration
226
227
```python { .api }
228
class APNSConfig:
229
"""Apple Push Notification service configuration."""
230
231
def __init__(self, headers=None, payload=None, fcm_options=None):
232
"""
233
Initialize APNS configuration.
234
235
Args:
236
headers: Dict of APNS headers (optional)
237
payload: APNSPayload instance (optional)
238
fcm_options: APNSFCMOptions instance (optional)
239
"""
240
241
class APNSPayload:
242
"""APNS payload configuration."""
243
244
def __init__(self, aps=None, **kwargs):
245
"""
246
Initialize APNS payload.
247
248
Args:
249
aps: Aps instance (optional)
250
**kwargs: Additional custom payload fields
251
"""
252
253
class Aps:
254
"""APNS aps dictionary configuration."""
255
256
def __init__(self, alert=None, badge=None, sound=None, content_available=None, category=None, thread_id=None, mutable_content=None, custom_data=None):
257
"""Initialize APNS aps configuration."""
258
259
class ApsAlert:
260
"""APNS alert configuration."""
261
262
def __init__(self, title=None, subtitle=None, body=None, loc_key=None, loc_args=None, title_loc_key=None, title_loc_args=None, subtitle_loc_key=None, subtitle_loc_args=None, action_loc_key=None, launch_image=None):
263
"""Initialize APNS alert configuration."""
264
265
class APNSFCMOptions:
266
"""APNS-specific FCM options."""
267
268
def __init__(self, analytics_label=None, image=None):
269
"""
270
Initialize APNS FCM options.
271
272
Args:
273
analytics_label: Analytics label string (optional)
274
image: Image URL string (optional)
275
"""
276
```
277
278
### Web Push Configuration
279
280
```python { .api }
281
class WebpushConfig:
282
"""Web push protocol configuration."""
283
284
def __init__(self, headers=None, data=None, notification=None, fcm_options=None):
285
"""
286
Initialize webpush configuration.
287
288
Args:
289
headers: Dict of webpush headers (optional)
290
data: Dict of data payload (optional)
291
notification: WebpushNotification instance (optional)
292
fcm_options: WebpushFCMOptions instance (optional)
293
"""
294
295
class WebpushNotification:
296
"""Web push notification configuration."""
297
298
def __init__(self, title=None, actions=None, badge=None, body=None, data=None, dir=None, icon=None, image=None, lang=None, renotify=None, require_interaction=None, silent=None, tag=None, timestamp=None, vibrate=None, custom_data=None):
299
"""Initialize webpush notification configuration."""
300
301
class WebpushNotificationAction:
302
"""Web push notification action."""
303
304
def __init__(self, action, title, icon=None):
305
"""
306
Initialize notification action.
307
308
Args:
309
action: Action identifier string
310
title: Action title string
311
icon: Action icon URL string (optional)
312
"""
313
314
class WebpushFCMOptions:
315
"""Webpush-specific FCM options."""
316
317
def __init__(self, link=None, analytics_label=None):
318
"""
319
Initialize webpush FCM options.
320
321
Args:
322
link: Link URL string (optional)
323
analytics_label: Analytics label string (optional)
324
"""
325
```
326
327
## Response Types
328
329
```python { .api }
330
class BatchResponse:
331
"""Response from batch messaging operations."""
332
333
@property
334
def responses(self):
335
"""List of SendResponse instances for each message."""
336
337
@property
338
def success_count(self):
339
"""Number of messages sent successfully."""
340
341
@property
342
def failure_count(self):
343
"""Number of messages that failed to send."""
344
345
class SendResponse:
346
"""Response from individual message send operations."""
347
348
@property
349
def message_id(self):
350
"""Message ID if successful, None if failed."""
351
352
@property
353
def success(self):
354
"""Whether the message was sent successfully."""
355
356
@property
357
def exception(self):
358
"""Exception if the message failed to send, None if successful."""
359
360
class TopicManagementResponse:
361
"""Response from topic subscription operations."""
362
363
@property
364
def success_count(self):
365
"""Number of tokens successfully subscribed/unsubscribed."""
366
367
@property
368
def failure_count(self):
369
"""Number of tokens that failed to subscribe/unsubscribe."""
370
371
@property
372
def errors(self):
373
"""List of ErrorInfo instances for failed operations."""
374
375
class ErrorInfo:
376
"""Error information for failed operations."""
377
378
@property
379
def index(self):
380
"""Index of the failed item in the original request."""
381
382
@property
383
def reason(self):
384
"""Error reason string."""
385
```
386
387
## Common Options
388
389
```python { .api }
390
class FCMOptions:
391
"""Common FCM options for all platforms."""
392
393
def __init__(self, analytics_label=None):
394
"""
395
Initialize FCM options.
396
397
Args:
398
analytics_label: Analytics label string for tracking (optional)
399
"""
400
401
class LightSettings:
402
"""LED light settings for Android notifications."""
403
404
def __init__(self, color, light_on_duration, light_off_duration):
405
"""
406
Initialize light settings.
407
408
Args:
409
color: Light color as Color instance
410
light_on_duration: On duration as datetime.timedelta
411
light_off_duration: Off duration as datetime.timedelta
412
"""
413
414
class CriticalSound:
415
"""Critical alert sound for iOS notifications."""
416
417
def __init__(self, name, critical=None, volume=None):
418
"""
419
Initialize critical sound.
420
421
Args:
422
name: Sound file name string
423
critical: Whether this is a critical alert (optional)
424
volume: Sound volume (0.0 to 1.0) (optional)
425
"""
426
```
427
428
## Usage Examples
429
430
### Simple Notification
431
432
```python
433
from firebase_admin import messaging
434
435
# Create a simple notification message
436
message = messaging.Message(
437
notification=messaging.Notification(
438
title='Hello World',
439
body='This is a test notification'
440
),
441
token='registration-token'
442
)
443
444
# Send the message
445
response = messaging.send(message)
446
print(f'Successfully sent message: {response}')
447
```
448
449
### Platform-Specific Message
450
451
```python
452
message = messaging.Message(
453
notification=messaging.Notification(
454
title='Platform Specific',
455
body='This message has platform-specific options'
456
),
457
android=messaging.AndroidConfig(
458
priority='high',
459
notification=messaging.AndroidNotification(
460
color='#ff0000',
461
sound='default'
462
)
463
),
464
apns=messaging.APNSConfig(
465
payload=messaging.APNSPayload(
466
aps=messaging.Aps(
467
sound='default',
468
badge=1
469
)
470
)
471
),
472
token='registration-token'
473
)
474
475
response = messaging.send(message)
476
```
477
478
### Topic Messaging
479
480
```python
481
# Send to topic
482
message = messaging.Message(
483
notification=messaging.Notification(
484
title='Topic News',
485
body='Breaking news update!'
486
),
487
topic='news'
488
)
489
490
response = messaging.send(message)
491
492
# Subscribe tokens to topic
493
response = messaging.subscribe_to_topic(['token1', 'token2'], 'news')
494
print(f'Successfully subscribed {response.success_count} tokens')
495
```