Skip to content

Python

Create a Campaign

Create a Campaign that targets all Users that have the App Open.

Make sure you have python-requests installed.

Find out more about campaigns here.

pip install requests
import json
import requests
from pprint import pprint

#You can find your AUTH_TOKEN and HOST here:
#https://dashboard.streethawk.com/static/bb/#app-details
AUTH_TOKEN = 
HOST =
PATH = "/v3/campaigns/campaign"
# selected the "campaign create" endpoint
# from https://streethawk.freshdesk.com/solution/articles/12000022999-api-version-reference

TITLE = "My First Campaign"

#Target all Users that have the App open
FILTERS = [{
    "filter": "online",
    "status": "online",
}]

#Send a Push Message
ACTIONS =  [{
     "action": "simple_push",
     "msg": "My 1st Push",
}]

params = {
    "title":TITLE,
    "action_type":"push",
    "filters":FILTERS,
    "actions":ACTIONS,
}

headers = {
    'Content-type': 'application/json',
    'X-Auth-Token': AUTH_TOKEN,
    'x-app-key': APP_KEY
}
response = requests.post(HOST + PATH, headers=headers, json=params)
pprint(response.json())

Push

StreetHawk provides 3 ways to push to devices:

"Publish" API - basic "Push" API - batch/userlists/traceable/reporting "Campaign" API - flexible segmentation, targeting, timing, reporting

Publish API: This article covers the most basic way to push to a device in StreetHawk is with the Publish API. This takes a single device "installid" and sends a push to it immediately:

import sys
import requests
import simplejson as json

# Get the <API HOST> and <AUTH TOKEN> from the "App Details" page
# in the StreetHawk Dashboard for your app_key.
HOST = 
AUTH_TOKEN=
INSTALLID = '7U2XULU76XGKDMUZ' #see the dashboard for getting the installid

def simple_push(installid):
    print "Publishing to: "+HOST, installid
    params = dict(code=8010,
                title="this is title",
                message="this is the message",
                #alert="this is alert",
                #data="this is data",
                auth_token=AUTH_TOKEN
    )
    if not installid:
        params['installid']=INSTALLID
    else:
        params['installid']=installid

    r = requests.post(HOST + '/v1/installs/publish', params)
    print r.json()

The push is for both iOS and Android and has a flexible number of options. For example "code"=>8010 is a "Simple Push", other types of push are: Rich Push (open a browser or Web View In-App), Open a Screen in the App, Open the Appstore for Rating or Upgrade, Custom JSON, Feedback Form etc etc

The flexible collection of Push Codes are here.

At the end of simple_push the puts is showing the return result in JSON, you'll probably want to parse it yourself. For example, you get a response like:

{
  "code": 0,
  "value": {
    "i": 49690,
    "aps": {
      "sound": "default",
      "alert": "this is title this is the message"
    },
    "c": 8010,
    "l": 13
  }
}

That gives you the message ID for this specific push in value.i and the actual data that was sent to the device.

Simple Push to a User Id We provide a simple way for targeting installs with a unique customer ID. In this full command-line example we are using an email address but you can use whatever is unique in your own backend. You need to tag the user with the sh_cuid at some time. NOTE: you can't push to anonymous/unregistered users with this method, you will need to user the above installid approach or use campaigns.

import sys
import requests
import simplejson as json
from optparse import OptionParser

# Get the <API HOST> and <AUTH TOKEN> from the "App Details" page in the StreetHawk Dashboard for your app_key.
HOST = 
AUTH_TOKEN=
INSTALLID = '7U2XULU76XGKDMUZ'

def publish(installid):
    params = dict(code=8010,
                title="this is title",
                message="this is the message",
                #alert="this is alert",
                #data="this is data",
                app_key=APP_KEY,
                auth_token=AUTH_TOKEN
    )
    if not installid:
        params['installid']=INSTALLID
    else:
        params['installid']=installid

    print(requests.post(HOST + '/v1/installs/publish', params).json())


def install_list(sh_cuid):
    params = dict(
                app_key=APP_KEY,
                auth_token=AUTH_TOKEN)
    if not sh_cuid:
        install_list_count()
    else:
        params['identifier'] = sh_cuid
    list_request = requests.get(HOST + '/v1/installs/list?order_by=-created', params=params)
    install_list=list_request.json()['value']
    if len(install_list):
        return install_list[0].get('installid')
    else:
        print "Could not find this sh_cuid install"


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-t", "--publish_to_sh_cuid", action="store", help="publish for a specified user &amp;amp;amp; app_key")
    (options, args) = parser.parse_args()
    if not options:
        print "Please provide an operation as an argument"
        sys.exit(-1)
    if options.publish_to_sh_cuid:
        sh_cuid = options.publish_to_sh_cuid
        installid = install_list(sh_cuid)
        if installid:
            print "Will publish for: ",sh_cuid, installid
            publish(installid)
        else:
            print "Please provide a valid sh_cuid"
    else:
        print "Try another option"

Advanced Push

StreetHawk provides 3 ways to push to devices:

"Publish" API - basic "Push" API - batch/userlists, traceable, reporting "Campaign" API - flexible segmentation, targeting, timing, reporting

Push API: This article covers how to Push to Users. StreetHawk takes a user-centric approach to push simplifying the link between your own CRM/Backend and the StreetHawk cloud. The recipients of this API call can be specified by:

sh_cuid - your CRM/Backend ID for the user. This could be a GUID or something like an email address (if that is how the user logs in) usernames - a list/array of user sh_cuids userlist_id - StreetHawk has a Userlist concept that can be accessed via the StreetHawk Console or Userlist API.

By setting the sh_cuid from your App is probably the most important initial step you can do - it allows you to tag users from your CRM/Backend, target and track them. For info about Tagging sh_cuid, see:

Tagging API Android, iOS, PhoneGap, Xamarin Android, Xamarin iOS, Titanium tagging

import sys
import requests
import simplejson as json

# Get the <HOST>, <APP_KEY> and <AUTH_TOKEN> from the "App Details" page
# in the StreetHawk Dashboard for your app_key.
HOST =
APP_KEY =
AUTH_TOKEN=

def push():
    print("Pushing to: %s" % HOST)
    params = dict(
                usernames="[\"olly@streethawk.com\", \"david@streethawk.com\"]",
                code=8010,
                title="this is title",
                message="this is the message",
                #alert="this is alert",
                #data="this is data",
                app_key=APP_KEY,
                auth_token=AUTH_TOKEN
    )
    print(requests.post(HOST + '/v1/push', params).json())

The push is for both iOS and Android and has a flexible number of options. For example "code"=>8010 is a "Simple Push", other types of push are: Rich Push (open a browser or Web View In-App), Open a Screen in the App, Open the Appstore for Rating or Upgrade, Custom JSON, Feedback Form etc etc

A common usage is to open a specific instance of a screen (e.g a product or place page). For this, use:

"code"=>8010, # Custom JSON 
"data"=> <your custom JSON>,

The flexible collection of Push Codes are here. Documentation for the Push API is here.

At the end of the push function the puts is showing the return result in JSON, you'll probably want to parse it yourself. For example, you get a response like:

{
  "code": 0,
  "value": "5YPZ697CV5"
}

That gives you the "Campaign" ID for this specific push in value.

Push to all devices (Broadcast)

A common requirement is to send a push to all users. Whilst we don't think its a terrific idea (e.g you should segment/personalize and try to target users in an appropriate time-of-day for their timezone) - here is one example of how you can achieve this.

import requests
import simplejson as json

# Get the <HOST> and <AUTH TOKEN> from the "App Details" page in
# the StreetHawk Dashboard for your app_key.
HOST = 
AUTH_TOKEN =

def create_campaign(campaign_title, push_title, push_msg):
    params = dict(
        auth_token=AUTH_TOKEN,
        title=campaign_title,
        status=1, # enabled
        type=1, # run once (not continuously for all new installs - which you may want 
        rules=json.dumps([{"action":"simple_push", "type":"push","title":push_title, "msg":push_msg, "data":      {}}])
    )
    print(requests.post(HOST + '/v1/campaigns/create', params).json())

create_campaign("Example Push to All","my push title", "my push message") 

In the example above the broadcast is achieved by omitting filters in the "rules". As you can see we have no filters, only an "action" for a simple_push - all push actions are supported. For example custom JSON can be sent - check out the Raw JSON Action.

There are a few benefits to using a campaign approach:

you can let it run for a period of time or forever (Type = 1 or 2) to push to new users. (Although we recommend waiting a while before sending on-boarding push messages). you can review the performance of the push notifications and views message history is stored for each device - so you can confirm it was sent.

NOTE: Its important to realize that each campaign is unique and that StreetHawk only sends: "one push per campaign per device". So if you want to run a similar broadcast push, then create a new campaign. Of course - you can alter a campaign once its started. Refer to Campaigns API for the details.

Batch Adding Geofences

Here is a simple example you can use as a basis for uploading new geofences as a batch. In this case, its just a simple POST for the Geofence creation, if you are updating, then you can use the same POST but by providing the "suid" of the geofence, you are updating the fields.

To get the "suid" you can observe it in the last line of this snippet, its returned in the POST response and then store it. Alternatively you can do a GET on /geofences and iterate over the returned JSON list to get the suid(s).

import requests
import simplejson as json

# Get the <HOST>, <APP_KEY> and <AUTH_TOKEN> from the "App Details" page in 
# the StreetHawk Dashboard for your app_key.
HOST = 
APP_KEY =
AUTH_TOKEN=

def create_geofence(geofence_title, lat, lng):
 params = dict(app_key=APP_KEY,
 auth_token=AUTH_TOKEN,
 title=geofence_title,
 latitude=lat,
 longitude=lng,
 )
 r = requests.post(HOST + '/v1/geofences', params)
 print r.json()

create_geofence("SF Union Square","37.784999", "-122.407511")
create_geofence("SF Marina","37.803914", "-122.439815") 

Tagging Users from a MySQL System

This is a python example that extracts data from a mysql database and updates users in StreetHawk so that you can provide real-time triggered campaigns based on these "tags".

import requests
import simplejson as json
import datetime
import mysql.connector

# Get the <API HOST>, <APP_KEY> and <AUTH_TOKEN> from the "App Details" page in
# the StreetHawk Dashboard for your app_key.

HOST = 
APP_KEY = 
AUTH_TOKEN =

def tag_names_by_cuid(the_cuid,first_name, last_name):
    params = dict(app_key=APP_KEY, auth_token=AUTH_TOKEN, sh_cuid=the_cuid, key="sh_first_name", string=first_name)
    r = requests.post(HOST + '/v1/tag', params)
    print r.json()
    params = dict(app_key=APP_KEY, auth_token=AUTH_TOKEN, sh_cuid=the_cuid, key="sh_last_name", string=last_name)
    r = requests.post(HOST + '/v1/tag', params)


cnx = mysql.connector.connect(user='root', database='my-backend-database')
cursor = cnx.cursor()

last_date = datetime.date(2014, 1, 1) # or some other date you want to sync since.
query = "SELECT id, first_name, last_name, updated_on FROM users WHERE updated_on > %s" % last_date

cursor.execute(query)

row = cursor.fetchone()
while row is not None:
    tag_names_by_cuid(row[0],row[1],row[2])
    row = cursor.fetchone()

cursor.close()
cnx.close()

Tag User

To tag a User you have to set the User's sh_cuid first. The complete tagging API documentation can be found here. Make sure you have python-requests installed.

import json
import requests
from pprint import pprint

#You can find your AUTH_TOKEN and HOST here:
#https://dashboard.streethawk.com/static/bb/#app-details
AUTH_TOKEN = 
HOST = 
PATH = # select endpoint from https://streethawk.freshdesk.com/solution/articles/12000022999-api-version-reference


params = dict(
    sh_cuid=<sh_cuid>,
    key='level',
    numeric=5,
)

headers = {'X-Auth-Token': AUTH_TOKEN} 
response = requests.post(HOST + PATH, headers=headers, data=params)
pprint(response.json()) 

Delete Install

Deletes an Install and all information that is attached to it (e.g. Sessions, Push History) completely. Make sure you have python-requests installed. Be careful using this API. Deleting Installs is a permanent action!

#You can find your AUTH_TOKEN and HOST here:
#https://dashboard.streethawk.com/static/bb/#app-details
AUTH_TOKEN = ''
HOST = ''

#You can list your Installs under 'Growth Campaigns' - 'User Search'
INSTALLID = ''

import json
import requests
from pprint import pprint


PATH = '/v1/installs/delete'

params = dict(
    installid=INSTALLID,
)

headers = {'X-Auth-Token': AUTH_TOKEN} 
response = requests.post(HOST + PATH, headers=headers, data=params)
pprint(response.json())