Registry / communication / pyapns-client

pyapns-client

JSON →
library2.0.6pypypi✓ verified 27d ago

pyapns-client is a Python library designed for sending Apple Push Notifications (APNs) to iOS, macOS, and Safari using the modern HTTP/2 Push provider API. It focuses on simplicity, flexibility, and speed, leveraging token-based authentication for enhanced security and avoiding certificate renewal hassles. The current version is 2.0.6, with a more recent async-enabled version (pyapns-client3) also available. This library is actively maintained, with the latest update for the 2.x series in June 2022.

pip install pyapns-client
INSTALL
IMPORT
SIG · PYAPNS-CLIENT
P
pyapns-client
communicationpythonv2.0.6
Install
3.5s avg
Import
276ms
Disk
41MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v2.0.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.286s · 43.2MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 3.5s · import 0.266s · 44MB
41MB installed
● package 41MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

APNSClient
✓ from pyapns_client import APNSClient
IOSPayloadAlert
✓ from pyapns_client import IOSPayloadAlert
IOSPayload
✓ from pyapns_client import IOSPayload
IOSNotification
✓ from pyapns_client import IOSNotification
APNSDeviceException
✓ from pyapns_client import APNSDeviceException
APNSServerException
✓ from pyapns_client import APNSServerException
APNSProgrammingException
✓ from pyapns_client import APNSProgrammingException
UnregisteredException
✓ from pyapns_client import UnregisteredException

This quickstart demonstrates how to send a basic push notification using token-based authentication with `pyapns-client`. It leverages environment variables for sensitive credentials and includes essential error handling for common APNs responses. Ensure you replace placeholder values with your actual Apple Developer details and a valid device token. The `topic` parameter must match your application's bundle ID.

import os from pyapns_client import APNSClient, IOSPayloadAlert, IOSPayload, IOSNotification, APNSDeviceException, APNSServerException, APNSProgrammingException, UnregisteredException # --- Environment Variables (Replace with your actual values or secure fetching) --- # APNS_MODE: APNSClient.MODE_DEV or APNSClient.MODE_PROD # APNS_AUTH_KEY_PATH: Path to your .p8 authentication key file # APNS_AUTH_KEY_ID: Your 10-character Key ID from Apple Developer portal # APNS_TEAM_ID: Your 10-character Team ID from Apple Developer portal # APNS_ROOT_CERT_PATH: Path to Apple's root certificate (e.g., AppleWWDRCA.pem or AAACertificateServices.pem) # Can be None if included in your system's trust store or not strictly required for token-based auth. APNS_MODE = os.environ.get('APNS_MODE', APNSClient.MODE_DEV) # Use MODE_PROD for production APNS_AUTH_KEY_PATH = os.environ.get('APNS_AUTH_KEY_PATH', 'path/to/AuthKey_YOURKEYID.p8') APNS_AUTH_KEY_ID = os.environ.get('APNS_AUTH_KEY_ID', 'YOURKEYID') APNS_TEAM_ID = os.environ.get('APNS_TEAM_ID', 'YOURTEAMID') APNS_ROOT_CERT_PATH = os.environ.get('APNS_ROOT_CERT_PATH', None) # Or 'path/to/AAACertificateServices.pem' device_token = os.environ.get('DEVICE_TOKEN', 'a_sample_device_token_hex_string') APP_BUNDLE_ID = os.environ.get('APP_BUNDLE_ID', 'com.example.yourapp') if APNS_ROOT_CERT_PATH and not os.path.exists(APNS_ROOT_CERT_PATH): print(f"Warning: APNS_ROOT_CERT_PATH '{APNS_ROOT_CERT_PATH}' not found. Set it correctly or None.") if not os.path.exists(APNS_AUTH_KEY_PATH): print(f"Error: APNS_AUTH_KEY_PATH '{APNS_AUTH_KEY_PATH}' not found. Please provide a valid path to your .p8 key.") exit(1) try: # Initialize the client using token-based authentication client = APNSClient( mode=APNS_MODE, auth_key_path=APNS_AUTH_KEY_PATH, auth_key_id=APNS_AUTH_KEY_ID, team_id=APNS_TEAM_ID, root_cert_path=APNS_ROOT_CERT_PATH # Optional, depends on your trust store setup ) # Create the notification payload alert = IOSPayloadAlert(title='Hello from pyapns-client!', subtitle='New Message', body='This is a test push notification.') payload = IOSPayload(alert=alert, badge=1, sound='default') # Create the notification object notification = IOSNotification(payload=payload, topic=APP_BUNDLE_ID) print(f"Attempting to push notification to device: {device_token}") # Send the notification client.push(notification=notification, device_token=device_token) print("Notification sent successfully!") except UnregisteredException as e: print(f"Device is unregistered: {e.device_token}. Remove from DB. Timestamp: {e.timestamp_datetime}") except APNSDeviceException as e: print(f"Device error for {e.device_token}: {e.reason}. Flag device as invalid.") except APNSServerException as e: print(f"APNs server error: {e.reason}. Try again later.") except APNSProgrammingException as e: print(f"Programming error: {e.reason}. Check your code and APNs settings.") except Exception as e: print(f"An unexpected error occurred: {e}")
pyapns-client --version
Debug
Known issues
breakingThis library requires Python 3.6 or higher. Older Python 2.x environments or Python 3.5 and below are not supported.
fix
Upgrade your Python environment to 3.6 or newer. If on an older system, consider using a different APNs library or updating your infrastructure.
affects: <2.0.0 (and Python <3.6)
gotchaThe `topic` parameter in `IOSNotification` *must* precisely match your application's bundle ID (e.g., 'com.example.yourapp'). A mismatch will result in push delivery failures.
fix
Verify your app's bundle ID in Xcode or your Apple Developer account and ensure it's passed correctly as the `topic` argument.
affects: All versions
deprecatedThis library (pyapns-client) uses Apple's HTTP/2 APNs API with token-based authentication. Apple deprecated the legacy binary API in late 2019. Using older APNs libraries that rely on the binary API or only certificate-based authentication (without JWT tokens) is highly discouraged and may cease to function.
fix
Ensure you are using an up-to-date APNs client library like `pyapns-client` that supports the HTTP/2 API and token-based authentication.
affects: Libraries using the binary API (not pyapns-client)
gotchaAPNs responses require robust error handling. Device tokens can become invalid (e.g., app uninstalled), leading to `UnregisteredException`. Server issues (e.g., throttling) can cause `APNSServerException`. Incorrect payload or settings will raise `APNSProgrammingException`.
fix
Implement comprehensive `try-except` blocks for `UnregisteredException`, `APNSDeviceException`, `APNSServerException`, and `APNSProgrammingException` to manage device tokens (remove unregistered ones), retry server failures, and debug programming errors effectively.
affects: All versions
gotchaThe APNs payload has size limits (4KB for most notifications, 5KB for VoIP). Exceeding this limit will result in delivery failure without a clear error from the client library.
fix
Keep your notification payload as concise as possible. If sending large data, consider notifying the app to fetch content from your server instead of including it directly in the push payload.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pyapns_client'
The `pyapns-client` library is either not installed, or there's a typo in the import statement, or Python cannot find the installed package in its path.
fix
Ensure the library is correctly installed using `pip install pyapns_client`. Verify that your import statement is `from pyapns_client import APNSClient` (or other components) and not `from apnsclient import ...` or similar incorrect names.
pyapns_client.exceptions.UnregisteredException
This exception indicates that the device token you attempted to send a push notification to is no longer valid or active for the given application. This typically happens if the user uninstalled the app or the token has expired.
fix
When this exception is caught, you should remove the associated device token from your database or list of active tokens to prevent future delivery attempts to an unregistered device.
pyapns_client.exceptions.APNSDeviceException
This exception signifies an issue with the specific device token, such as a 'BadDeviceToken' status from APNs, meaning the token is malformed or does not match the environment.
fix
Flag the device token as potentially invalid and consider removing it from your database after a few failed attempts. Ensure the device token corresponds to the correct APNs environment (sandbox vs. production).
pyapns_client.exceptions.APNSServerException
This is a generic exception indicating an error on the APNs server side. This can include issues like 'InvalidProviderToken' (authentication key/certificate problems), throttling, or internal server errors within APNs.
fix
Catch this exception and implement a retry mechanism, as it often indicates a transient server issue. For persistent errors, verify your APNs authentication credentials (e.g., `.p8` key, `auth_key_id`, `team_id`) are correct, unexpired, and match the environment (development/production).
pyapns_client.exceptions.APNSProgrammingException
This exception suggests an issue with the notification payload itself, such as an incorrect format, missing required fields, or a payload size exceeding Apple's limits.
fix
Review your notification payload construction to ensure it adheres to Apple's APNs payload specifications. Check for correct topic, push type, and payload size.
Upgrade
Version history
2.0.6latest on PyPI · released Jun 9, 2022
Audit
Dependencies
httpxrequiredUsed as the underlying HTTP client for APNs HTTP/2 communication.
Agent activity
16 hits · last 30 days
node
12
OpenAI (training)
1
Resources
pyapns-client — pip install pyapns-client · libregistry