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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226 | class SpireClient():
"""A lightweight to interact with the Spire API using requests sessions for connection reuse and authenticated calls."""
def __init__(self, host, company, username, password,):
"""
Initialize a SpireClient instance.
Args:
host (str): Spire Server host.
company (str): Spire company.
username (str): Spire user username.
password (str): Spire user password.
"""
self.session = requests.Session()
self.session.auth = (username, password)
self.session.headers.update({
"accept": "application/json",
"content-type": "application/json"
})
self.base_url = f"https://{host}/api/v2/companies/{company}"
try:
response = self.session.get(self.base_url)
if response.text == 'No such company intertes':
raise ValueError(f"No company entries for {company}")
if response.text == 'Unauthorized':
raise ValueError(f"Invalid Authorization")
except ConnectionError as conn_err:
print(f"Connection error occurred for : {conn_err}")
except Timeout as timeout_err:
print(f"Request timed out: {timeout_err}")
except RequestException as req_err:
print(f"General error occurred: {req_err}")
def _get(self, endpoint, params=None):
"""
Send a GET request to the Spire API.
This method constructs the full URL using the provided endpoint,
sends an HTTP GET request with optional query parameters, and returns
the parsed JSON response. Raises an HTTPError if the response contains
an unsuccessful status code.
Args:
endpoint (str): The relative API endpoint (e.g., 'inventory/items/123').
params (dict, optional): A dictionary of query parameters to include
in the request (e.g., {'status': 'active'}). Defaults to None.
Returns:
dict: The JSON-decoded response from the API.
Raises:
requests.exceptions.HTTPError: If the response contains an HTTP error status.
"""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
response = self.session.get(url , params=params)
response.raise_for_status()
return response.json()
def _post(self, endpoint, data=None, json=None):
"""
Send a POST request to the Spire API.
Args:
endpoint (str): The relative API endpoint (e.g., 'sales/orders').
data (dict, optional): Data to send in the body of the request.
json (dict, optional): JSON data to send in the body of the request.
Returns:
dict: A dictionary containing the response status code, URL, content, and headers.
Raises:
requests.exceptions.HTTPError: If the response contains an HTTP error status.
"""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
response = self.session.post(url, data=data, json=json)
response.raise_for_status()
return self._handle_response(response)
def _put(self, endpoint, data=None, json=None):
"""
Send a PUT request to the Spire API.
Args:
endpoint (str): The relative API endpoint (e.g., 'inventory/items/123').
data (dict, optional): Data to send in the body of the request.
json (dict, optional): JSON data to send in the body of the request.
Returns:
dict: The JSON-decoded response from the API.
Raises:
requests.exceptions.HTTPError: If the response contains an HTTP error status.
"""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
response = self.session.put(url, data=data, json=json)
response.raise_for_status()
return response.json()
def _delete(self, endpoint):
"""
Send a DELETE request to the Spire API.
Args:
endpoint (str): The relative API endpoint to delete (e.g., 'inventory/items/123').
Returns:
bool: True if the deletion was successful (status code 200, 202, or 204), False otherwise.
"""
url = f"{self.base_url}/{endpoint.lstrip('/')}"
response = self.session.delete(url)
return response.status_code in (200, 202, 204)
def _handle_response(self, response):
try:
content = response.json()
except ValueError:
content = response.text
return{
"status_code": response.status_code,
"url": response.url,
"content": content,
"headers" : response.headers
}
def _query(
self,
endpoint: str,
resource_cls: Type["APIResource[T]"],
*,
all: bool = False,
limit: int = 1000,
start: int = 0,
query: Optional[str] = None,
filter: Optional[Dict[str, Any]] = None,
sort: Optional[Dict[str, str]] = None,
**extra_params
) -> List["APIResource[T]"]:
"""
Query a list of resources from a Spire API endpoint with support for
pagination, searching, filtering, and multi-level sorting.
Args:
endpoint (str): The API endpoint (e.g., 'sales/orders').
resource_cls (Type[APIResource[T]]): The resource wrapper class (e.g., SalesOrderResource).
all (bool, optional): If True, fetches all available pages of results.
limit (int, optional): Number of results per page (max 1000). Default is 1000.
start (int, optional): Starting offset for pagination. Default is 0.
q (str, optional): Free-text search query.
filter (dict, optional): Dictionary of filter criteria, which will be JSON-encoded.
sort (dict, optional): Dictionary of sorting rules (e.g., {"orderDate": "desc", "orderNo": "asc"}).
**extra_params: Any additional query parameters to pass to the API.
Returns:
List[APIResource[T]]: A list of wrapped resource instances.
"""
collected = []
current_start = start
remaining = limit
while True:
current_limit = min(remaining, 1000)
# Build the query params as a list of tuples to allow repeated keys like 'sort'
params: List[Tuple[str, Any]] = [
("start", current_start),
("limit", current_limit)
]
if query:
params.append(("q", query))
if filter:
model_fields = resource_cls.Model.model_fields.keys()
invalid_fields = [key for key in filter.keys() if key not in model_fields]
if invalid_fields:
raise ValueError(f"Invalid filter field(s): {invalid_fields}. for {resource_cls.Model.__name__} ")
encoded_filter = json.dumps(filter)
params.append(("filter", encoded_filter))
if sort:
for field, direction in sort.items():
prefix = "-" if direction.lower() == "desc" else ""
params.append(("sort", f"{prefix}{field}"))
# Add any additional custom parameters
for k, v in extra_params.items():
params.append((k, v))
response = self._get(endpoint.rstrip("/"), params=params)
items = response.get("records", [])
count = response.get("count", 0)
for item in items:
collected.append(resource_cls.from_json(item, self))
# Exit if:
# - 'all' is False and we reached the requested 'limit'
# - no more items are returned
if not all:
remaining -= len(items)
if remaining <= 0 or len(items) == 0:
break
# Exit if there are no more items available
if (current_start + current_limit) >= count or len(items) == 0:
break
current_start += current_limit
return collected
|