Python example of using API

The following is an example Python program that illustrates use of the API.

Python example

You can copy the following code to a file, and run it where Python is installed on your machine:

python <filename.py>

You will need to fill in your specific environment information in this python file, such as Metric Insights URl, and API credentials

# python <file.py>

import urllib
import urllib2
import json

#########################################
def httpRequestToAPI(path, data, headers):
# GET request has url, data is empty
# POST request has url, data
    urlFinal = urlMain + '/api/' + path
    print 'Request to ' + urlFinal
    #print 'Headers: ' + headers
    if data != None :
        print 'Body: ' + data
    req = urllib2.Request(urlFinal, data, headers)
    try:
       response = urllib2.urlopen(req)
    except urllib2.URLError as e:
        if hasattr(e, 'reason'):
            print 'We failed to reach a server.'
            print 'Reason: ', e.reason
        elif hasattr(e, 'code'):
            print 'The server couldn\'t fulfill the request.'
            print 'Error code: ', e.code
    else:
        # everything is fine


# return the response data
        result = response.read()
        return result

#########################################

# call get token
# TODO fill in with your Metric Insights server:
urlMain = "https://localhost"
#
# TODO fill in with your API credentials
# JSON
values = {'application_id' : '<fill in>',
          'application_key' : '<fill in>',
          'user' : '<fill in>' }

# XML
#values = '<?xml version="1.0" encoding="UTF-8" ?><request><application_id>(fill in)</application_id><application_key>(fill in)</application_key><user>(fill in)</user></request>'

# JSON
data = json.dumps(values)
# Form data
#data = urllib.urlencode(values)
# XML
#data = values

# JSON
headers = { 'Accept' : 'application/json', 'Content-Type' : 'application/json' }
# Form
#headers = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded' }
# XML
#headers = { 'Accept' : 'application/xml', 'Content-Type' : 'application/xml' }

# returns:
# {"token":"N5WDX010V8jrEh8cNXMQLvlnFGLa9J29qv3msWhVsYzHdi1wbX","expires":"2015-02-19 12:05:25"}
#headers = { 'Accept' : 'application/xml' }
# returns:
# <?xml version="1.0" encoding="utf-8"?>
# <response><token>srhbCkGavdV9I1TNMiO5e33clW79L9BH6WNsRZSIUMmXAiGYGm</token><expires>2015-02-19 12:06:06</expires></response>


# Get Token
result = httpRequestToAPI("get_token", data, headers);
print 'result:'
print result

# get returned token value
resultJson = json.loads(result)
print resultJson
token = resultJson["token"]
print 'Token to use: ' + token


# Get Dimensions
headers = { 'Accept' : 'application/json', 'Token' : token }
result = httpRequestToAPI("dimension", None, headers);
print 'result:'
print result

0 Comments

Add your comment

E-Mail me when someone replies to this comment