Posts Tagged ‘Token’

WeoGeo API: Python Examples, Part 3

Tuesday, January 19th, 2010

The Developer Documentation for WeoGeo’s API provides examples using curl.  In this blog series, I’m providing similar examples using Python.  In WeoGeo API: Python Examples, Part 1, I showed how to invoke the “GET Dataset as WeoFile” API from Python using urllib.  In Part 2, I showed the same GET Dataset request using httplib.  This time, we’re going to generate Dataset Tokens, which will require use of POST and https.

First, a little background: Dataset Tokens are Universally Unique Identifiers.  There is one Dataset Token for each Dataset Listing in your WeoGeo Library.  If your Dataset is also listed on the WeoGeo Market, the same Token is used there.  Although the WeoApp can create Dataset Tokens for you when it creates a Dataset WeoFile, sometimes developers find it is useful to create a number of them in advance.

The Developer API Documentation shows that the curl request for Dataset Token generation is:

curl -u ${api_key}: -X POST https://${hostname}/datasets/tokens?count=2

There are three things of note here:

  1. For authentication, only the API Key is used
  2. The HTTP method is POST where previous examples have used GET
  3. This API uses https rather than http

Here is a bare-bones Python example demonstrating the same API call:

import base64
import string
import httplib, urllib

# Programmer defined variables
usern = "your API key goes here"
passw = "" # Null string when API Key is used
library = "YourLibraryName" # the %s part of %s.weogeo.com
n_tokens = 2
# No more programmer changes

# set up the authentication string
auth = 'Basic ' + string.strip(base64.encodestring(usern + ':' + passw))

# Generate Tokens Curl Example (POST via HTTPS)
# curl -u #{api_key}: -X POST https://#{hostname}/datasets/tokens?count=2

# create the header with the authentication string
headers = {
 "Content-Type": "application/xml" ,
 "Authorization": auth,
 }

# set parameters for the request
params =  urllib.urlencode( { 'count':n_tokens } )

# create the connection
conn = httplib.HTTPSConnection("%s.weogeo.com" % library)

# Construct the request with headers amd add paramters to the URI
conn.request("POST","/datasets/tokens?%s" % params, "", headers)

# call the URI close the connection
response = conn.getresponse()

#check status of result
print response.status, response.reason

#check status of result
data = response.read()

# close the connection
conn.close()

# output the results
print data

For the three things of interest noted above:

  1. API Key is set on line 5 and used on lines 11, 17, and 28
  2. Line 28 sets the HTTP Request Method to POST
  3. Line 25 uses httplib.HTTPSConnection (previous examples used httplib.HTTPConnection)

That’s it!  Next time, I plan to show the PUT method as used in the Update Dataset API.