Robots In The Cloud IaaS Production and Design

CloudStack API calls in Python

These are a couple classes I wrote with Kraig Amador, for signing CloudStack API calls, and allowing individual APIs to be called as methods.


#!/ usr/bin/env python
# By: Kelcey Damage, 2012 & Kraig Amador, 2012


api_url = ‘your_stuff_here’
apiKey = ‘your_stuff_here’
secret = ‘your_stuff_here’


import hashlib, hmac, string, base64, urllib
import json, urllib


class SignedAPICall(object):
    def __init__(self, api_url, apiKey, secret):
        self.api_url = api_url
        self.apiKey = apiKey
        self.secret = secret


    def request(self, args):
        args['apiKey'] = self.apiKey


        self.params = []


    def _sort_request(self, args):
        keys = sorted(args.keys())


        for key in keys:
            self.params.append(key + ‘=’ + urllib.quote_plus(args[key]))


    def _create_signature(self):
        self.query = ‘&’.join(self.params)
        digest =


        self.signature = base64.b64encode(digest)


    def _build_post_request(self):
        self.query += ‘&signature=’ + urllib.quote_plus(self.signature)
        self.value = self.api_url + ‘?’ + self.query


class CloudStack(SignedAPICall):
    def __getattr__(self, name):
        def handlerFunction(*args, **kwargs):
            if kwargs:
                return self._make_request(name, kwargs)
            return self._make_request(name, args[0])
        return handlerFunction


    def _http_get(self, url):
        response = urllib.urlopen(url)


    def _make_request(self, command, args):
        args['response'] = ‘json’
        args['command'] = command
        data = self._http_get(self.value)
        # The response is of the format {commandresponse: actual-data}
        key = command.lower() + “response”
        return json.loads(data)[key]




#api = CloudStack(api_url, apiKey, secret)


#request = {‘listall’: ‘true’}
#result = api.listVirtualMachines(request)
#print “count”, result['count']
#print “api url”, api.value