|
| 1 | +""" |
| 2 | +UBER API Client Library |
| 3 | +
|
| 4 | +Usage: |
| 5 | + >>> from uber import Api |
| 6 | + >>> api = Api.Uber(**credentials) |
| 7 | + >>> api.get_profile() |
| 8 | +""" |
| 9 | + |
| 10 | +__all__ = ['Uber'] |
| 11 | + |
| 12 | +import json |
| 13 | +import urllib |
| 14 | +import requests |
| 15 | +from uber.config import BASE_URL |
| 16 | + |
| 17 | + |
| 18 | +class UberApiError(Exception): |
| 19 | + '''Base class for Uber API errors''' |
| 20 | + |
| 21 | + @property |
| 22 | + def message(self): |
| 23 | + '''Returns the first argument used to construct this error.''' |
| 24 | + return self.args[0] |
| 25 | + |
| 26 | + |
| 27 | +class Uber(object): |
| 28 | + """ |
| 29 | + instance of Uber API |
| 30 | + """ |
| 31 | + def __init__(self, **credentials): |
| 32 | + self.url = BASE_URL |
| 33 | + self.server_token = credentials.get('SERVER_TOKEN') |
| 34 | + self.user_token = credentials.get('user_token') |
| 35 | + print self.url |
| 36 | + |
| 37 | + def authenticate(self, bearer=False): |
| 38 | + ''' |
| 39 | + returns authentication header |
| 40 | + ''' |
| 41 | + if bearer: |
| 42 | + request_headers = dict(Authorization='Bearer {}'.format( |
| 43 | + self.user_token)) |
| 44 | + else: |
| 45 | + request_headers = dict(Authorization='Token {}'.format( |
| 46 | + self.server_token)) |
| 47 | + return request_headers |
| 48 | + |
| 49 | + def validate_response(self, resp): |
| 50 | + ''' |
| 51 | + validates response from Uber API. |
| 52 | + No action if status code is 200 |
| 53 | + Else, raise custom exception |
| 54 | + ''' |
| 55 | + msg = "Unexpected response - HTTP:{} - payload: {}".format( |
| 56 | + resp.status_code, resp.content) |
| 57 | + if resp.status_code not in (200, 202): |
| 58 | + # 202 for Request |
| 59 | + raise UberApiError(msg) |
| 60 | + |
| 61 | + def get_products(self, latitude, longitude): |
| 62 | + ''' |
| 63 | + returns information about the Uber products offered at a |
| 64 | + given location |
| 65 | + ''' |
| 66 | + url = self.url + '/products' |
| 67 | + params = dict(latitude=latitude, longitude=longitude) |
| 68 | + resp = requests.get(url, data=params, headers=self.authenticate()) |
| 69 | + self.validate_response(resp) |
| 70 | + return json.loads(resp.content) |
| 71 | + |
| 72 | + def get_product(self, product_id): |
| 73 | + ''' |
| 74 | + return individual product details |
| 75 | + ''' |
| 76 | + url = self.url + '/products/{}'.format(str(product_id)) |
| 77 | + params = dict(product_id=product_id) |
| 78 | + resp = requests.get(url, data=params, headers=self.authenticate()) |
| 79 | + self.validate_response(resp) |
| 80 | + return json.loads(resp.content) |
| 81 | + |
| 82 | + def get_price_estimate(self, start, end): |
| 83 | + ''' |
| 84 | + returns an estimated price range for each product |
| 85 | + offered at a given location |
| 86 | +
|
| 87 | + @param start <dict> contains keys: `latitude` and `longitude` |
| 88 | + @param end <dict> contains keys: `latitude` and `longitude` |
| 89 | + ''' |
| 90 | + try: |
| 91 | + assert isinstance(start, dict) |
| 92 | + assert isinstance(end, dict) |
| 93 | + assert 'latitude' in start |
| 94 | + assert 'longitude' in start |
| 95 | + assert 'latitude' in end |
| 96 | + assert 'longitude' in end |
| 97 | + except AssertionError: |
| 98 | + raise UberApiError("Incorrect request parameters - " |
| 99 | + "start: {} - end: {}".format(start, end)) |
| 100 | + url = self.url + '/estimates/price' |
| 101 | + params = dict(start_latitude=start.get('latitude'), |
| 102 | + start_longitude=start.get('longitude'), |
| 103 | + end_latitude=end.get('latitude'), |
| 104 | + end_longitude=end.get('longitude')) |
| 105 | + url = url + '?%s' % urllib.urlencode(params) |
| 106 | + resp = requests.get(url, headers=self.authenticate()) |
| 107 | + self.validate_response(resp) |
| 108 | + return json.loads(resp.content) |
| 109 | + |
| 110 | + def get_time_estimate(self, start, customer_id=None, product_id=None): |
| 111 | + ''' |
| 112 | + returns ETAs for all products offered at a given location |
| 113 | +
|
| 114 | + @param start <dict> contains keys: `latitude` and `longitude` |
| 115 | + @param customer_id <str> Optional |
| 116 | + @param product_id <str> Optional |
| 117 | + ''' |
| 118 | + try: |
| 119 | + assert isinstance(start, dict) |
| 120 | + assert 'latitude' in start |
| 121 | + assert 'longitude' in start |
| 122 | + except AssertionError: |
| 123 | + raise UberApiError("Incorrect request parameters - " |
| 124 | + "start: {} ".format(start)) |
| 125 | + url = self.url + '/estimates/time' |
| 126 | + params = dict(start_latitude=start.get('latitude'), |
| 127 | + start_longitude=start.get('longitude')) |
| 128 | + if customer_id: |
| 129 | + params['customer_uuid'] = str(customer_id) |
| 130 | + if product_id: |
| 131 | + params['product_id'] = str(product_id) |
| 132 | + url = url + '?%s' % urllib.urlencode(params) |
| 133 | + resp = requests.get(url, headers=self.authenticate()) |
| 134 | + self.validate_response(resp) |
| 135 | + return json.loads(resp.content) |
| 136 | + |
| 137 | + def get_promotions(self, start={}, end={}): |
| 138 | + ''' |
| 139 | + returns information about the promotion that will be |
| 140 | + available to a new user based on their activity's location |
| 141 | +
|
| 142 | + @param start <dict> contains keys: `latitude` and `longitude` |
| 143 | + @param end <dict> contains keys: `latitude` and `longitude` |
| 144 | +
|
| 145 | + At least one valid set of coordinates is required. |
| 146 | + ''' |
| 147 | + try: |
| 148 | + assert (isinstance(start.get('latitude'), float) and |
| 149 | + isinstance(start.get('longitude'), float)) or\ |
| 150 | + (isinstance(end.get('latitude'), float) and |
| 151 | + isinstance(end.get('longitude'), float)) |
| 152 | + except AssertionError: |
| 153 | + raise UberApiError("Incorrect parameters - " |
| 154 | + "start: {} - end: {}".format(start, end)) |
| 155 | + url = self.url + '/promotions' |
| 156 | + |
| 157 | + params = dict(start_latitude=start.get('latitude'), |
| 158 | + start_longitude=start.get('longitude'), |
| 159 | + end_latitude=end.get('latitude'), |
| 160 | + end_longitude=end.get('longitude')) |
| 161 | + url = url + '?%s' % urllib.urlencode(params) |
| 162 | + resp = requests.get(url, headers=self.authenticate()) |
| 163 | + self.validate_response(resp) |
| 164 | + return json.loads(resp.content) |
| 165 | + |
| 166 | + def get_profile(self,): |
| 167 | + ''' |
| 168 | + returns information about the Uber user that has |
| 169 | + authorized with the application |
| 170 | + ''' |
| 171 | + try: |
| 172 | + url = self.url + '/me' |
| 173 | + resp = requests.get(url, headers=self.authenticate(bearer=True)) |
| 174 | + self.validate_response(resp) |
| 175 | + return json.loads(resp.content) |
| 176 | + except Exception, err: |
| 177 | + error = 'cannot get profile - {}'.format(str(err)) |
| 178 | + raise UberApiError(error) |
| 179 | + |
| 180 | + def request(self, product_id, start, end): |
| 181 | + ''' |
| 182 | + allows a ride to be requested on behalf of an Uber user |
| 183 | + given their desired product, start, and end locations |
| 184 | +
|
| 185 | + @param product_id <str> product requested |
| 186 | + @param start <dict> contains keys: `latitude` and `longitude` |
| 187 | + @param end <dict> contains keys: `latitude` and `longitude` |
| 188 | + ''' |
| 189 | + try: |
| 190 | + assert isinstance(start, dict) |
| 191 | + assert isinstance(end, dict) |
| 192 | + assert 'latitude' in start |
| 193 | + assert 'longitude' in start |
| 194 | + assert 'latitude' in end |
| 195 | + assert 'longitude' in end |
| 196 | + |
| 197 | + url = self.url + '/requests' |
| 198 | + params = dict(product_id=str(product_id), |
| 199 | + start_latitude=start.get('latitude'), |
| 200 | + start_longitude=start.get('longitude'), |
| 201 | + end_latitude=end.get('latitude'), |
| 202 | + end_longitude=end.get('longitude')) |
| 203 | + request_headers = self.authenticate(bearer=True) |
| 204 | + request_headers['Content-Type'] = 'application/json' |
| 205 | + resp = requests.post(url, data=json.dumps(params), |
| 206 | + headers=request_headers) |
| 207 | + self.validate_response(resp) |
| 208 | + return json.loads(resp.content) |
| 209 | + |
| 210 | + except AssertionError: |
| 211 | + raise UberApiError("Incorrect request parameters - " |
| 212 | + "start: {} - end: {}".format(start, end)) |
| 213 | + |
| 214 | + except Exception, err: |
| 215 | + error = 'Uber.request() fail - {}'.format(str(err)) |
| 216 | + raise UberApiError(error) |
| 217 | + |
| 218 | + def request_details(self, request_id): |
| 219 | + ''' |
| 220 | + Get the real time status of an ongoing trip that was |
| 221 | + created using the Ride Request endpoint |
| 222 | + ''' |
| 223 | + try: |
| 224 | + url = self.url + '/requests/{}'.format(str(request_id).strip()) |
| 225 | + resp = requests.get(url, headers=self.authenticate(bearer=True)) |
| 226 | + self.validate_response(resp) |
| 227 | + return json.loads(resp.content) |
| 228 | + |
| 229 | + except Exception, err: |
| 230 | + error = 'Uber.request_details() fail - {}'.format(str(err)) |
| 231 | + raise UberApiError(error) |
| 232 | + |
| 233 | + def sandbox_modify_request(self, request_id, new_status): |
| 234 | + ''' |
| 235 | + modifies the status of an ongoing sandbox Request |
| 236 | +
|
| 237 | + @param request_id <str> id of the request to modify |
| 238 | + @param status <str> status to modify to |
| 239 | + ( see config for all possible values for `status` ) |
| 240 | + ''' |
| 241 | + try: |
| 242 | + url = self.url + '/sandbox/requests/{}'.format(request_id) |
| 243 | + status_update = dict(status=new_status) |
| 244 | + params = json.dumps(status_update) |
| 245 | + request_headers = self.authenticate(bearer=True) |
| 246 | + request_headers['Content-Type'] = 'application/json' |
| 247 | + resp = requests.put(url, data=params, headers=request_headers) |
| 248 | + if resp.status_code == 204: |
| 249 | + return True |
| 250 | + else: |
| 251 | + return False |
| 252 | + except Exception, err: |
| 253 | + error = 'cannot update request status - {}'.format(str(err)) |
| 254 | + raise UberApiError(error) |
0 commit comments