Python Backend Sample


Send push notifications to your users with this Python code sample.

The following code will send a push notification to devices with {message: "Hello World!"} as the payload.

# Import Pushy API class
from pushy import PushyAPI

# Payload data you want to send to devices
data = {'message': 'Hello World!'}

# The recipient device tokens
to = ['cdd92f4ce847efa5c7f']

# Optionally, send to a publish/subscribe topic instead
# to = '/topics/news'

# Optional push notification options (such as iOS notification fields)
options = { 
    'notification': {
        'badge': 1,
        'sound': 'ping.aiff',
        'title': 'Test Notification',
        'body': u'Hello World \u270c'
    }
}

# Send the push notification with Pushy
PushyAPI.sendPushNotification(data, to, options)

Create a file named pushy.py and paste the following code inside it:

import json
import urllib2

class PushyAPI:

    @staticmethod
    def sendPushNotification(data, to, options):
        # Insert your Pushy Secret API Key here
        apiKey = 'SECRET_API_KEY';

        # Default post data to provided options or empty object
        postData = options or {}
        
        # Set notification payload and recipients
        postData['to'] = to
        postData['data'] = data

        # Set URL to Send Notifications API endpoint
        req = urllib2.Request('https://api.pushy.me/push?api_key=' + apiKey)

        # Set Content-Type header since we're sending JSON
        req.add_header('Content-Type', 'application/json')

        try:
           # Actually send the push
           urllib2.urlopen(req, json.dumps(postData))
        except urllib2.HTTPError, e:
           # Print response errors
           print "Pushy API returned HTTP error " + str(e.code) + ": " + e.read()

Note: Make sure to replace SECRET_API_KEY with your app's Secret API Key, available in the Pushy Dashboard (Click your app -> API Authentication tab). This is a backend API endpoint. Never expose your application's Secret API Key in your client code.