Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 1 | # Copyright (C) 2010 Google Inc. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | """Client for discovery based APIs |
| 16 | |
| 17 | A client library for Google's discovery |
| 18 | based APIs. |
| 19 | """ |
| 20 | |
| 21 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 22 | |
| 23 | |
| 24 | import httplib2 |
| 25 | import re |
| 26 | import simplejson |
| 27 | import urlparse |
| 28 | import uritemplate |
| 29 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 30 | |
Joe Gregorio | 41cf797 | 2010-08-18 15:21:06 -0400 | [diff] [blame] | 31 | class HttpError(Exception): |
| 32 | pass |
| 33 | |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame^] | 34 | DISCOVERY_URI = 'http://www.googleapis.com/discovery/0.1/describe\ |
| 35 | {?api,apiVersion}' |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 36 | |
| 37 | |
| 38 | def key2method(key): |
| 39 | """ |
| 40 | max-results -> MaxResults |
| 41 | """ |
| 42 | result = [] |
| 43 | key = list(key) |
| 44 | newWord = True |
| 45 | if not key[0].isalpha(): |
| 46 | result.append('X') |
| 47 | newWord = False |
| 48 | for c in key: |
| 49 | if c.isalnum(): |
| 50 | if newWord: |
| 51 | result.append(c.upper()) |
| 52 | newWord = False |
| 53 | else: |
| 54 | result.append(c.lower()) |
| 55 | else: |
| 56 | newWord = True |
| 57 | |
| 58 | return ''.join(result) |
| 59 | |
| 60 | |
| 61 | def key2param(key): |
| 62 | """ |
| 63 | max-results -> max_results |
| 64 | """ |
| 65 | result = [] |
| 66 | key = list(key) |
| 67 | if not key[0].isalpha(): |
| 68 | result.append('x') |
| 69 | for c in key: |
| 70 | if c.isalnum(): |
| 71 | result.append(c) |
| 72 | else: |
| 73 | result.append('_') |
| 74 | |
| 75 | return ''.join(result) |
| 76 | |
| 77 | |
| 78 | class JsonModel(object): |
Joe Gregorio | 41cf797 | 2010-08-18 15:21:06 -0400 | [diff] [blame] | 79 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 80 | def request(self, headers, params): |
| 81 | model = params.get('body', None) |
| 82 | query = '?alt=json&prettyprint=true' |
| 83 | headers['Accept'] = 'application/json' |
| 84 | if model == None: |
| 85 | return (headers, params, query, None) |
| 86 | else: |
Joe Gregorio | 41cf797 | 2010-08-18 15:21:06 -0400 | [diff] [blame] | 87 | model = {'data': model} |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 88 | headers['Content-Type'] = 'application/json' |
| 89 | del params['body'] |
| 90 | return (headers, params, query, simplejson.dumps(model)) |
| 91 | |
| 92 | def response(self, resp, content): |
Joe Gregorio | 41cf797 | 2010-08-18 15:21:06 -0400 | [diff] [blame] | 93 | # Error handling is TBD, for example, do we retry |
| 94 | # for some operation/error combinations? |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 95 | if resp.status < 300: |
| 96 | return simplejson.loads(content)['data'] |
| 97 | else: |
| 98 | if resp['content-type'] != 'application/json': |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame^] | 99 | raise HttpError('%d %s' % (resp.status, resp.reason)) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 100 | else: |
| 101 | raise HttpError(simplejson.loads(content)['error']) |
| 102 | |
| 103 | |
| 104 | def build(service, version, http=httplib2.Http(), |
Joe Gregorio | 41cf797 | 2010-08-18 15:21:06 -0400 | [diff] [blame] | 105 | discoveryServiceUrl=DISCOVERY_URI, auth=None, model=JsonModel()): |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 106 | params = { |
| 107 | 'api': service, |
| 108 | 'apiVersion': version |
| 109 | } |
| 110 | resp, content = http.request(uritemplate.expand(discoveryServiceUrl, params)) |
| 111 | d = simplejson.loads(content) |
| 112 | service = d['data'][service][version] |
| 113 | base = service['baseUrl'] |
| 114 | resources = service['resources'] |
| 115 | |
| 116 | class Service(object): |
| 117 | """Top level interface for a service""" |
| 118 | |
| 119 | def __init__(self, http=http): |
| 120 | self._http = http |
| 121 | self._baseUrl = base |
| 122 | self._model = model |
| 123 | |
| 124 | def createMethod(theclass, methodName, methodDesc): |
Joe Gregorio | 41cf797 | 2010-08-18 15:21:06 -0400 | [diff] [blame] | 125 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 126 | def method(self, **kwargs): |
| 127 | return createResource(self._http, self._baseUrl, self._model, |
| 128 | methodName, methodDesc) |
| 129 | |
| 130 | setattr(method, '__doc__', 'A description of how to use this function') |
| 131 | setattr(theclass, methodName, method) |
| 132 | |
| 133 | for methodName, methodDesc in resources.iteritems(): |
| 134 | createMethod(Service, methodName, methodDesc) |
| 135 | return Service() |
| 136 | |
| 137 | |
| 138 | def createResource(http, baseUrl, model, resourceName, resourceDesc): |
| 139 | |
| 140 | class Resource(object): |
| 141 | """A class for interacting with a resource.""" |
| 142 | |
| 143 | def __init__(self): |
| 144 | self._http = http |
| 145 | self._baseUrl = baseUrl |
| 146 | self._model = model |
| 147 | |
| 148 | def createMethod(theclass, methodName, methodDesc): |
| 149 | pathUrl = methodDesc['pathUrl'] |
| 150 | pathUrl = re.sub(r'\{', r'{+', pathUrl) |
| 151 | httpMethod = methodDesc['httpMethod'] |
| 152 | args = methodDesc['parameters'].keys() |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame^] | 153 | required = [arg for arg in args if methodDesc['parameters'][arg].get('required', True)] |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 154 | if httpMethod in ['PUT', 'POST']: |
| 155 | args.append('body') |
| 156 | argmap = dict([(key2param(key), key) for key in args]) |
| 157 | |
| 158 | def method(self, **kwargs): |
| 159 | for name in kwargs.iterkeys(): |
| 160 | if name not in argmap: |
| 161 | raise TypeError('Got an unexpected keyword argument "%s"' % name) |
| 162 | params = dict( |
| 163 | [(argmap[key], value) for key, value in kwargs.iteritems()] |
| 164 | ) |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame^] | 165 | for name in required: |
| 166 | if name not in kwargs: |
| 167 | raise TypeError('Missing required parameter "%s"' % name) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 168 | headers = {} |
| 169 | headers, params, query, body = self._model.request(headers, params) |
| 170 | |
| 171 | url = urlparse.urljoin(self._baseUrl, |
| 172 | uritemplate.expand(pathUrl, params) + query) |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame^] | 173 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 174 | return self._model.response(*self._http.request( |
| 175 | url, method=httpMethod, headers=headers, body=body)) |
| 176 | |
| 177 | docs = ['A description of how to use this function\n\n'] |
| 178 | for arg in argmap.iterkeys(): |
| 179 | docs.append('%s - A parameter\n' % arg) |
| 180 | |
| 181 | setattr(method, '__doc__', ''.join(docs)) |
| 182 | setattr(theclass, methodName, method) |
| 183 | |
| 184 | for methodName, methodDesc in resourceDesc['methods'].iteritems(): |
| 185 | createMethod(Resource, methodName, methodDesc) |
| 186 | |
| 187 | return Resource() |