OneSignal Python API Client
The `onesignal-python-api` library is the official Python client for the OneSignal Push Notification API. It enables developers to programmatically send push notifications, manage users and segments, and interact with other OneSignal services. The current stable version is 5.3.0, and the library generally maintains a monthly or bi-monthly release cadence, with major versions often introducing significant API changes.
Common errors
-
ModuleNotFoundError: No module named 'onesignal_sdk'
cause You are trying to import from the old `onesignal_sdk` package which was used in versions prior to v4.0.0. The package name changed to `onesignal-python-api` and the import path changed.fixFirst, uninstall the old package: `pip uninstall onesignal_sdk`. Then, install the current package: `pip install onesignal-python-api`. Finally, update your imports to `import onesignal as os_client`. -
TypeError: send_notification() got an unexpected keyword argument 'data'
cause You are passing notification data using an old keyword argument (e.g., `data`, `contents_en`) that is no longer supported or has changed structure in v4.x or v5.x. The new API expects a dictionary for `notification_body` with `contents` as a dictionary, and other top-level keys.fixConsult the current documentation for `send_notification`. Ensure your `notification_body` dictionary uses `contents` (a dictionary of language codes to strings) and other fields as direct keys, e.g., `{'contents': {'en': 'Message'}, 'included_segments': ['All']}`. -
OneSignalAPIError: 400 Bad Request - {'errors': ['App id not found.']}cause The `app_id` provided during client initialization is incorrect, malformed, or does not exist on your OneSignal account.fixDouble-check your OneSignal dashboard for the correct App ID. Ensure it's passed as a string during client initialization, e.g., `client = os_client.Client(app_id='YOUR_CORRECT_APP_ID', ...)`. -
OneSignalAPIError: 401 Unauthorized - {'errors': ['REST API Key not found.']}cause The `rest_api_key` provided during client initialization is incorrect or missing, or lacks the necessary permissions for the requested operation.fixVerify your REST API Key from your OneSignal dashboard. Ensure it is correctly passed as a string to the `rest_api_key` parameter during client initialization. Also, confirm that the key has the required permissions for the API calls you are making.
Warnings
- breaking Version 5.0.0 (February 2024) introduced a complete rewrite of the API client to comply with OneSignal's OpenAPI specification. This involved significant changes to most methods, model structures, and how parameters are passed.
- breaking Version 4.0.0 (May 2023) introduced breaking changes to the `Client` and `Notification` APIs, most notably renaming `create_notification` to `send_notification` and altering parameters.
- gotcha Confusion between `rest_api_key` and `user_auth_key` for client initialization. `rest_api_key` is typically used for sending notifications and app-level operations, while `user_auth_key` is for specific authenticated user management actions (e.g., exporting user data). Using the wrong key will result in authentication errors or permission denied responses.
Install
-
pip install onesignal-python-api
Imports
- Client
from onesignal_sdk.client import Client
import onesignal as os_client
- OneSignalAPIError
from onesignal.exceptions import OneSignalAPIError
Quickstart
import os
import onesignal as os_client
from onesignal.exceptions import OneSignalAPIError
# Initialize the OneSignal client using environment variables for credentials
# Replace 'YOUR_APP_ID' and 'YOUR_REST_API_KEY' with actual values or set environment variables.
app_id = os.environ.get("ONESIGNAL_APP_ID", "YOUR_APP_ID")
rest_api_key = os.environ.get("ONESIGNAL_REST_API_KEY", "YOUR_REST_API_KEY")
# Basic check for placeholder credentials
if app_id == "YOUR_APP_ID" or rest_api_key == "YOUR_REST_API_KEY":
print("WARNING: Please set ONESIGNAL_APP_ID and ONESIGNAL_REST_API_KEY environment variables ")
print(" or replace placeholders for successful API calls.")
try:
client = os_client.Client(
app_id=app_id,
rest_api_key=rest_api_key
)
# Example 1: Send a basic notification to all subscribed users
notification_body = {
"contents": {"en": "Hello from the OneSignal Python API client!"},
"included_segments": ["All"],
"name": "Python Test Notification" # Optional, for internal tracking
}
print("\nAttempting to send a notification...")
notification = client.send_notification(notification_body)
print(f"Notification created successfully. ID: {notification.id}")
# Example 2: Get details for the app (requires appropriate API key permissions)
print("\nAttempting to retrieve app details...")
app_details = client.get_app(app_id)
print(f"Successfully fetched app '{app_details.name}' (ID: {app_details.id})")
except OneSignalAPIError as e:
print(f"\nOneSignal API Error: {e.status_code} - {e.json_body}")
except Exception as e:
print(f"\nAn unexpected error occurred: {e}")