OneSignal Python API Client

5.3.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the OneSignal client using environment variables for credentials and then send a simple notification to all users. It also includes an example of fetching app details. Remember to set `ONESIGNAL_APP_ID` and `ONESIGNAL_REST_API_KEY` in your environment or replace the placeholders.

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}")

view raw JSON →