Created
October 19, 2012 13:54
-
-
Save jamesoutterside/3918348 to your computer and use it in GitHub Desktop.
Sample script to uploaded resources via the oerbookmarking.ncl.ac.uk API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
############################ | |
# | |
# bare bones script to upload a dict of resources to oerbookmarking.ncl.ac.uk | |
# | |
# http://oerbookmarking.ncl.ac.uk/api/ | |
# | |
# Developer = [email protected] | |
import urllib2 | |
BASE_CONFIG = {'base_url':'http://oerbookmarking.ncl.ac.uk', | |
'api_key':'<<YOUR_API_KEY>>', | |
'api_username':'<<YOUR_API_USERNAME>>', | |
'api_format':'json', | |
'bookmark_path':'/api/v1/bookmark/' | |
} | |
def upload_resources(): | |
sample_resources = [{'title':'Test title 1','description':'Test description','url':'http://oerbookmarking.ncl.ac.uk'}, | |
{'title':'Test title 2','description':'Test description','url':'http://oerbookmarking.ncl.ac.uk'}, | |
{'title':'Test title 3','description':'Test description','url':'http://oerbookmarking.ncl.ac.uk'}, | |
] | |
for resource in sample_resources: | |
upload(resource) | |
def upload(resource_data): | |
""" | |
Upload a resource via the post API | |
resource_data must contain | |
title | |
description | |
url | |
Note there is no checking here to see if a resource already exists, oerbookmarking uses a unique key of title and username, so | |
if re-uploaded an error will be returned for all entries that already exist. In a more robust script it would be better to check | |
first. If a resource was to be updated the request would need to be a put and the resource_data would need to include the | |
oerbookmarking id. | |
""" | |
api_url = "%(base_url)s%(bookmark_path)s?api_key=%(api_key)s&username=%(api_username)s" % BASE_CONFIG | |
resource_json = '{'\ | |
'"title":"%(title)s",'\ | |
'"description":"%(description)s",'\ | |
'"url":"%(url)s"'\ | |
'}' % resource_data | |
req = urllib2.Request(api_url, resource_json) | |
req.add_header('Content-Type', 'application/json') | |
req.get_method = lambda: 'POST' | |
try: | |
response = urllib2.urlopen(req) | |
print response.read() | |
print response.msg | |
print '* Posted %s' % resource_data['title'] | |
except urllib2.HTTPError as he: | |
print "** HTTPError" | |
print "**",he.getcode() | |
print "**",he.read() | |
except urllib2.URLError as ue: | |
print "** URLError" | |
print "**",ue | |
if __name__ == '__main__': | |
upload_resources() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment