-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.py
154 lines (132 loc) · 5.73 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""Api and Utilities
This file is part of pyrest.
pyrest is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
pyrest is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pyrest. If not, see <http://www.gnu.org/licenses/>.
"""
import httplib2
import urllib
class Api():
"""Api Object"""
base_url = '' # Prefixed before every URL. EX: api.website.url/v2
endpoints = None # Dictionary holding all the options
request_handler = None # httplib2-esque
# This is how we handle our different types of requests...
_method = {
'get': 'GET',
'post': 'POST',
'put': 'PUT',
'delete': 'DELETE',
'head': 'HEAD'
}
def __init__(self, base_url, username='', password='', oauth_client=None):
"""Grabs everything we need to connect to a REST API
base_url: 'http://google.com' -- no trailing slashes
username = '[email protected]'
password = 'helloworld'
oauth_client = oauth2.client()
"""
self.base_url = base_url
self.endpoints = {}
if oauth_client:
self.request_handler = oauth_client
else:
self.request_handler = Api._httplib2_init(username, password)
def update_endpoints(self, endpoints):
""""
Adds to the endpoints collection
endpoints = {
'get_users': 'users',
'classes': 'crazyURL/withExtraStuff',
'get_user': 'user/%(id)s' # requires url_data
'get_me': 'user/3' # Don't be afraid to hard code!
}
"""
self.endpoints.update(endpoints)
def clear_endpoints(self):
"""Clears all stored endpoints"""
self.endpoints = {}
def get(self, endpoint, url_data=None, parameters=None):
"""Returns the response and body for a get request
endpoints = 'users' # resource to access
url_data = {}, () # Used to modularize endpoints, see __init__
parameters = {}, ((),()) # URL parameters: google.com?q=a&f=b
"""
return self.request_handler.request(
self._url(endpoint, url_data, parameters),
method=Api._method['get'],
)
def post(self, endpoint, data, url_data=None, parameters=None):
"""Returns the response and body for a post request
endpoints = 'users' # resource to access
data = {'username': 'blah, 'password': blah} # POST body
url_data = {}, () # Used to modularize endpoints, see __init__
parameters = {}, ((),()) # URL paramters, ex: google.com?q=a&f=b
"""
return self.request_handler.request(
self._url(endpoint, url_data, parameters),
method=Api._method['post'],
body=urllib.urlencode(data)
)
def put(self, endpoint, data, url_data=None, parameters=None):
"""Returns the response and body for a put request
endpoints = 'users' # resource to access
data = {'username': 'blah, 'password': blah} # PUT body
url_data = {}, () # Used to modularize endpoints, see __init__
parameters = {}, ((),()) # URL paramters, ex: google.com?q=a&f=b
"""
return self.request_handler.request(
self._url(endpoint, url_data, parameters),
method=Api._method['put'],
body=urllib.urlencode(data)
)
def delete(self, endpoint, data, url_data=None, parameters=None):
"""Returns the response and body for a delete request
endpoints = 'users' # resource to access
data = {'username': 'blah, 'password': blah} # DELETE body
url_data = {}, () # Used to modularize endpoints, see __init__
parameters = {}, ((),()) # URL paramters, ex: google.com?q=a&f=b
"""
return self.request_handler.request(
self._url(endpoint, url_data, parameters),
method=Api._method['delete'],
body=urllib.urlencode(data)
)
def head(self, endpoint, url_data=None, parameters=None):
"""Returns the response and body for a head request
endpoints = 'users' # resource to access
url_data = {}, () # Used to modularize endpoints, see __init__
parameters = {}, ((),()) # URL paramters, ex: google.com?q=a&f=b
"""
return self.request_handler.request(
self._url(endpoint, url_data, parameters),
method=Api._method['head']
)
def _url(self, endpoint, url_data=None, parameters=None):
"""Generate URL on the modularized endpoints and url parameters"""
try:
url = '%s/%s' % (self.base_url, self.endpoints[endpoint])
except KeyError:
raise EndPointDoesNotExist(endpoint)
if url_data:
url = url % url_data
if parameters:
# url = url?key=value&key=value&key=value...
url = '%s?%s' % (url, urllib.urlencode(parameters, True))
return url
@staticmethod
def _httplib2_init(username, password):
"""Used to instantiate a regular HTTP request object"""
obj = httplib2.Http()
if username and password:
obj.add_credentials(username, password)
return obj
class EndPointDoesNotExist(Exception):
"""Raised when the endpoint could not be found"""
pass