Firebase Cloud Messaging (FCM) with FastAPI for Sending Notifications

Firebase Cloud Messaging (FCM) is a service from Google that allows developers to send push notifications and messages to users on iOS, Android, and web applications.
It supports features like targeting specific users, sending real-time updates, and engaging users with timely notifications. FCM can be easily integrated into Python applications, allowing developers to send notifications from their back end, like using FastAPI in this article.
1. Setting Up FCM on Firebase Portal
Before sending notifications, you need to set up Firebase Cloud Messaging on the Firebase portal.
Creating a Firebase Project
Go to the Firebase Console.
Click on “Create a project” and follow the setup instructions.
Once your project is created, go to Project settings (gear icon in the left menu).
Enabling Firebase Cloud Messaging
In Project settings, navigate to the Cloud Messaging tab.
Ensure that Firebase Cloud Messaging is enabled.
Service Account JSON File
Go to Project settings > Service accounts tab.
Click “Generate new private key” under the Firebase Admin SDK section.
This will download a JSON file (
serviceAccountKey.json
), which contains the credentials needed for your FastAPI application to authenticate with Firebase.
2. Setting Up FastAPI for Sending Notifications
Installing Required Libraries
pip install fastapi py-fcm
Initializing FastAPI Application
from fastapi import FastAPI
from pydantic import BaseModel
from pyfcm import FCMNotification
app = FastAPI()
Model for Input Validation
Define a model to handle the API request input, this model will include
title
,data
,priority
, anddevice_token
.
class NotificationRequest(BaseModel):
title: str
data: dict
priority: str # Can be "high" or "normal"
device_token: str
Configuring FCMNotification with Service Account File
# Load the service account JSON file for Firebase authentication
service_account_file = "path/to/your/serviceAccountKey.json"
# Firebase Project-ID
project_id = ""
# Initialize the FCMNotification object using the service account file
fcm = FCMNotification(service_account_file=service_account_file, project_id=project_id)
Implementing the Send Notification Endpoint
The
notify_single_device
method will use thetitle
,data
,priority
, anddevice_token
from the request body. Based on thepriority
, theandroid_config
dictionary will be adjusted.
@app.post("/send-notification/")
async def send_notification(request: NotificationRequest):
android_config = {}
# Handle priority
if request.priority == "high":
android_config["priority"] = "HIGH"
android_config.setdefault("notification", {})["notification_priority"] = "PRIORITY_MAX"
else:
android_config["priority"] = "NORMAL"
# Hardcoded values for sound and channel_id (OPTIONAL)
android_config.setdefault("notification", {})["sound"] = "default" # Replace with desired sound which is loaded in the Application
android_config.setdefault("notification", {})["channel_id"] = "your_channel_id" # Replace with your channel ID
# Build the notification payload
kwargs = {
"fcm_token": request.device_token,
"notification_title": request.title,
"notification_body": request.data.get("message", ""),
"android_config": android_config,
"data": request.data
}
# Send the notification
result = fcm.notify(**kwargs)
return {"status": "Notification Sent", "result": result}
3. Testing the FCM Notifications
POST request to
http://127.0.0.1:8000/send-notification/
with a JSON payload
{
"title": "New Order",
"data": {
"message": "You have a new order to process",
"order_ids": [123, 456]
},
"priority": "high",
"device_token": "YOUR_DEVICE_TOKEN"
}
An alternative approach to sending notifications is to use Firebase Admin SDK, which provides additional features and greater control over your Firebase Cloud Messaging setup
You can explore the full range of configuration options in the Firebase Cloud Messaging documentation for additional features and capabilities.