CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyfcm

Python client for FCM - Firebase Cloud Messaging (Android, iOS and Web)

Pending
Overview
Eval results
Files

core-messaging.mddocs/

Core Messaging

PyFCM's core messaging functionality provides comprehensive support for sending push notifications through Firebase Cloud Messaging HTTP v1 API. The system supports multiple targeting methods, message types, and platform-specific configurations.

Capabilities

FCMNotification Class

Main client class for Firebase Cloud Messaging operations, handling authentication, request management, and message delivery.

class FCMNotification:
    def __init__(
        service_account_file: Optional[str] = None,
        project_id: Optional[str] = None,
        credentials: Optional[Credentials] = None,
        proxy_dict: Optional[dict] = None,
        env: Optional[str] = None,
        json_encoder=None,
        adapter=None
    ):
        """
        Initialize FCM client.
        
        Parameters:
        - service_account_file: Path to service account JSON file
        - project_id: Google Cloud project ID
        - credentials: Google OAuth2 credentials instance (ADC, etc.)
        - proxy_dict: Proxy configuration {"http": "...", "https": "..."}
        - env: Environment setting ("app_engine" for App Engine)
        - json_encoder: Custom JSON encoder class
        - adapter: Custom HTTP adapter instance
        """

Notification Messaging

Send display notifications that appear in the device's notification tray with title, body, and optional image.

def notify(
    fcm_token=None,
    notification_title=None,
    notification_body=None,
    notification_image=None,
    data_payload=None,
    topic_name=None,
    topic_condition=None,
    android_config=None,
    apns_config=None,
    webpush_config=None,
    fcm_options=None,
    dry_run=False,
    timeout=120
):
    """
    Send push notification to device, topic, or conditional target.
    
    Parameters:
    - fcm_token (str, optional): FCM device registration token
    - notification_title (str, optional): Notification title text
    - notification_body (str, optional): Notification body text  
    - notification_image (str, optional): Image URL for notification
    - data_payload (dict, optional): Custom key-value data payload
    - topic_name (str, optional): Topic name for broadcasting
    - topic_condition (str, optional): Boolean topic condition expression
    - android_config (dict, optional): Android-specific message options
    - apns_config (dict, optional): Apple Push Notification options
    - webpush_config (dict, optional): Web push protocol options
    - fcm_options (dict, optional): Platform-independent FCM options
    - dry_run (bool, optional): Validate without sending (default: False)
    - timeout (int, optional): Request timeout seconds (default: 120)
    
    Returns:
    dict: Response containing message name/ID
    
    Raises:
    AuthenticationError: Invalid credentials or authentication failure
    InvalidDataError: Malformed data or missing required parameters
    FCMServerError: FCM service temporarily unavailable
    FCMNotRegisteredError: Invalid or unregistered device token
    FCMSenderIdMismatchError: Token sender mismatch
    """

Data Messaging

Send data-only messages containing custom key-value pairs that are processed by the client application without displaying notifications.

# Data-only message (no notification display)
data_payload = {
    "action": "sync_data",
    "user_id": "12345",
    "timestamp": "2024-01-01T00:00:00Z"
}

result = fcm.notify(
    fcm_token="device_token",
    data_payload=data_payload
)

Topic Messaging

Broadcast messages to devices subscribed to specific topics or topic condition expressions.

# Send to topic subscribers
result = fcm.notify(
    topic_name="news",
    notification_title="Breaking News",
    notification_body="Important update"
)

# Conditional topic messaging
topic_condition = "'sports' in topics && ('basketball' in topics || 'football' in topics)"
result = fcm.notify(
    topic_condition=topic_condition,
    notification_title="Sports Update",
    notification_body="Game results are in!"
)

Platform-Specific Configuration

Configure platform-specific options for Android, iOS, and Web platforms using dedicated configuration objects.

# Android-specific configuration
android_config = {
    "notification": {
        "icon": "stock_ticker_update",
        "color": "#f45342"
    },
    "data": {
        "click_action": "FLUTTER_NOTIFICATION_CLICK"
    }
}

# iOS-specific configuration  
apns_config = {
    "headers": {
        "apns-priority": "10"
    },
    "payload": {
        "aps": {
            "alert": {
                "title": "Custom Title",
                "body": "Custom Body"
            },
            "badge": 42
        }
    }
}

# Web push configuration
webpush_config = {
    "headers": {
        "TTL": "86400"
    },
    "notification": {
        "icon": "https://example.com/icon.png",
        "actions": [
            {
                "action": "view",
                "title": "View Details"
            }
        ]
    }
}

result = fcm.notify(
    fcm_token="device_token",
    notification_title="Multi-platform Message",
    android_config=android_config,
    apns_config=apns_config,
    webpush_config=webpush_config
)

Authentication Methods

Multiple authentication methods including service account files, Google OAuth2 credentials, and environment variables.

# Service account file authentication
fcm = FCMNotification(
    service_account_file="path/to/service-account.json",
    project_id="your-project-id"
)

# Google OAuth2 credentials (ADC, impersonation, etc.)
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_info(
    credential_dict,
    scopes=['https://www.googleapis.com/auth/firebase.messaging']
)
fcm = FCMNotification(
    credentials=credentials,
    project_id="your-project-id"
)

# With proxy configuration
proxy_dict = {
    "http": "http://proxy.example.com:8080",
    "https": "http://proxy.example.com:8080"
}
fcm = FCMNotification(
    service_account_file="service-account.json",
    project_id="your-project-id",
    proxy_dict=proxy_dict
)

Utility Methods

Core utility methods available on FCMNotification instances for advanced use cases and custom request handling.

def json_dumps(self, data):
    """
    Standardized JSON serialization with FCM-compatible formatting.
    
    Parameters:
    - data: Dictionary or list to be serialized
    
    Returns:
    bytes: UTF-8 encoded JSON with sorted keys and separators
    """

def parse_response(self, response):
    """
    Parse FCM HTTP response and handle error conditions.
    
    Parameters:
    - response: HTTP response object from requests
    
    Returns:
    dict: Parsed response data containing message identifier
    
    Raises:
    AuthenticationError: Authentication failure (401)
    InvalidDataError: Malformed request data (400)
    FCMSenderIdMismatchError: Sender authorization error (403)
    FCMNotRegisteredError: Invalid token (404)
    FCMServerError: Server errors and timeouts (5xx)
    """

def parse_payload(
    self,
    fcm_token=None,
    notification_title=None,
    notification_body=None,
    notification_image=None,
    data_payload=None,
    topic_name=None,
    topic_condition=None,
    android_config=None,
    apns_config=None,
    webpush_config=None,
    fcm_options=None,
    dry_run=False
):
    """
    Convert notification parameters into FCM-compatible JSON payload.
    
    Parameters: Same as notify() method
    
    Returns:
    bytes: JSON payload ready for FCM API request
    
    Raises:
    InvalidDataError: Invalid configuration format or data
    """

Types

# From google.oauth2.credentials
class Credentials:
    """Google OAuth2 credentials for authentication"""
    
# Response format
ResponseDict = dict  # Contains "name" key with message identifier

# Configuration dictionaries
AndroidConfig = dict  # Android-specific message configuration
APNSConfig = dict     # Apple Push Notification Service configuration  
WebpushConfig = dict  # Web push protocol configuration
FCMOptions = dict     # Platform-independent FCM options

Install with Tessl CLI

npx tessl i tessl/pypi-pyfcm

docs

async-operations.md

core-messaging.md

error-handling.md

index.md

tile.json