PyFCM - Firebase Cloud Messaging Client

2.1.0 · active · verified Thu Apr 16

PyFCM is an active Python client library for Firebase Cloud Messaging (FCM), currently at version 2.1.0. It provides a convenient interface for sending push notifications and data messages to Android, iOS, and web clients. The library's release cadence is tied to significant FCM API changes, ensuring compatibility with the latest Firebase services.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to send both notification and data messages to a single FCM device using PyFCM's `FCMNotification` class. It leverages the FCM v1 API, requiring a Firebase service account JSON file (specified via `GOOGLE_APPLICATION_CREDENTIALS` environment variable) and your Firebase project ID for authentication. The `notify()` method is the unified entry point for sending messages.

import os
from pyfcm import FCMNotification

# For FCM v1 API, authentication uses a service account JSON file.
# Set GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of your service account JSON file.
# Ensure your service account has 'Firebase Cloud Messaging API' enabled and 'Firebase Cloud Messaging Sender' role.
# A project_id is also required.

service_account_path = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', '')
project_id = os.environ.get('FCM_PROJECT_ID', 'your-project-id') # Replace with your Firebase Project ID
fcm_token = os.environ.get('FCM_DEVICE_TOKEN', 'YOUR_DEVICE_REGISTRATION_ID') # Replace with a device token

if not service_account_path:
    print("WARNING: GOOGLE_APPLICATION_CREDENTIALS environment variable not set. Using dummy service_account_file for example.")
    # For a runnable example without actual auth, you might provide a non-existent path,
    # but real usage *requires* a valid service account file.
    # For testing, ensure you have a valid service_account_path and project_id.

# Initialize FCMNotification with service account file and project ID for FCM v1 API
try:
    push_service = FCMNotification(service_account_file=service_account_path, project_id=project_id)

    # Send a notification message to a single device
    notification_title = "Test Notification"
    notification_body = "This is a test message from PyFCM!"

    result = push_service.notify(
        fcm_token=fcm_token,
        notification_title=notification_title,
        notification_body=notification_body
    )

    print("Notification sent. Result:", result)

    # Send a data message (handled by the client app)
    data_payload = {"score": "100", "time": "10:00"}
    data_result = push_service.notify(
        fcm_token=fcm_token,
        data_payload=data_payload
    )
    print("Data message sent. Result:", data_result)

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →