-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathrestapi.py
189 lines (145 loc) · 5.03 KB
/
restapi.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# -*- encoding: utf-8 -*-
#
# THE RESTAPI GENERIC CLIENT CONSUMER
# Author: Sergio Berlotto <sergio.berlotto@gmail.com>
#
# Project died, so updates made by me: Joshua M Smith <saether@gmail.com>
import requests as req
import ujson
class EndpointError(AttributeError):
def __init__(self, endpoint):
message = "Call Error: endpoint '{}' not allowed.".format(
endpoint
)
super(EndpointError, self).__init__(message)
class ApiError(Exception):
def __init__(self, method, route, status_code, server_message):
message = """{method} {route} Return code: {status_code}\n
Server message:{server_message}""".format(**locals())
super(ApiError, self).__init__(message)
class Client(object):
def __init__(self, root_path):
self.root_path = root_path
self.known_endpoints = []
def __getattribute__(self, attr):
try:
return super(Client, self).__getattribute__(attr)
except AttributeError:
return Endpoint(
self.root_path,
attr
)
class Endpoint(object):
def __init__(self, root_path, endpoint):
self.endpoint = endpoint
self.root_path = root_path
def _url(self, path, *args):
url = "{}/{}/".format(self.root_path, path)
if args:
url += "/".join([str(a) for a in args])
return url
def _headers(self, others={}):
"""Return the default headers and others as necessary"""
headers = {
'Content-Type': 'application/json'
}
for p in others.keys():
headers[p] = others[p]
return headers
def _params(self, others={}):
params = {}
for p in others.keys():
params[p] = others[p]
return params
def _formatreturn(self, resp):
try:
r = resp.json()
except ValueError:
#When the return is not a JSON
r = resp.text
return r
def post(self, user_data, the_id=None, user_params={}, user_headers={}):
strjsondata = ujson.dumps(user_data, ensure_ascii=False)
if the_id:
url = self._url(self.endpoint, the_id)
else:
url = self._url(self.endpoint)
resp = req.post(
url,
data=strjsondata,
headers=self._headers(user_headers),
params=self._params(user_params),
stream=False
)
if resp.status_code != 201:
raise ApiError(
"GET",
self.endpoint,
resp.status_code,
resp.text)
else:
return self._formatreturn(resp)
def put(self, the_id, user_data, user_params={}, user_headers={}):
strjsondata = ujson.dumps(user_data, ensure_ascii=False)
resp = req.put(
self._url(self.endpoint, the_id),
data=strjsondata,
headers=self._headers(user_headers),
params=self._params(user_params)
)
if resp.status_code != 200:
raise ApiError(
"GET",
self.endpoint,
resp.status_code,
resp.text)
else:
return self._formatreturn(resp)
def patch(self, the_id, user_data, user_params={}, user_headers={}):
strjsondata = ujson.dumps(user_data, ensure_ascii=False)
resp = req.patch(
self._url(self.endpoint, the_id),
data=strjsondata,
headers=self._headers(user_headers),
params=self._params(user_params)
)
if resp.status_code != 200:
raise ApiError(
"GET",
self.endpoint,
resp.status_code,
resp.text)
else:
return self._formatreturn(resp)
def get(self, the_id=None, level=None, user_params={}, user_headers={}):
if the_id:
url = self._url(self.endpoint, the_id)
else:
url = self._url(self.endpoint)
resp = req.get(
url,
headers=self._headers(user_headers),
params=self._params(user_params)
)
if resp.status_code != 200:
raise ApiError(
"GET",
self.endpoint,
resp.status_code,
resp.text)
else:
return self._formatreturn(resp)
def delete(self, level=None, user_params={}, user_headers={}):
resp = req.delete(
self._url(self.endpoint),
headers=self._headers(user_headers),
params=self._params(user_params)
)
if resp.status_code != 200:
raise ApiError(
"DELETE",
self.endpoint,
resp.status_code,
resp.text)
else:
return self._formatreturn(resp)