This repository has been archived by the owner on Sep 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
rest_request.py
103 lines (84 loc) · 2.84 KB
/
rest_request.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
import requests
class RestRequest:
"""
A class representing a rest request
Attributes:
uri (str)
method (str)
headers (dict)
body (dict)
delay (float)
Methods:
with_header(key (str), value (str)):
Adds a header and returns RestRequest
with_body(body (dict)):
Adds a body and returns RestRequest
with_delay(delay (float)):
Adds a delay and returns RestRequest
send(timeout (float)):
Composes and sends rest request, returning request response
Usage:
rest_request = (
RestRequest("https://example.com", "POST")
.with_header("Authorization", "jwt_token")
.with_body({"abc": 123})
.with_delay(1.0)
)
rest_request.send(10.0)
"""
def __init__(self, uri: str, method: str):
"""
Parameters:
uri (str): The uri of the rest api
method (str): The type/method of the request (get/post/patch/etc...)
"""
self.uri = uri
self.method = method.casefold()
self.headers = {}
self.body = {}
self.delay = 0.0
def with_header(self, key: str, value: str) -> "RestRequest":
"""
Adds a key/value pair to the header dictionary
Headers are standard rest api request headers
Parameters:
key (str): The key of the header
value (str): The value of the header
Returns:
(RestRequest): The RestRequest instance with_header was called on
"""
self.headers[key] = value
return self
def with_body(self, body: dict) -> "RestRequest":
"""
Adds a dictionary representing request body
Parameters:
body (dict): The dictionary representing request body
Returns:
(RestRequest): The RestRequest instance with_body was called on
"""
self.body = body
return self
def with_delay(self, delay: float) -> "RestRequest":
"""
Adds a delay to the rest request
Parameters:
delay (float): The number of seconds to be delayed
Returns:
(RestRequest): The RestRequest instance with_delay was called on
"""
self.delay = delay
return self
def send(self, timeout: float):
"""
Composes and sends the rest request
Receives any responses from the api and returns that response
Returns:
(Response): An instance of a response object with the response of the rest api
"""
kwargs = {"timeout": timeout}
if self.headers:
kwargs["headers"] = self.headers
if self.body:
kwargs["json"] = self.body
return requests.request(self.method, self.uri, **kwargs)