Urban Airship and RESTful Puts with Python
This will be a quick post with a bit of code. I wanted to share this since I had an awful time finding some working code snippets to communicate with Urban Airship to do Push notifications to Apple for iPhones.
This code snippet will register a new device with Urban Airship that can then receive Push notifications.
import urllib2
from simplejson import dumps as json_dumps
user = UAPUSH_USER
passwd = UAPUSH_PASS
base_url = UAPUSH_BASE_URL
# push_payload = {
# 'aps': { 'badge': 2 },
# 'device_tokens': [ 'devToken01', 'devToken02', etc ]
# }
def _http_request(url,payload,is_put=False):
headers = {"Content-type": "application/json" }
authinfo = urllib2.HTTPBasicAuthHandler()
authinfo.add_password("API", url, user, passwd )
opener = urllib2.build_opener(authinfo)
req = urllib2.Request(url, payload, headers)
if is_put: req.get_method = lambda: 'PUT'
data = opener.open(req)
return data.read()
def register_device(dev_token, tags):
# dev_token is a string of hex returned from
# registerForRemoteNotificationTypes:
# tags is a list of string based tags
content = {"tags": tags}
url = "%sdevice_tokens/%s" % (base_url, dev_token)
print _http_request(url, json_dumps(content), is_put=True)
There’s nothing magical here. I just found it a bit interesting to have an HTTP base authenticated PUT request to a restful service and figured I’d show how to tie these all together.

Nice snippet, Jeremy. I’m sorry you had trouble finding examples — I know that’s something we can improve on.
You might find httplib a bit easier to work with than urllib2. With httplib.HTTPConnection you can specify the method in the request. Even nicer is httplib2, a third party module, which makes working with HTTP APIs much easier. One word of warning, though; on Python 2.6 there’s some trouble doing SSL connections, so unless you’re willing to hack through it you might want to skip it if you’re on 2.5.
Do let us know if we can do anything to help!
Adam, actually, i should have mentioned. My snippet will work on 2.4 and 2.5. I’m a big fan of httplib2 and plan to paste some code for that soon, as well. Unfortunately, the server I was dealing with is 2.5 so I went with urllib2. Thanks for the pointers, I heartily agree httplib2 is the way to go if it’s an option.