PyFCM - Firebase Cloud Messaging Client
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
-
pyfcm.errors.AuthenticationError: There was an error authenticating the sender account
cause The Firebase API key (or service account credentials) provided is invalid, missing, or lacks the necessary permissions for your project, or you are attempting to use a legacy API key with FCM v1 API.fixFor PyFCM v2.x, ensure you are using a valid Firebase service account JSON key file, that the `GOOGLE_APPLICATION_CREDENTIALS` environment variable points to it, and you've provided the correct `project_id` to `FCMNotification`. Verify the service account has the 'Firebase Cloud Messaging API' enabled and 'Firebase Cloud Messaging Sender' role. If you are on an older PyFCM version, ensure your legacy Server Key is correct. -
FCMServerError: FCM server is temporarily unavailable
cause This error typically indicates an issue with the Firebase Cloud Messaging service itself or that the legacy FCM API endpoints you might be hitting (if using an older `pyfcm` version) have been shut down.fixFirst, check the Firebase status dashboard for any ongoing service outages. If the service is operational, ensure you have upgraded PyFCM to version 2.x to utilize the FCM v1 HTTP API, as the legacy APIs began deprecation and shutdown in 2024. -
AttributeError: 'FCMNotification' object has no attribute 'notify_single_device'
cause You are likely using PyFCM version 2.0.1 or later, which refactored the message sending methods. The individual `notify_single_device`, `notify_multiple_devices`, and `notify_topic_subscribers` methods were removed.fixMigrate your code to use the unified `push_service.notify()` method. All previous functionality is now accessed via parameters to this single method (e.g., `fcm_token` for single device, `registration_ids` for multiple, `topic_name` for topics). -
ModuleNotFoundError: No module named 'pyfcm'
cause The `pyfcm` library is not installed in your current Python environment or the environment where your script is being executed.fixInstall the library using pip: `pip install pyfcm`. If using a virtual environment, ensure it's activated before installation.
Warnings
- breaking Version 2.0.1 migrated to the FCM v1 HTTP API, deprecating the legacy HTTP API. This involves significant changes to method signatures and authentication. Old methods like `notify_single_device`, `notify_multiple_devices`, and `notify_topic_subscribers` were renamed to a single `notify()` method with unified parameters. Authentication now prefers Google service account credentials over a simple API key.
- breaking Prior to 2.0.1, versions like 1.4.0 and 1.2.0 introduced changes to the structure of the response dict returned by notification sending methods. Ensure your code correctly parses the `multicast_ids`, `success`, `failure`, `canonical_ids`, and `results` keys.
- gotcha Authentication with FCM v1 API requires proper Google Cloud credentials, typically a service account key file, and the correct Firebase project ID. Using an outdated or invalid legacy 'Server Key' (API key) with PyFCM v2.x will lead to authentication failures.
- gotcha If you are working within a Django project, consider using `fcm-django` (a separate library) instead of `pyfcm` directly. `fcm-django` provides deeper integration with Django models and often handles authentication with `firebase-admin` (not `pyfcm`) which has its own migration path for FCM v1.
Install
-
pip install pyfcm
Imports
- FCMNotification
from pyfcm import FCMNotification
Quickstart
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}")