Prabha Obulichetty
6 min readMar 4, 2024

Mastering Firebase Push Notifications with Python: Elevate Your App’s Engagement with Firebase Admin SDK

Introduction:

In this article, discover the seamless integration of Firebase Cloud Messaging (FCM) push notifications into your Python workflow. Dive into the implementation details as we explore the power of the Firebase Admin SDK, demonstrating how to trigger FCM push notifications effortlessly through a purposeful Python script. Elevate your app’s user engagement by harnessing the capabilities of FCM with step-by-step guidance and insightful examples.

What are Push Notifications?

Push notifications are small messages that pop up on a user’s device. App publishers and website owners can send them anytime, and users don’t have to be in the app / on the website to receive them. A smartphone user can see notifications even when their phone is locked.

Why use Push Notifications?

Push notifications enhance user experience by delivering personalized content at opportune times, fostering convenience and engagement.

Leveraging this communication channel not only improves customer engagement and retention but also drives conversions and boosts app revenue.

Ultimately, push notifications are a highly effective tool for maximizing user lifetime value and sustaining long-term app success.

How do Push Notifications work?

  • Client-side Integration: Developers integrate push notification functionality into their app or website using platform-specific SDKs like Firebase Cloud Messaging for mobile or Web Push API for browsers.
  • Registration: Upon installation or first launch, the app registers with the push notification service, generating a unique device token for mobile or an endpoint URL for the web.
  • Server-side Setup: Developers configure a server responsible for sending push notifications to the service, such as Firebase Cloud Messaging.
  • Sending Notifications: The server composes notification messages, including target device tokens or endpoint URLs, and sends requests to the push notification service’s API.
  • Delivery to Devices: The push notification service receives requests and forwards notifications to devices or browsers associated with provided tokens or URLs.
  • Displaying Notifications: Devices or browsers display notifications natively, based on settings and configurations, such as showing alerts, badge icons, or playing sounds.
  • User Interaction: Users interact with notifications by tapping on them, triggering actions specified by developers, like opening the app or performing custom actions.

Now that we have a basic idea of what a push notification is and how it works, let’s dive into the practical implementation of sending push notifications to mobile devices using Python.

Before jumping into the script, there are some prerequisites for this implementation. Let’s go through them one by one.

  1. Use the firebase-admin package in Python to send push notifications via Firebase Cloud Messaging (FCM). Install the firebase-admin package if you haven't already:
pip install firebase-admin

Python recommended version : 3.8+

2. Obtain the Firebase service account key JSON file.

Reference: How to get Firebase service account key?

3. Collect the device tokens of the targeted audience.

Now that all the prerequisites are completed, let’s take a look at a simple script that can be used to send push notifications to mobile devices seamlessly.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging

def send_push_notification(server_key, device_tokens, title, body, data=None):
cred = credentials.Certificate(server_key)
firebase_admin.initialize_app(cred)

message = messaging.MulticastMessage(
notification=messaging.Notification(
title=title,
body=body
),
tokens=device_tokens
)
if data:
message.data = data

response = messaging.send_multicast(message)

print("Successfully sent notification:", response)

# Replace with the path to your service account key JSON file
server_key = '/path/to/your/serviceAccountKey.json'

# Replace with your device tokens
device_tokens = [
'DEVICE_TOKEN_1',
'DEVICE_TOKEN_2',
# Add more device tokens as needed
]

# Notification details
title = 'Test Notification'
body = 'This is a test notification.'
data = {
'key1': 'value1',
'key2': 'value2'
}

# Send push notification
send_push_notification(server_key, device_tokens, title, body, data)

Replace '/path/to/your/serviceAccountKey.json' with the path to your Firebase service account key JSON file. Replace 'DEVICE_TOKEN_1', 'DEVICE_TOKEN_2', etc., with the device tokens of the devices you want to send the notification to. Customize title, body, and data according to your notification requirements.

This script initializes the Firebase Admin SDK with your service account credentials and sends a multicast message to the specified device tokens.

Web Push Notification:

To send web push notifications using the Firebase Admin SDK for Python, you can use the messaging module. Here's a basic example of how to send a web push notification using Firebase Admin SDK

message = messaging.Message(
notification=messaging.WebpushNotification(
title='Test Notification',
body='This is a test notification.'
),
token='WEB_PUSH_TOKEN'
)

# Send the message
response = messaging.send(message)

Concept of Priority and its usage:

In the context of push notifications, Priority refers to the level of urgency or importance assigned to a notification. It helps the push notification service determine the delivery priority of the notification, especially when there are multiple notifications queued for delivery.

Most push notification services provide a priority setting that developers can specify when sending notifications. There are typically two levels of priority:

  1. Normal Priority: This is the default priority for notifications. Notifications with normal priority are delivered to the device in a best-effort manner, without any guarantee of immediate delivery. The system may delay the delivery of normal priority notifications in favor of higher priority messages or to conserve device resources.
  2. High Priority: Notifications with high priority are typically delivered immediately, even if the device is in a low-power state or has limited connectivity. High-priority notifications are useful for time-sensitive messages or critical alerts that require immediate attention from the user.

Here is an example of how to set the priority to “high” in an FCM message using Python’s Firebase Admin SDK:

message = messaging.Message(
notification=messaging.Notification(
title='High Priority Notification',
body='This is a high-priority message.'
),
token='DEVICE_TOKEN',
android=messaging.AndroidConfig(
priority='high'
)
)

response = messaging.send(message)
  1. The priority property is set within the AndroidConfig object.
  2. The priority level can influence the behavior of message delivery, especially when the device is in a low-power state.

Silent Notification:

A silent notification, also known as a data-only notification or background notification, is a type of push notification that does not display any visible content such as a title, body, or notification icon. Instead, they carry a custom data payload that the application can use to perform specific tasks or actions in the background without interrupting the user.

Silent notifications are primarily used to perform background tasks or trigger actions within the application without alerting the user with a visible notification. These notifications can be particularly useful for maintaining the freshness of data in the app, checking for updates, or initiating background processes.

In the context of Firebase Cloud Messaging (FCM), you can achieve silent pushes by sending a data message without a notification payload. Here’s an example in Python using Firebase Admin SDK:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging

# Initialize the Firebase Admin SDK
cred = credentials.Certificate('path/to/serviceAccountKey.json')
firebase_admin.initialize_app(cred)

# Define the message
message = messaging.Message(
data={
'key1': 'value1',
'key2': 'value2'
},
token='Device Token'
)

# Send the message
response = messaging.send(message)

print('Successfully sent message:', response)

In this example, the data field contains key-value pairs that your app can use to perform background tasks or update content. Since there is no notification payload, the user won’t see any visible indication of the push notification. It’s essential to handle the incoming data on the client side to execute the desired background tasks.

Conclusion:
In conclusion, push notifications are powerful tools for enhancing user engagement and driving app success. Through client-side integration, server-side setup, and careful management of notification priorities, developers can effectively reach their target audience with personalized content. With the Firebase Admin SDK and Python, sending push notifications becomes seamless, whether for mobile devices or web browsers. Understanding the nuances of push notifications, including silent notifications for background tasks, empowers developers to maximize the impact of their applications and create meaningful user experiences.

Happy Coding!

Prabha Obulichetty

Passionate software developer always seeking new challenges and technologies. Eager to learn and grow in a dynamic environment.