Install aioapns via pip
masterInstall the aioapns library using pip to start sending push notifications via APNs using Python's asyncio framework.
$ pip install aioapnsrepository·master·Indexed 41 days ago
https://github.com/fatal1ty/aioapnsAn efficient, asynchronous Apple Push Notification Service (APNs) client library for Python, built on asyncio and HTTP2. It supports both certificate-based and token-based (.p8 key) authentication, connection pooling, and sandbox environment switching.
Install the aioapns library using pip to start sending push notifications via APNs using Python's asyncio framework.
$ pip install aioapnsTo send notifications, you must first initialize an APNs client using either a certificate or a token-based approach. Then, create a NotificationRequest object containing the device_token and the notification message payload. Finally, call send_notification(request) on your client instance.
Supported configuration options for APNs include:
client_cert: Path to the certificate file (for certificate-based auth).key: The loaded key (for token-based auth).key_id: Your Apple API Key ID.team_id: Your Apple Team ID.topic: Your app's Bundle ID.use_sandbox: Boolean to switch between production and development APNs servers.import asyncio
from uuid import uuid4
from aioapns import APNs, NotificationRequest, PushType
async def run():
# Example using Certificate-based authentication
apns_cert_client = APNs(
client_cert='/path/to/apns-cert.pem',
use_sandbox=False,
)
# Example using Token-based authentication (p8 key)
# Note: 'read' is a placeholder for your logic to load the key file
with open('/path/to/apns-key.p8', 'rb') as f:
key = f.read()
apns_key_client = APNs(
key=key,
key_id='<KEY_ID>',
team_id='<TEAM_ID>',
topic='<APNS_TOPIC>', # Bundle ID
use_sandbox=False,
)
# Construct the notification request
request = NotificationRequest(
device_token='<DEVICE_TOKEN>',
message = {
"aps": {
"alert": "Hello from APNs",
"badge": "1",
}
},
notification_id=str(uuid4()), # optional
time_to_live=3, # optional
push_type=PushType.ALERT, # optional
)
# Send the notifications
await apns_cert_client.send_notification(request)
await apns_key_client.send_notification(request)
if __name__ == "__main__":
asyncio.run(run())The NotificationRequest class is used to define the payload and metadata for a push notification.
Key parameters include:
device_token: The target device's token.message: A dictionary containing the APNs payload (e.g., {"aps": {"alert": "..."]}).notification_id: An optional unique identifier for the notification.time_to_live: An optional integer setting the TTL (Time To Live) for the notification.push_type: An optional PushType enum value (e.g., PushType.ALERT).Use the send_notification method to dispatch a push notification. It takes a NotificationRequest object and returns a NotificationResult.
If the notification is unsuccessful (i.e., response.is_successful is False), the client will either execute the err_func callback provided during initialization or log an error to the logger.
async def send_notification(self, request: NotificationRequest) -> NotificationResult
from aioapns import APNs
from aioapns.common import NotificationRequest
async def main():
client = APNs(key="key.p8", key_id="ID", team_id="TEAM", topic="com.app")
request = NotificationRequest(
# ... populate request fields ...
)
result = await client.send_notification(request)
if result.is_successful:
print("Notification sent successfully!")
else:
print(f"Failed: {result.status} - {result.description}")The APNs class is the primary entry point for sending push notifications. It manages a connection pool and supports two authentication methods: Certificate-based or Token-based (using a .p8 key).
client_cert. You cannot provide a key if client_cert is specified.key, key_id, team_id, and topic.| Parameter | Type | Description |
|---|---|---|
client_cert | Optional[str] | Path to the client certificate file. |
key | Optional[str] | Path to the .p8 private key file. |
key_id | Optional[str] | The Key ID provided by Apple. |
team_id | Optional[str] | Your Apple Developer Team ID. |
topic | Optional[str] | The push topic (usually the bundle ID). |
max_connections | int | Maximum number of concurrent connections (default: 10). |
max_connection_attempts | int | Maximum attempts to establish a connection (default: 5). |
use_sandbox | bool | Set to True to use the APNs sandbox environment (default: False). |
no_cert_validation | bool | If True, skips SSL certificate validation. |
ssl_context | Optional[SSLContext] | A custom ssl.SSLContext instance. |
proxy_host | Optional[str] | Hostname of a proxy server. |
proxy_port | Optional[int] | Port of a proxy server. |
err_func | Optional[Callable] | An async callback function (request, result) -> None called when a notification fails. |
from aioapns import APNs
# Example: Token-based authentication (Recommended)
client = APNs(
key="path/to/AuthKey_ABC123.p8",
key_id="ABC123DEFG",
team_id="TEAMID1234",
topic="com.example.app"
)
# Example: Certificate-based authentication
client = APNs(
client_cert="path/to/client.pem",
topic="com.example.app"
)