Firebase Admin Python SDK enables server-side Python developers to integrate Firebase services into their applications from privileged environments.
—
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.
Send individual and batch messages to Firebase Cloud Messaging with comprehensive platform-specific customization options.
def send(message, dry_run=False, app=None):
"""
Send a message to Firebase Cloud Messaging.
Args:
message: A Message instance
dry_run: Whether to send in dry-run mode (optional)
app: Firebase app instance (optional)
Returns:
str: Message ID of the sent message
Raises:
QuotaExceededError: If the FCM quota is exceeded
SenderIdMismatchError: If the sender ID is mismatched
ThirdPartyAuthError: If there's a third-party authentication error
UnregisteredError: If the registration token is invalid
"""
def send_each(messages, dry_run=False, app=None):
"""
Send multiple messages to Firebase Cloud Messaging.
Args:
messages: List of Message instances
dry_run: Whether to send in dry-run mode (optional)
app: Firebase app instance (optional)
Returns:
BatchResponse: Response containing individual message results
"""
def send_each_async(messages, dry_run=False, app=None):
"""
Send multiple messages asynchronously to Firebase Cloud Messaging.
Args:
messages: List of Message instances
dry_run: Whether to send in dry-run mode (optional)
app: Firebase app instance (optional)
Returns:
BatchResponse: Response containing individual message results
"""Send messages to multiple registration tokens efficiently using multicast operations.
def send_each_for_multicast(multicast_message, dry_run=False, app=None):
"""
Send a multicast message to multiple registration tokens.
Args:
multicast_message: A MulticastMessage instance
dry_run: Whether to send in dry-run mode (optional)
app: Firebase app instance (optional)
Returns:
BatchResponse: Response containing results for each token
"""
def send_each_for_multicast_async(multicast_message, dry_run=False, app=None):
"""
Send a multicast message asynchronously to multiple registration tokens.
Args:
multicast_message: A MulticastMessage instance
dry_run: Whether to send in dry-run mode (optional)
app: Firebase app instance (optional)
Returns:
BatchResponse: Response containing results for each token
"""Manage device subscriptions to messaging topics for broadcasting messages to groups of devices.
def subscribe_to_topic(tokens, topic, app=None):
"""
Subscribe registration tokens to a topic.
Args:
tokens: List of registration token strings or single token string
topic: Topic name string
app: Firebase app instance (optional)
Returns:
TopicManagementResponse: Response with success/failure counts
"""
def unsubscribe_from_topic(tokens, topic, app=None):
"""
Unsubscribe registration tokens from a topic.
Args:
tokens: List of registration token strings or single token string
topic: Topic name string
app: Firebase app instance (optional)
Returns:
TopicManagementResponse: Response with success/failure counts
"""class Message:
"""A message that can be sent to Firebase Cloud Messaging."""
def __init__(self, data=None, notification=None, android=None, apns=None, webpush=None, token=None, topic=None, condition=None, fcm_options=None):
"""
Initialize a message.
Args:
data: Dict of data payload (optional)
notification: Notification instance (optional)
android: AndroidConfig instance (optional)
apns: APNSConfig instance (optional)
webpush: WebpushConfig instance (optional)
token: Registration token string (optional)
topic: Topic name string (optional)
condition: Condition string (optional)
fcm_options: FCMOptions instance (optional)
"""class MulticastMessage:
"""A message that can be sent to multiple registration tokens."""
def __init__(self, tokens, data=None, notification=None, android=None, apns=None, webpush=None, fcm_options=None):
"""
Initialize a multicast message.
Args:
tokens: List of registration token strings
data: Dict of data payload (optional)
notification: Notification instance (optional)
android: AndroidConfig instance (optional)
apns: APNSConfig instance (optional)
webpush: WebpushConfig instance (optional)
fcm_options: FCMOptions instance (optional)
"""class Notification:
"""Cross-platform notification payload."""
def __init__(self, title=None, body=None, image=None):
"""
Initialize notification.
Args:
title: Notification title string (optional)
body: Notification body string (optional)
image: Image URL string (optional)
"""class AndroidConfig:
"""Android-specific message configuration."""
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):
"""
Initialize Android configuration.
Args:
collapse_key: Collapse key string (optional)
priority: Priority ('normal' or 'high') (optional)
ttl: Time to live as datetime.timedelta (optional)
restricted_package_name: Package name string (optional)
data: Dict of data payload (optional)
notification: AndroidNotification instance (optional)
fcm_options: AndroidFCMOptions instance (optional)
direct_boot_ok: Whether message can be received in direct boot (optional)
"""
class AndroidNotification:
"""Android-specific notification configuration."""
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):
"""Initialize Android notification configuration."""
class AndroidFCMOptions:
"""Android-specific FCM options."""
def __init__(self, analytics_label=None):
"""
Initialize Android FCM options.
Args:
analytics_label: Analytics label string (optional)
"""class APNSConfig:
"""Apple Push Notification service configuration."""
def __init__(self, headers=None, payload=None, fcm_options=None):
"""
Initialize APNS configuration.
Args:
headers: Dict of APNS headers (optional)
payload: APNSPayload instance (optional)
fcm_options: APNSFCMOptions instance (optional)
"""
class APNSPayload:
"""APNS payload configuration."""
def __init__(self, aps=None, **kwargs):
"""
Initialize APNS payload.
Args:
aps: Aps instance (optional)
**kwargs: Additional custom payload fields
"""
class Aps:
"""APNS aps dictionary configuration."""
def __init__(self, alert=None, badge=None, sound=None, content_available=None, category=None, thread_id=None, mutable_content=None, custom_data=None):
"""Initialize APNS aps configuration."""
class ApsAlert:
"""APNS alert configuration."""
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):
"""Initialize APNS alert configuration."""
class APNSFCMOptions:
"""APNS-specific FCM options."""
def __init__(self, analytics_label=None, image=None):
"""
Initialize APNS FCM options.
Args:
analytics_label: Analytics label string (optional)
image: Image URL string (optional)
"""class WebpushConfig:
"""Web push protocol configuration."""
def __init__(self, headers=None, data=None, notification=None, fcm_options=None):
"""
Initialize webpush configuration.
Args:
headers: Dict of webpush headers (optional)
data: Dict of data payload (optional)
notification: WebpushNotification instance (optional)
fcm_options: WebpushFCMOptions instance (optional)
"""
class WebpushNotification:
"""Web push notification configuration."""
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):
"""Initialize webpush notification configuration."""
class WebpushNotificationAction:
"""Web push notification action."""
def __init__(self, action, title, icon=None):
"""
Initialize notification action.
Args:
action: Action identifier string
title: Action title string
icon: Action icon URL string (optional)
"""
class WebpushFCMOptions:
"""Webpush-specific FCM options."""
def __init__(self, link=None, analytics_label=None):
"""
Initialize webpush FCM options.
Args:
link: Link URL string (optional)
analytics_label: Analytics label string (optional)
"""class BatchResponse:
"""Response from batch messaging operations."""
@property
def responses(self):
"""List of SendResponse instances for each message."""
@property
def success_count(self):
"""Number of messages sent successfully."""
@property
def failure_count(self):
"""Number of messages that failed to send."""
class SendResponse:
"""Response from individual message send operations."""
@property
def message_id(self):
"""Message ID if successful, None if failed."""
@property
def success(self):
"""Whether the message was sent successfully."""
@property
def exception(self):
"""Exception if the message failed to send, None if successful."""
class TopicManagementResponse:
"""Response from topic subscription operations."""
@property
def success_count(self):
"""Number of tokens successfully subscribed/unsubscribed."""
@property
def failure_count(self):
"""Number of tokens that failed to subscribe/unsubscribe."""
@property
def errors(self):
"""List of ErrorInfo instances for failed operations."""
class ErrorInfo:
"""Error information for failed operations."""
@property
def index(self):
"""Index of the failed item in the original request."""
@property
def reason(self):
"""Error reason string."""class FCMOptions:
"""Common FCM options for all platforms."""
def __init__(self, analytics_label=None):
"""
Initialize FCM options.
Args:
analytics_label: Analytics label string for tracking (optional)
"""
class LightSettings:
"""LED light settings for Android notifications."""
def __init__(self, color, light_on_duration, light_off_duration):
"""
Initialize light settings.
Args:
color: Light color as Color instance
light_on_duration: On duration as datetime.timedelta
light_off_duration: Off duration as datetime.timedelta
"""
class CriticalSound:
"""Critical alert sound for iOS notifications."""
def __init__(self, name, critical=None, volume=None):
"""
Initialize critical sound.
Args:
name: Sound file name string
critical: Whether this is a critical alert (optional)
volume: Sound volume (0.0 to 1.0) (optional)
"""from firebase_admin import messaging
# Create a simple notification message
message = messaging.Message(
notification=messaging.Notification(
title='Hello World',
body='This is a test notification'
),
token='registration-token'
)
# Send the message
response = messaging.send(message)
print(f'Successfully sent message: {response}')message = messaging.Message(
notification=messaging.Notification(
title='Platform Specific',
body='This message has platform-specific options'
),
android=messaging.AndroidConfig(
priority='high',
notification=messaging.AndroidNotification(
color='#ff0000',
sound='default'
)
),
apns=messaging.APNSConfig(
payload=messaging.APNSPayload(
aps=messaging.Aps(
sound='default',
badge=1
)
)
),
token='registration-token'
)
response = messaging.send(message)# Send to topic
message = messaging.Message(
notification=messaging.Notification(
title='Topic News',
body='Breaking news update!'
),
topic='news'
)
response = messaging.send(message)
# Subscribe tokens to topic
response = messaging.subscribe_to_topic(['token1', 'token2'], 'news')
print(f'Successfully subscribed {response.success_count} tokens')Install with Tessl CLI
npx tessl i tessl/pypi-firebase-admin