endzoneapi 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- endzoneapi/__init__.py +25 -0
- endzoneapi/_core.py +307 -0
- endzoneapi/_version.py +1 -0
- endzoneapi/client.py +880 -0
- endzoneapi/py.typed +0 -0
- endzoneapi-0.1.0.dist-info/METADATA +204 -0
- endzoneapi-0.1.0.dist-info/RECORD +9 -0
- endzoneapi-0.1.0.dist-info/WHEEL +4 -0
- endzoneapi-0.1.0.dist-info/licenses/LICENSE +21 -0
endzoneapi/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""EndzoneAPI: Python client for the EndzoneAPI NFL data API."""
|
|
2
|
+
from ._core import (
|
|
3
|
+
APIConnectionError,
|
|
4
|
+
APIError,
|
|
5
|
+
AuthError,
|
|
6
|
+
InsufficientCreditsError,
|
|
7
|
+
NotFoundError,
|
|
8
|
+
RateLimitError,
|
|
9
|
+
to_dataframe,
|
|
10
|
+
)
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .client import TOOLS, Client
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"APIConnectionError",
|
|
16
|
+
"APIError",
|
|
17
|
+
"AuthError",
|
|
18
|
+
"Client",
|
|
19
|
+
"InsufficientCreditsError",
|
|
20
|
+
"NotFoundError",
|
|
21
|
+
"RateLimitError",
|
|
22
|
+
"TOOLS",
|
|
23
|
+
"__version__",
|
|
24
|
+
"to_dataframe",
|
|
25
|
+
]
|
endzoneapi/_core.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Shared runtime for the EndzoneAPI Python client.
|
|
2
|
+
|
|
3
|
+
Standard library only. The generated methods live in client.py and call
|
|
4
|
+
``Client._call``; everything else (auth, retries, errors, credits headers) is here.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import socket
|
|
11
|
+
import ssl
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
|
16
|
+
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
|
|
19
|
+
BRAND = "EndzoneAPI"
|
|
20
|
+
ENV_VAR = "ENDZONEAPI_API_KEY"
|
|
21
|
+
DEFAULT_BASE_URL = "https://mcp.endzoneapi.com"
|
|
22
|
+
SIGNUP_URL = "https://endzoneapi.com/signup"
|
|
23
|
+
DEFAULT_TIMEOUT = 60.0
|
|
24
|
+
MAX_RETRIES = 3
|
|
25
|
+
MAX_RETRY_WAIT = 30.0
|
|
26
|
+
|
|
27
|
+
# A transport takes (method, url, headers, body, timeout) and returns
|
|
28
|
+
# (status, headers, body). Header names in the returned dict are lowercase.
|
|
29
|
+
Transport = Callable[
|
|
30
|
+
[str, str, Dict[str, str], Optional[bytes], float],
|
|
31
|
+
Tuple[int, Dict[str, str], bytes],
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class APIError(Exception):
|
|
36
|
+
"""Any error response from the API, or a failed connection."""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
message: str,
|
|
41
|
+
status_code: Optional[int] = None,
|
|
42
|
+
body: Any = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__(message)
|
|
45
|
+
self.message = message
|
|
46
|
+
self.status_code = status_code
|
|
47
|
+
self.body = body
|
|
48
|
+
|
|
49
|
+
def __str__(self) -> str:
|
|
50
|
+
if self.status_code:
|
|
51
|
+
return "%s (HTTP %s)" % (self.message, self.status_code)
|
|
52
|
+
return self.message
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class AuthError(APIError):
|
|
56
|
+
"""401: the API key is missing, invalid or revoked."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class InsufficientCreditsError(APIError):
|
|
60
|
+
"""402: the account does not have enough credits for this call."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class NotFoundError(APIError):
|
|
64
|
+
"""404: the game, player, team or other id does not exist."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class RateLimitError(APIError):
|
|
68
|
+
"""429: too many requests. ``retry_after`` is in seconds when the server sent it."""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
message: str,
|
|
73
|
+
status_code: Optional[int] = 429,
|
|
74
|
+
body: Any = None,
|
|
75
|
+
retry_after: Optional[float] = None,
|
|
76
|
+
) -> None:
|
|
77
|
+
super().__init__(message, status_code, body)
|
|
78
|
+
self.retry_after = retry_after
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class APIConnectionError(APIError):
|
|
82
|
+
"""The request never got a response (DNS, TLS, timeout, reset)."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _ssl_context() -> Optional[ssl.SSLContext]:
|
|
86
|
+
"""Use certifi's CA bundle when it is installed, else the system default.
|
|
87
|
+
|
|
88
|
+
Some python.org installs on macOS ship without root certificates. Installing
|
|
89
|
+
certifi (or running the "Install Certificates" script) fixes the resulting
|
|
90
|
+
CERTIFICATE_VERIFY_FAILED error.
|
|
91
|
+
"""
|
|
92
|
+
try:
|
|
93
|
+
import certifi
|
|
94
|
+
except ImportError:
|
|
95
|
+
return None
|
|
96
|
+
return ssl.create_default_context(cafile=certifi.where())
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _urllib_transport(
|
|
100
|
+
method: str,
|
|
101
|
+
url: str,
|
|
102
|
+
headers: Dict[str, str],
|
|
103
|
+
body: Optional[bytes],
|
|
104
|
+
timeout: float,
|
|
105
|
+
) -> Tuple[int, Dict[str, str], bytes]:
|
|
106
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
107
|
+
try:
|
|
108
|
+
with urllib.request.urlopen(req, timeout=timeout, context=_ssl_context()) as resp:
|
|
109
|
+
return (
|
|
110
|
+
resp.status,
|
|
111
|
+
{k.lower(): v for k, v in resp.headers.items()},
|
|
112
|
+
resp.read(),
|
|
113
|
+
)
|
|
114
|
+
except urllib.error.HTTPError as exc:
|
|
115
|
+
try:
|
|
116
|
+
payload = exc.read()
|
|
117
|
+
finally:
|
|
118
|
+
exc.close()
|
|
119
|
+
return (
|
|
120
|
+
exc.code,
|
|
121
|
+
{k.lower(): v for k, v in (exc.headers or {}).items()},
|
|
122
|
+
payload,
|
|
123
|
+
)
|
|
124
|
+
except (urllib.error.URLError, socket.timeout, ConnectionError, OSError) as exc:
|
|
125
|
+
reason = getattr(exc, "reason", exc)
|
|
126
|
+
raise APIConnectionError("Could not reach the API: %s" % (reason,)) from exc
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _to_number(value: Optional[str]) -> Optional[Union[int, float]]:
|
|
130
|
+
if value is None:
|
|
131
|
+
return None
|
|
132
|
+
try:
|
|
133
|
+
return int(value)
|
|
134
|
+
except ValueError:
|
|
135
|
+
try:
|
|
136
|
+
return float(value)
|
|
137
|
+
except ValueError:
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _error_message(parsed: Any, raw: bytes, status: int) -> str:
|
|
142
|
+
if isinstance(parsed, dict):
|
|
143
|
+
err = parsed.get("error")
|
|
144
|
+
if isinstance(err, str) and err:
|
|
145
|
+
return err
|
|
146
|
+
if isinstance(err, dict) and isinstance(err.get("message"), str):
|
|
147
|
+
return err["message"]
|
|
148
|
+
text = raw.decode("utf-8", "replace").strip()
|
|
149
|
+
if text:
|
|
150
|
+
return text[:300]
|
|
151
|
+
return "HTTP %s" % status
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class BaseClient:
|
|
155
|
+
"""Holds the key, base URL, retry policy and the last credit counters."""
|
|
156
|
+
|
|
157
|
+
def __init__(
|
|
158
|
+
self,
|
|
159
|
+
api_key: Optional[str] = None,
|
|
160
|
+
*,
|
|
161
|
+
base_url: Optional[str] = None,
|
|
162
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
163
|
+
max_retries: int = MAX_RETRIES,
|
|
164
|
+
transport: Optional[Transport] = None,
|
|
165
|
+
) -> None:
|
|
166
|
+
key = api_key or os.environ.get(ENV_VAR)
|
|
167
|
+
if not key:
|
|
168
|
+
raise AuthError(
|
|
169
|
+
"No API key. Pass api_key=... or set %s. "
|
|
170
|
+
"A free key is at %s" % (ENV_VAR, SIGNUP_URL)
|
|
171
|
+
)
|
|
172
|
+
self.api_key = key
|
|
173
|
+
self.base_url = (base_url or os.environ.get(BRAND.upper() + "_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
174
|
+
self.timeout = timeout
|
|
175
|
+
self.max_retries = max(0, int(max_retries))
|
|
176
|
+
self._transport: Transport = transport or _urllib_transport
|
|
177
|
+
self._sleep: Callable[[float], None] = time.sleep
|
|
178
|
+
self.last_credits_used: Optional[Union[int, float]] = None
|
|
179
|
+
self.last_credits_remaining: Optional[Union[int, float]] = None
|
|
180
|
+
|
|
181
|
+
def __repr__(self) -> str:
|
|
182
|
+
return "<%s.Client base_url=%r>" % (BRAND, self.base_url)
|
|
183
|
+
|
|
184
|
+
def call(self, tool: str, arguments: Optional[Dict[str, Any]] = None) -> Any:
|
|
185
|
+
"""Call any tool by name. Useful for tools newer than this package."""
|
|
186
|
+
return self._call(tool, arguments or {})
|
|
187
|
+
|
|
188
|
+
def _call(self, tool: str, arguments: Dict[str, Any]) -> Any:
|
|
189
|
+
payload = {k: v for k, v in arguments.items() if v is not None}
|
|
190
|
+
url = "%s/v1/%s" % (self.base_url, tool)
|
|
191
|
+
headers = {
|
|
192
|
+
"x-api-key": self.api_key,
|
|
193
|
+
"content-type": "application/json",
|
|
194
|
+
"accept": "application/json",
|
|
195
|
+
"user-agent": "%s-python/%s" % (BRAND.lower(), __version__),
|
|
196
|
+
}
|
|
197
|
+
body = json.dumps(payload).encode("utf-8")
|
|
198
|
+
|
|
199
|
+
attempt = 0
|
|
200
|
+
while True:
|
|
201
|
+
try:
|
|
202
|
+
status, resp_headers, raw = self._transport("POST", url, headers, body, self.timeout)
|
|
203
|
+
except APIConnectionError:
|
|
204
|
+
if attempt >= self.max_retries:
|
|
205
|
+
raise
|
|
206
|
+
self._sleep(self._backoff(attempt, None))
|
|
207
|
+
attempt += 1
|
|
208
|
+
continue
|
|
209
|
+
|
|
210
|
+
self._record_credits(resp_headers)
|
|
211
|
+
if status == 429 or status >= 500:
|
|
212
|
+
if attempt < self.max_retries:
|
|
213
|
+
self._sleep(self._backoff(attempt, self._retry_after(resp_headers)))
|
|
214
|
+
attempt += 1
|
|
215
|
+
continue
|
|
216
|
+
return self._handle(status, resp_headers, raw)
|
|
217
|
+
|
|
218
|
+
@staticmethod
|
|
219
|
+
def _retry_after(headers: Dict[str, str]) -> Optional[float]:
|
|
220
|
+
value = headers.get("retry-after")
|
|
221
|
+
if value is None:
|
|
222
|
+
return None
|
|
223
|
+
try:
|
|
224
|
+
return max(0.0, float(value))
|
|
225
|
+
except ValueError:
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
@staticmethod
|
|
229
|
+
def _backoff(attempt: int, retry_after: Optional[float]) -> float:
|
|
230
|
+
if retry_after is not None:
|
|
231
|
+
return min(retry_after, MAX_RETRY_WAIT)
|
|
232
|
+
return min(0.5 * (2 ** attempt), MAX_RETRY_WAIT)
|
|
233
|
+
|
|
234
|
+
def _record_credits(self, headers: Dict[str, str]) -> None:
|
|
235
|
+
used = _to_number(headers.get("x-credits-used"))
|
|
236
|
+
remaining = _to_number(headers.get("x-credits-remaining"))
|
|
237
|
+
if used is not None:
|
|
238
|
+
self.last_credits_used = used
|
|
239
|
+
if remaining is not None:
|
|
240
|
+
self.last_credits_remaining = remaining
|
|
241
|
+
|
|
242
|
+
def _handle(self, status: int, headers: Dict[str, str], raw: bytes) -> Any:
|
|
243
|
+
try:
|
|
244
|
+
parsed = json.loads(raw.decode("utf-8")) if raw else None
|
|
245
|
+
except ValueError:
|
|
246
|
+
parsed = None
|
|
247
|
+
|
|
248
|
+
if 200 <= status < 300:
|
|
249
|
+
if parsed is None:
|
|
250
|
+
raise APIError("The API returned a response that is not JSON", status, raw[:300])
|
|
251
|
+
if isinstance(parsed, dict) and "data" in parsed:
|
|
252
|
+
return parsed["data"]
|
|
253
|
+
return parsed
|
|
254
|
+
|
|
255
|
+
message = _error_message(parsed, raw, status)
|
|
256
|
+
if status == 401:
|
|
257
|
+
raise AuthError(message, status, parsed)
|
|
258
|
+
if status == 402:
|
|
259
|
+
raise InsufficientCreditsError(message, status, parsed)
|
|
260
|
+
if status == 404:
|
|
261
|
+
raise NotFoundError(message, status, parsed)
|
|
262
|
+
if status == 429:
|
|
263
|
+
raise RateLimitError(message, status, parsed, self._retry_after(headers))
|
|
264
|
+
raise APIError(message, status, parsed)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _rows(data: Any, key: Optional[str]) -> List[Any]:
|
|
268
|
+
if key is not None:
|
|
269
|
+
cur = data
|
|
270
|
+
for part in key.split("."):
|
|
271
|
+
if not isinstance(cur, dict) or part not in cur:
|
|
272
|
+
raise KeyError("No %r in the response. Keys: %s" % (key, sorted(cur) if isinstance(cur, dict) else type(cur).__name__))
|
|
273
|
+
cur = cur[part]
|
|
274
|
+
if isinstance(cur, list):
|
|
275
|
+
return cur
|
|
276
|
+
return [cur]
|
|
277
|
+
if isinstance(data, list):
|
|
278
|
+
return data
|
|
279
|
+
if isinstance(data, dict):
|
|
280
|
+
lists = {k: v for k, v in data.items() if isinstance(v, list)}
|
|
281
|
+
records = {k: v for k, v in lists.items() if v and all(isinstance(r, dict) for r in v)}
|
|
282
|
+
pool = records or lists
|
|
283
|
+
if pool:
|
|
284
|
+
return pool[max(pool, key=lambda k: len(pool[k]))]
|
|
285
|
+
for v in data.values():
|
|
286
|
+
if isinstance(v, dict) and any(isinstance(x, list) for x in v.values()):
|
|
287
|
+
return _rows(v, None)
|
|
288
|
+
return [data]
|
|
289
|
+
return [data]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def to_dataframe(data: Any, key: Optional[str] = None) -> Any:
|
|
293
|
+
"""Turn a response into a pandas DataFrame.
|
|
294
|
+
|
|
295
|
+
``data`` is what a client method returned. ``key`` names the list to use
|
|
296
|
+
(dots reach into nested dicts, for example ``"props"``). Without a key the
|
|
297
|
+
longest list of records in the response is used. Nested dicts are flattened
|
|
298
|
+
into dotted columns. pandas is imported here, so it stays optional.
|
|
299
|
+
"""
|
|
300
|
+
try:
|
|
301
|
+
import pandas as pd
|
|
302
|
+
except ImportError as exc: # pragma: no cover
|
|
303
|
+
raise ImportError("to_dataframe needs pandas: pip install pandas") from exc
|
|
304
|
+
rows = _rows(data, key)
|
|
305
|
+
if rows and all(isinstance(r, dict) for r in rows):
|
|
306
|
+
return pd.json_normalize(rows)
|
|
307
|
+
return pd.DataFrame(rows)
|
endzoneapi/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|