This repository has been archived by the owner on Apr 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest_api.py
executable file
·145 lines (115 loc) · 4.75 KB
/
rest_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
#!/usr/bin/python
"""Python client library for VMRay REST API"""
import base64
import datetime
import os.path
import urlparse
import requests
class VMRayRESTAPIError(Exception):
"""Exception class that is used when API returns an error"""
def __init__(self, *args, **kwargs):
self.status_code = kwargs.pop("status_code", None)
Exception.__init__(self, *args, **kwargs)
def handle_rest_api_result(result):
"""Handle result of API request (check for errors)"""
if (result.status_code < 200) or (result.status_code > 299):
try:
json_result = result.json()
except ValueError:
raise VMRayRESTAPIError(
"API returned error %u: %s" % (result.status_code,
result.text),
status_code=result.status_code)
raise VMRayRESTAPIError(json_result.get("error_msg", "Unknown error"),
status_code=result.status_code)
class VMRayRESTAPI(object):
"""VMRay REST API class"""
def __init__(self, server, api_key, verify_cert=True):
# split server URL into components
url_desc = urlparse.urlsplit(server)
# assume HTTPS if no scheme is specified
if url_desc.scheme == "":
server = "https://" + server
# save variables
self.server = server
self.api_key = api_key
self.verify_cert = verify_cert
def call(self, http_method, api_path, params=None, raw_data=False):
"""Call VMRay REST API"""
# get function of requests package
requests_func = getattr(requests, http_method.lower())
# parse parameters
req_params = {}
file_params = {}
if params is not None:
for key, value in params.iteritems():
if isinstance(value, (datetime.date,
datetime.datetime,
float,
int)):
req_params[key] = unicode(value)
elif isinstance(value, basestring):
req_params[key] = unicode(value)
elif isinstance(value, file):
filename = os.path.split(value.name)[1]
# For the following block refer to DEV-1820
try:
filename.decode("ASCII")
except (UnicodeDecodeError, UnicodeEncodeError):
b64_key = key + "name_b64enc"
byte_value = filename.encode("utf-8")
b64_value = base64.b64encode(byte_value)
filename = "@param=%s" % b64_key
req_params[b64_key] = b64_value
file_params[key] = (filename, value,
"application/octet-stream")
else:
raise VMRayRESTAPIError(
"Parameter \"%s\" has unknown type" % (key))
# construct request
if file_params:
files = file_params
else:
files = None
# we need to adjust some stuff for POST requests
if http_method.lower() == "post":
req_data = req_params
req_params = None
else:
req_data = None
# do request
result = requests_func(
self.server + api_path, data=req_data,
params=req_params,
headers={"Authorization": "api_key " + self.api_key},
files=files, verify=self.verify_cert,
stream=raw_data)
handle_rest_api_result(result)
if raw_data:
return result.raw
# parse result
try:
json_result = result.json()
except ValueError:
raise ValueError("API returned invalid JSON: %s" % (result.text))
# if there are no cached elements then return the data
if "continuation_id" not in json_result:
return json_result.get("data", None)
data = json_result["data"]
# get cached results
while "continuation_id" in json_result:
# send request to server
result = requests.get(
"%s/rest/continuation/%u" % (self.server,
json_result["continuation_id"]),
headers={"Authorization": "api_key " + self.api_key},
verify=self.verify_cert)
handle_rest_api_result(result)
# parse result
try:
json_result = result.json()
except ValueError:
raise ValueError(
"API returned invalid JSON: %s" % (result.text))
data.extend(json_result["data"])
return data