fastballapi 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.
- fastballapi/__init__.py +25 -0
- fastballapi/_core.py +307 -0
- fastballapi/_version.py +1 -0
- fastballapi/client.py +773 -0
- fastballapi/py.typed +0 -0
- fastballapi-0.1.0.dist-info/METADATA +194 -0
- fastballapi-0.1.0.dist-info/RECORD +9 -0
- fastballapi-0.1.0.dist-info/WHEEL +4 -0
- fastballapi-0.1.0.dist-info/licenses/LICENSE +21 -0
fastballapi/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""FastballAPI: Python client for the FastballAPI MLB 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
|
+
]
|
fastballapi/_core.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Shared runtime for the FastballAPI 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 = "FastballAPI"
|
|
20
|
+
ENV_VAR = "FASTBALLAPI_API_KEY"
|
|
21
|
+
DEFAULT_BASE_URL = "https://mcp.fastballapi.com"
|
|
22
|
+
SIGNUP_URL = "https://fastballapi.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)
|
fastballapi/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
fastballapi/client.py
ADDED
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
"""Generated by packages/python/generate.py from the FastballAPI OpenAPI spec. Do not edit by hand."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, List, Literal, Optional, Union
|
|
5
|
+
|
|
6
|
+
from ._core import BaseClient
|
|
7
|
+
|
|
8
|
+
#: Credits each tool costs, from the spec.
|
|
9
|
+
TOOLS: Dict[str, int] = {
|
|
10
|
+
"list_teams": 1,
|
|
11
|
+
"get_games": 2,
|
|
12
|
+
"get_schedule": 2,
|
|
13
|
+
"get_game": 5,
|
|
14
|
+
"get_standings": 2,
|
|
15
|
+
"get_injuries": 2,
|
|
16
|
+
"search_players": 1,
|
|
17
|
+
"get_player": 5,
|
|
18
|
+
"get_player_games": 5,
|
|
19
|
+
"get_leaders": 5,
|
|
20
|
+
"get_team_stats": 5,
|
|
21
|
+
"get_plate_appearances": 10,
|
|
22
|
+
"get_pitches": 10,
|
|
23
|
+
"get_pitch_mix": 5,
|
|
24
|
+
"get_spray_chart": 10,
|
|
25
|
+
"get_odds": 5,
|
|
26
|
+
"get_line_movement": 10,
|
|
27
|
+
"get_ratings": 2,
|
|
28
|
+
"get_player_props": 10,
|
|
29
|
+
"get_prop_history": 10,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Client(BaseClient):
|
|
34
|
+
"""Client for the FastballAPI API (MLB).
|
|
35
|
+
|
|
36
|
+
Create one with ``Client()`` (reads FASTBALLAPI_API_KEY) or ``Client(api_key="...")``.
|
|
37
|
+
Every method returns the unwrapped ``data`` from the response.
|
|
38
|
+
``last_credits_used`` and ``last_credits_remaining`` hold the counters from
|
|
39
|
+
the most recent response.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def list_teams(
|
|
43
|
+
self,
|
|
44
|
+
*,
|
|
45
|
+
season: Optional[Union[int, float, str]] = None,
|
|
46
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
47
|
+
) -> Any:
|
|
48
|
+
"""List teams.
|
|
49
|
+
|
|
50
|
+
Use to find team ids and abbreviations for a season (default: the latest). Every other tool
|
|
51
|
+
takes a team as an id or abbreviation. Costs 1 credit.
|
|
52
|
+
|
|
53
|
+
Costs 1 credit per call.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
season (optional): Season (a year, e.g. 2025; default: the latest).
|
|
57
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
The unwrapped ``data`` object from the response.
|
|
61
|
+
"""
|
|
62
|
+
return self._call(
|
|
63
|
+
"list_teams",
|
|
64
|
+
{
|
|
65
|
+
"season": season,
|
|
66
|
+
"league": league,
|
|
67
|
+
},
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def get_games(
|
|
71
|
+
self,
|
|
72
|
+
*,
|
|
73
|
+
season: Optional[Union[int, float, str]] = None,
|
|
74
|
+
season_type: Optional[Literal["regular", "postseason"]] = None,
|
|
75
|
+
team: Optional[str] = None,
|
|
76
|
+
date: Optional[str] = None,
|
|
77
|
+
from_: Optional[str] = None,
|
|
78
|
+
to: Optional[str] = None,
|
|
79
|
+
status: Optional[Literal["scheduled", "final"]] = None,
|
|
80
|
+
limit: Optional[int] = None,
|
|
81
|
+
offset: Optional[int] = None,
|
|
82
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
83
|
+
) -> Any:
|
|
84
|
+
"""Games.
|
|
85
|
+
|
|
86
|
+
Use to list games with runs, hits and errors by season, date, date range or team, newest first.
|
|
87
|
+
For upcoming games with lines use get_schedule; for one game's box score use get_game. Costs 2
|
|
88
|
+
credits.
|
|
89
|
+
|
|
90
|
+
Costs 2 credits per call.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
season (optional): Season (a year, e.g. 2025; default: the latest).
|
|
94
|
+
season_type (optional): regular or postseason (default both).
|
|
95
|
+
team (optional): Team id or abbreviation.
|
|
96
|
+
date (optional): One date, YYYY-MM-DD (US Eastern).
|
|
97
|
+
from_ (optional): From date, YYYY-MM-DD.
|
|
98
|
+
to (optional): To date, YYYY-MM-DD.
|
|
99
|
+
status (optional): One of: scheduled, final.
|
|
100
|
+
limit (optional): Max games (default 50).
|
|
101
|
+
offset (optional): offset
|
|
102
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
The unwrapped ``data`` object from the response.
|
|
106
|
+
"""
|
|
107
|
+
return self._call(
|
|
108
|
+
"get_games",
|
|
109
|
+
{
|
|
110
|
+
"season": season,
|
|
111
|
+
"season_type": season_type,
|
|
112
|
+
"team": team,
|
|
113
|
+
"date": date,
|
|
114
|
+
"from": from_,
|
|
115
|
+
"to": to,
|
|
116
|
+
"status": status,
|
|
117
|
+
"limit": limit,
|
|
118
|
+
"offset": offset,
|
|
119
|
+
"league": league,
|
|
120
|
+
},
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
def get_schedule(
|
|
124
|
+
self,
|
|
125
|
+
*,
|
|
126
|
+
days: Optional[int] = None,
|
|
127
|
+
team: Optional[str] = None,
|
|
128
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
129
|
+
) -> Any:
|
|
130
|
+
"""Schedule.
|
|
131
|
+
|
|
132
|
+
Use for upcoming games (next 1-30 days, default 7) with the median line across posted
|
|
133
|
+
sportsbooks: moneylines, run line and total. For every book's line use get_odds. Costs 2
|
|
134
|
+
credits.
|
|
135
|
+
|
|
136
|
+
Costs 2 credits per call.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
days (optional): days
|
|
140
|
+
team (optional): Team id or abbreviation.
|
|
141
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
The unwrapped ``data`` object from the response.
|
|
145
|
+
"""
|
|
146
|
+
return self._call(
|
|
147
|
+
"get_schedule",
|
|
148
|
+
{
|
|
149
|
+
"days": days,
|
|
150
|
+
"team": team,
|
|
151
|
+
"league": league,
|
|
152
|
+
},
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
def get_game(
|
|
156
|
+
self,
|
|
157
|
+
game_id: str,
|
|
158
|
+
*,
|
|
159
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
160
|
+
) -> Any:
|
|
161
|
+
"""Game.
|
|
162
|
+
|
|
163
|
+
Use for one game in full: line score, every batter's and pitcher's line, each sportsbook's
|
|
164
|
+
opening and closing line, and the win-probability range. For every plate appearance use
|
|
165
|
+
get_plate_appearances. Costs 5 credits.
|
|
166
|
+
|
|
167
|
+
Costs 5 credits per call.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
game_id: ESPN game id, from get_games or get_schedule.
|
|
171
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
The unwrapped ``data`` object from the response.
|
|
175
|
+
"""
|
|
176
|
+
return self._call(
|
|
177
|
+
"get_game",
|
|
178
|
+
{
|
|
179
|
+
"game_id": game_id,
|
|
180
|
+
"league": league,
|
|
181
|
+
},
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def get_standings(
|
|
185
|
+
self,
|
|
186
|
+
*,
|
|
187
|
+
season: Optional[Union[int, float, str]] = None,
|
|
188
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
189
|
+
) -> Any:
|
|
190
|
+
"""Standings.
|
|
191
|
+
|
|
192
|
+
Use for a season's regular-season standings computed from every final game: record, home and
|
|
193
|
+
away, last 10, runs scored and allowed, run differential and Pythagorean win percentage. Costs 2
|
|
194
|
+
credits.
|
|
195
|
+
|
|
196
|
+
Costs 2 credits per call.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
season (optional): Season (a year, e.g. 2025; default: the latest).
|
|
200
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
The unwrapped ``data`` object from the response.
|
|
204
|
+
"""
|
|
205
|
+
return self._call(
|
|
206
|
+
"get_standings",
|
|
207
|
+
{
|
|
208
|
+
"season": season,
|
|
209
|
+
"league": league,
|
|
210
|
+
},
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
def get_injuries(
|
|
214
|
+
self,
|
|
215
|
+
*,
|
|
216
|
+
team: Optional[str] = None,
|
|
217
|
+
date: Optional[str] = None,
|
|
218
|
+
) -> Any:
|
|
219
|
+
"""Injuries.
|
|
220
|
+
|
|
221
|
+
Use for the injury report: every listed player's status, injury and expected return, as captured
|
|
222
|
+
on the latest day (or the latest on or before date). Costs 2 credits.
|
|
223
|
+
|
|
224
|
+
Costs 2 credits per call.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
team (optional): team
|
|
228
|
+
date (optional): YYYY-MM-DD (default: the latest).
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
The unwrapped ``data`` object from the response.
|
|
232
|
+
"""
|
|
233
|
+
return self._call(
|
|
234
|
+
"get_injuries",
|
|
235
|
+
{
|
|
236
|
+
"team": team,
|
|
237
|
+
"date": date,
|
|
238
|
+
},
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
def search_players(
|
|
242
|
+
self,
|
|
243
|
+
name: str,
|
|
244
|
+
*,
|
|
245
|
+
limit: Optional[int] = None,
|
|
246
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
247
|
+
) -> Any:
|
|
248
|
+
"""Search players.
|
|
249
|
+
|
|
250
|
+
Use to find a player's id by name (partial names work). Costs 1 credit.
|
|
251
|
+
|
|
252
|
+
Costs 1 credit per call.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
name: Full or partial name.
|
|
256
|
+
limit (optional): limit
|
|
257
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
The unwrapped ``data`` object from the response.
|
|
261
|
+
"""
|
|
262
|
+
return self._call(
|
|
263
|
+
"search_players",
|
|
264
|
+
{
|
|
265
|
+
"name": name,
|
|
266
|
+
"limit": limit,
|
|
267
|
+
"league": league,
|
|
268
|
+
},
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
def get_player(
|
|
272
|
+
self,
|
|
273
|
+
player_id: str,
|
|
274
|
+
*,
|
|
275
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
276
|
+
) -> Any:
|
|
277
|
+
"""Player.
|
|
278
|
+
|
|
279
|
+
Use for a player's season-by-season batting (AVG, OBP, SLG, OPS, HR, K%, BB%, RE24, from every
|
|
280
|
+
plate appearance) and pitching (ERA, WHIP, K/9, BB/9). Costs 5 credits.
|
|
281
|
+
|
|
282
|
+
Costs 5 credits per call.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
player_id: ESPN athlete id, from search_players.
|
|
286
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
The unwrapped ``data`` object from the response.
|
|
290
|
+
"""
|
|
291
|
+
return self._call(
|
|
292
|
+
"get_player",
|
|
293
|
+
{
|
|
294
|
+
"player_id": player_id,
|
|
295
|
+
"league": league,
|
|
296
|
+
},
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
def get_player_games(
|
|
300
|
+
self,
|
|
301
|
+
player_id: str,
|
|
302
|
+
*,
|
|
303
|
+
season: Optional[Union[int, float, str]] = None,
|
|
304
|
+
season_type: Optional[Literal["regular", "postseason"]] = None,
|
|
305
|
+
limit: Optional[int] = None,
|
|
306
|
+
offset: Optional[int] = None,
|
|
307
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
308
|
+
) -> Any:
|
|
309
|
+
"""Player games.
|
|
310
|
+
|
|
311
|
+
Use for a player's game log: every game's batting line and pitching line, newest first,
|
|
312
|
+
optionally one season. Costs 5 credits.
|
|
313
|
+
|
|
314
|
+
Costs 5 credits per call.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
player_id: player_id
|
|
318
|
+
season (optional): Season (a year, e.g. 2025; default: the latest).
|
|
319
|
+
season_type (optional): One of: regular, postseason.
|
|
320
|
+
limit (optional): limit
|
|
321
|
+
offset (optional): offset
|
|
322
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
The unwrapped ``data`` object from the response.
|
|
326
|
+
"""
|
|
327
|
+
return self._call(
|
|
328
|
+
"get_player_games",
|
|
329
|
+
{
|
|
330
|
+
"player_id": player_id,
|
|
331
|
+
"season": season,
|
|
332
|
+
"season_type": season_type,
|
|
333
|
+
"limit": limit,
|
|
334
|
+
"offset": offset,
|
|
335
|
+
"league": league,
|
|
336
|
+
},
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
def get_leaders(
|
|
340
|
+
self,
|
|
341
|
+
stat: Literal["avg", "obp", "slg", "ops", "hr", "re24", "bb_pct", "k_pct", "era", "whip", "so", "k_per_9", "bb_per_9"],
|
|
342
|
+
*,
|
|
343
|
+
season: Optional[Union[int, float, str]] = None,
|
|
344
|
+
min_pa: Optional[int] = None,
|
|
345
|
+
min_ip: Optional[int] = None,
|
|
346
|
+
limit: Optional[int] = None,
|
|
347
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
348
|
+
) -> Any:
|
|
349
|
+
"""Leaders.
|
|
350
|
+
|
|
351
|
+
Use for a season's leaders among qualified players: batting avg, obp, slg, ops, hr, re24,
|
|
352
|
+
bb_pct, k_pct (3.1 plate appearances per team game) or pitching era, whip, so, k_per_9, bb_per_9
|
|
353
|
+
(1 inning per team game). Costs 5 credits.
|
|
354
|
+
|
|
355
|
+
Costs 5 credits per call.
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
stat: One of: avg, obp, slg, ops, hr, re24, bb_pct, k_pct, era, whip, so, k_per_9, bb_per_9.
|
|
359
|
+
season (optional): Season (a year, e.g. 2025; default: the latest).
|
|
360
|
+
min_pa (optional): Override the plate-appearance minimum.
|
|
361
|
+
min_ip (optional): Override the innings minimum.
|
|
362
|
+
limit (optional): limit
|
|
363
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
364
|
+
|
|
365
|
+
Returns:
|
|
366
|
+
The unwrapped ``data`` object from the response.
|
|
367
|
+
"""
|
|
368
|
+
return self._call(
|
|
369
|
+
"get_leaders",
|
|
370
|
+
{
|
|
371
|
+
"stat": stat,
|
|
372
|
+
"season": season,
|
|
373
|
+
"min_pa": min_pa,
|
|
374
|
+
"min_ip": min_ip,
|
|
375
|
+
"limit": limit,
|
|
376
|
+
"league": league,
|
|
377
|
+
},
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
def get_team_stats(
|
|
381
|
+
self,
|
|
382
|
+
*,
|
|
383
|
+
season: Optional[Union[int, float, str]] = None,
|
|
384
|
+
team: Optional[str] = None,
|
|
385
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
386
|
+
) -> Any:
|
|
387
|
+
"""Team stats.
|
|
388
|
+
|
|
389
|
+
Use for team offence and run prevention for a season: runs per game for and against, run
|
|
390
|
+
differential, and batting and opponents' batting (AVG, OBP, SLG, OPS, K%, BB%, HR) from every
|
|
391
|
+
plate appearance. Costs 5 credits.
|
|
392
|
+
|
|
393
|
+
Costs 5 credits per call.
|
|
394
|
+
|
|
395
|
+
Args:
|
|
396
|
+
season (optional): Season (a year, e.g. 2025; default: the latest).
|
|
397
|
+
team (optional): team
|
|
398
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
399
|
+
|
|
400
|
+
Returns:
|
|
401
|
+
The unwrapped ``data`` object from the response.
|
|
402
|
+
"""
|
|
403
|
+
return self._call(
|
|
404
|
+
"get_team_stats",
|
|
405
|
+
{
|
|
406
|
+
"season": season,
|
|
407
|
+
"team": team,
|
|
408
|
+
"league": league,
|
|
409
|
+
},
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
def get_plate_appearances(
|
|
413
|
+
self,
|
|
414
|
+
*,
|
|
415
|
+
game_id: Optional[str] = None,
|
|
416
|
+
batter_id: Optional[str] = None,
|
|
417
|
+
pitcher_id: Optional[str] = None,
|
|
418
|
+
team: Optional[str] = None,
|
|
419
|
+
season: Optional[Union[int, float, str]] = None,
|
|
420
|
+
season_type: Optional[Literal["regular", "postseason"]] = None,
|
|
421
|
+
result: Optional[str] = None,
|
|
422
|
+
inning: Optional[int] = None,
|
|
423
|
+
risp: Optional[bool] = None,
|
|
424
|
+
limit: Optional[int] = None,
|
|
425
|
+
offset: Optional[int] = None,
|
|
426
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
427
|
+
) -> Any:
|
|
428
|
+
"""Plate appearances.
|
|
429
|
+
|
|
430
|
+
Use for plate-appearance play-by-play: a whole game in order, or a batter's, pitcher's or team's
|
|
431
|
+
season, with the base-out state before, the result, the batted ball (trajectory and location),
|
|
432
|
+
runs, the win probability after (2019 on) and our run value (RE24). Filter by result, inning or
|
|
433
|
+
runners in scoring position. Costs 10 credits.
|
|
434
|
+
|
|
435
|
+
Costs 10 credits per call.
|
|
436
|
+
|
|
437
|
+
Args:
|
|
438
|
+
game_id (optional): game_id
|
|
439
|
+
batter_id (optional): batter_id
|
|
440
|
+
pitcher_id (optional): pitcher_id
|
|
441
|
+
team (optional): Batting team (id or abbreviation).
|
|
442
|
+
season (optional): Season (a year; default: the latest; ignored with game_id).
|
|
443
|
+
season_type (optional): One of: regular, postseason.
|
|
444
|
+
result (optional): e.g. home-run, strikeout, walk, single, double, ground-out.
|
|
445
|
+
inning (optional): inning
|
|
446
|
+
risp (optional): Runners in scoring position only.
|
|
447
|
+
limit (optional): Max rows (default 200).
|
|
448
|
+
offset (optional): offset
|
|
449
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
450
|
+
|
|
451
|
+
Returns:
|
|
452
|
+
The unwrapped ``data`` object from the response.
|
|
453
|
+
"""
|
|
454
|
+
return self._call(
|
|
455
|
+
"get_plate_appearances",
|
|
456
|
+
{
|
|
457
|
+
"game_id": game_id,
|
|
458
|
+
"batter_id": batter_id,
|
|
459
|
+
"pitcher_id": pitcher_id,
|
|
460
|
+
"team": team,
|
|
461
|
+
"season": season,
|
|
462
|
+
"season_type": season_type,
|
|
463
|
+
"result": result,
|
|
464
|
+
"inning": inning,
|
|
465
|
+
"risp": risp,
|
|
466
|
+
"limit": limit,
|
|
467
|
+
"offset": offset,
|
|
468
|
+
"league": league,
|
|
469
|
+
},
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
def get_pitches(
|
|
473
|
+
self,
|
|
474
|
+
*,
|
|
475
|
+
game_id: Optional[str] = None,
|
|
476
|
+
pitcher_id: Optional[str] = None,
|
|
477
|
+
batter_id: Optional[str] = None,
|
|
478
|
+
season: Optional[Union[int, float, str]] = None,
|
|
479
|
+
pitch_type: Optional[str] = None,
|
|
480
|
+
limit: Optional[int] = None,
|
|
481
|
+
offset: Optional[int] = None,
|
|
482
|
+
) -> Any:
|
|
483
|
+
"""Pitches.
|
|
484
|
+
|
|
485
|
+
Use for pitch-by-pitch data: every pitch of a game, or a pitcher's or batter's season, with the
|
|
486
|
+
count, pitch type, velocity, location and result. Costs 10 credits.
|
|
487
|
+
|
|
488
|
+
Costs 10 credits per call.
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
game_id (optional): game_id
|
|
492
|
+
pitcher_id (optional): pitcher_id
|
|
493
|
+
batter_id (optional): batter_id
|
|
494
|
+
season (optional): Season (a year; default: the latest; ignored with game_id).
|
|
495
|
+
pitch_type (optional): ESPN abbreviation, e.g. FF, SL, CH, CU, SI, FC.
|
|
496
|
+
limit (optional): Max pitches (default 500).
|
|
497
|
+
offset (optional): offset
|
|
498
|
+
|
|
499
|
+
Returns:
|
|
500
|
+
The unwrapped ``data`` object from the response.
|
|
501
|
+
"""
|
|
502
|
+
return self._call(
|
|
503
|
+
"get_pitches",
|
|
504
|
+
{
|
|
505
|
+
"game_id": game_id,
|
|
506
|
+
"pitcher_id": pitcher_id,
|
|
507
|
+
"batter_id": batter_id,
|
|
508
|
+
"season": season,
|
|
509
|
+
"pitch_type": pitch_type,
|
|
510
|
+
"limit": limit,
|
|
511
|
+
"offset": offset,
|
|
512
|
+
},
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
def get_pitch_mix(
|
|
516
|
+
self,
|
|
517
|
+
pitcher_id: str,
|
|
518
|
+
*,
|
|
519
|
+
season: Optional[Union[int, float, str]] = None,
|
|
520
|
+
) -> Any:
|
|
521
|
+
"""Pitch mix.
|
|
522
|
+
|
|
523
|
+
Use for a pitcher's arsenal in a season: each pitch type's usage, average and top velocity,
|
|
524
|
+
whiff rate per swing and ball rate. Costs 5 credits.
|
|
525
|
+
|
|
526
|
+
Costs 5 credits per call.
|
|
527
|
+
|
|
528
|
+
Args:
|
|
529
|
+
pitcher_id: ESPN athlete id.
|
|
530
|
+
season (optional): Season (a year; default: the latest; ignored with game_id).
|
|
531
|
+
|
|
532
|
+
Returns:
|
|
533
|
+
The unwrapped ``data`` object from the response.
|
|
534
|
+
"""
|
|
535
|
+
return self._call(
|
|
536
|
+
"get_pitch_mix",
|
|
537
|
+
{
|
|
538
|
+
"pitcher_id": pitcher_id,
|
|
539
|
+
"season": season,
|
|
540
|
+
},
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
def get_spray_chart(
|
|
544
|
+
self,
|
|
545
|
+
*,
|
|
546
|
+
batter_id: Optional[str] = None,
|
|
547
|
+
team: Optional[str] = None,
|
|
548
|
+
season: Optional[Union[int, float, str]] = None,
|
|
549
|
+
include_balls: Optional[bool] = None,
|
|
550
|
+
) -> Any:
|
|
551
|
+
"""Spray chart.
|
|
552
|
+
|
|
553
|
+
Use for where a batter or team hits the ball: balls in play by trajectory (ground ball, line
|
|
554
|
+
drive, fly ball, pop-up) and by field (left, center, right), with hit rates; include_balls adds
|
|
555
|
+
each ball's location for drawing. Costs 10 credits.
|
|
556
|
+
|
|
557
|
+
Costs 10 credits per call.
|
|
558
|
+
|
|
559
|
+
Args:
|
|
560
|
+
batter_id (optional): batter_id
|
|
561
|
+
team (optional): team
|
|
562
|
+
season (optional): Season (a year; default: the latest; ignored with game_id).
|
|
563
|
+
include_balls (optional): Add each ball in play's x/y (up to 3,000).
|
|
564
|
+
|
|
565
|
+
Returns:
|
|
566
|
+
The unwrapped ``data`` object from the response.
|
|
567
|
+
"""
|
|
568
|
+
return self._call(
|
|
569
|
+
"get_spray_chart",
|
|
570
|
+
{
|
|
571
|
+
"batter_id": batter_id,
|
|
572
|
+
"team": team,
|
|
573
|
+
"season": season,
|
|
574
|
+
"include_balls": include_balls,
|
|
575
|
+
},
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
def get_odds(
|
|
579
|
+
self,
|
|
580
|
+
*,
|
|
581
|
+
game_id: Optional[str] = None,
|
|
582
|
+
date: Optional[str] = None,
|
|
583
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
584
|
+
) -> Any:
|
|
585
|
+
"""Odds.
|
|
586
|
+
|
|
587
|
+
Use for betting lines: each sportsbook's moneyline, run line and total for a game (opening and
|
|
588
|
+
closing per book from July 2020 from The Odds API, and from 2024 from ESPN; ESPN's final line
|
|
589
|
+
only before that), with implied probabilities and, for finished games, whether the favourite won
|
|
590
|
+
and the total went over against the median close. Pass game_id for one game (5 credits) or date
|
|
591
|
+
for a day's games (10 credits).
|
|
592
|
+
|
|
593
|
+
Costs 5 credits per call.
|
|
594
|
+
|
|
595
|
+
Args:
|
|
596
|
+
game_id (optional): game_id
|
|
597
|
+
date (optional): A day's games, YYYY-MM-DD (US Eastern).
|
|
598
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
599
|
+
|
|
600
|
+
Returns:
|
|
601
|
+
The unwrapped ``data`` object from the response.
|
|
602
|
+
"""
|
|
603
|
+
return self._call(
|
|
604
|
+
"get_odds",
|
|
605
|
+
{
|
|
606
|
+
"game_id": game_id,
|
|
607
|
+
"date": date,
|
|
608
|
+
"league": league,
|
|
609
|
+
},
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
def get_line_movement(
|
|
613
|
+
self,
|
|
614
|
+
game_id: str,
|
|
615
|
+
*,
|
|
616
|
+
provider: Optional[str] = None,
|
|
617
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
618
|
+
) -> Any:
|
|
619
|
+
"""Line movement.
|
|
620
|
+
|
|
621
|
+
Use to see how a game's line moved before first pitch: our pre-game snapshots of each
|
|
622
|
+
sportsbook's moneyline, run line and total (ESPN's once a day, The Odds API's every hour for
|
|
623
|
+
games in the next two days). Costs 10 credits.
|
|
624
|
+
|
|
625
|
+
Costs 10 credits per call.
|
|
626
|
+
|
|
627
|
+
Args:
|
|
628
|
+
game_id: game_id
|
|
629
|
+
provider (optional): One sportsbook, e.g. DraftKings.
|
|
630
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
631
|
+
|
|
632
|
+
Returns:
|
|
633
|
+
The unwrapped ``data`` object from the response.
|
|
634
|
+
"""
|
|
635
|
+
return self._call(
|
|
636
|
+
"get_line_movement",
|
|
637
|
+
{
|
|
638
|
+
"game_id": game_id,
|
|
639
|
+
"provider": provider,
|
|
640
|
+
"league": league,
|
|
641
|
+
},
|
|
642
|
+
)
|
|
643
|
+
|
|
644
|
+
def get_ratings(
|
|
645
|
+
self,
|
|
646
|
+
*,
|
|
647
|
+
season: Optional[Union[int, float, str]] = None,
|
|
648
|
+
league: Optional[Literal["mlb", "ncaabase"]] = None,
|
|
649
|
+
) -> Any:
|
|
650
|
+
"""Ratings.
|
|
651
|
+
|
|
652
|
+
Use for our team power ratings (Elo from every final game in our data), ranked, as of the end of
|
|
653
|
+
a season or today. Costs 2 credits.
|
|
654
|
+
|
|
655
|
+
Costs 2 credits per call.
|
|
656
|
+
|
|
657
|
+
Args:
|
|
658
|
+
season (optional): season
|
|
659
|
+
league (optional): League. Defaults to mlb. One of: mlb, ncaabase.
|
|
660
|
+
|
|
661
|
+
Returns:
|
|
662
|
+
The unwrapped ``data`` object from the response.
|
|
663
|
+
"""
|
|
664
|
+
return self._call(
|
|
665
|
+
"get_ratings",
|
|
666
|
+
{
|
|
667
|
+
"season": season,
|
|
668
|
+
"league": league,
|
|
669
|
+
},
|
|
670
|
+
)
|
|
671
|
+
|
|
672
|
+
def get_player_props(
|
|
673
|
+
self,
|
|
674
|
+
*,
|
|
675
|
+
game_id: Optional[str] = None,
|
|
676
|
+
player_id: Optional[str] = None,
|
|
677
|
+
from_date: Optional[str] = None,
|
|
678
|
+
to_date: Optional[str] = None,
|
|
679
|
+
market: Optional[Literal["batter_hits", "batter_home_runs", "batter_total_bases", "batter_rbis", "pitcher_strikeouts", "pitcher_outs"]] = None,
|
|
680
|
+
bookmaker: Optional[str] = None,
|
|
681
|
+
snapshot_type: Optional[Literal["opening", "closing"]] = None,
|
|
682
|
+
estimate_only: Optional[bool] = None,
|
|
683
|
+
) -> Any:
|
|
684
|
+
"""Player props.
|
|
685
|
+
|
|
686
|
+
Use for player prop lines by sportsbook: over/under on hits, home runs, total bases, RBI,
|
|
687
|
+
pitcher strikeouts and pitcher outs, from May 2023 (DraftKings, FanDuel, BetMGM, ESPN BET,
|
|
688
|
+
Pinnacle and others). Pass game_id for every player's props in one game (10 credits), or
|
|
689
|
+
player_id with from_date (and to_date) for one player across games (10 credits per game
|
|
690
|
+
returned, up to 100). Returns the closing line by default (the last before the game starts) or
|
|
691
|
+
the opening line, with each book's over and under prices. Set estimate_only to get the price
|
|
692
|
+
without being charged.
|
|
693
|
+
|
|
694
|
+
Costs 10 credits per call.
|
|
695
|
+
|
|
696
|
+
Args:
|
|
697
|
+
game_id (optional): Game id: every player's props for that game.
|
|
698
|
+
player_id (optional): Player id (e.g. 33192) from search_players. With from_date: that
|
|
699
|
+
player's props across games.
|
|
700
|
+
from_date (optional): With player_id: first date, YYYY-MM-DD (the game's date).
|
|
701
|
+
to_date (optional): With player_id: last date (default: no end), YYYY-MM-DD (the game's
|
|
702
|
+
date).
|
|
703
|
+
market (optional): One market: batter_hits (hits), batter_home_runs (home runs),
|
|
704
|
+
batter_total_bases (total bases), batter_rbis (runs batted in), pitcher_strikeouts
|
|
705
|
+
(pitcher strikeouts), pitcher_outs (pitcher outs recorded)
|
|
706
|
+
bookmaker (optional): Bookmaker key, e.g. draftkings, fanduel, pinnacle.
|
|
707
|
+
snapshot_type (optional): closing (default): the last line before the game starts. opening:
|
|
708
|
+
the first one captured.
|
|
709
|
+
estimate_only (optional): Return what this call would cost, without charging or running it.
|
|
710
|
+
|
|
711
|
+
Returns:
|
|
712
|
+
The unwrapped ``data`` object from the response.
|
|
713
|
+
"""
|
|
714
|
+
return self._call(
|
|
715
|
+
"get_player_props",
|
|
716
|
+
{
|
|
717
|
+
"game_id": game_id,
|
|
718
|
+
"player_id": player_id,
|
|
719
|
+
"from_date": from_date,
|
|
720
|
+
"to_date": to_date,
|
|
721
|
+
"market": market,
|
|
722
|
+
"bookmaker": bookmaker,
|
|
723
|
+
"snapshot_type": snapshot_type,
|
|
724
|
+
"estimate_only": estimate_only,
|
|
725
|
+
},
|
|
726
|
+
)
|
|
727
|
+
|
|
728
|
+
def get_prop_history(
|
|
729
|
+
self,
|
|
730
|
+
player_id: str,
|
|
731
|
+
market: Literal["batter_hits", "batter_home_runs", "batter_total_bases", "batter_rbis", "pitcher_strikeouts", "pitcher_outs"],
|
|
732
|
+
*,
|
|
733
|
+
from_date: Optional[str] = None,
|
|
734
|
+
to_date: Optional[str] = None,
|
|
735
|
+
bookmaker: Optional[str] = None,
|
|
736
|
+
limit: Optional[int] = None,
|
|
737
|
+
) -> Any:
|
|
738
|
+
"""Prop history.
|
|
739
|
+
|
|
740
|
+
Use to see how a player did against his prop line over time: for one market (hits, home runs,
|
|
741
|
+
total bases, RBI, pitcher strikeouts or pitcher outs), one row per game with the closing line
|
|
742
|
+
(the median across books, or one book's), the opening line, the prices, what the player actually
|
|
743
|
+
recorded from our box scores and the result against the line, plus the over rate. Costs 10
|
|
744
|
+
credits for up to 200 games.
|
|
745
|
+
|
|
746
|
+
Costs 10 credits per call.
|
|
747
|
+
|
|
748
|
+
Args:
|
|
749
|
+
player_id: Player id (e.g. 33192) from search_players.
|
|
750
|
+
market: The market: batter_hits (hits), batter_home_runs (home runs), batter_total_bases
|
|
751
|
+
(total bases), batter_rbis (runs batted in), pitcher_strikeouts (pitcher strikeouts),
|
|
752
|
+
pitcher_outs (pitcher outs recorded)
|
|
753
|
+
from_date (optional): First date, YYYY-MM-DD (the game's date).
|
|
754
|
+
to_date (optional): Last date, YYYY-MM-DD (the game's date).
|
|
755
|
+
bookmaker (optional): One book's closing line instead of the median across books, e.g.
|
|
756
|
+
draftkings.
|
|
757
|
+
limit (optional): Games to return, oldest first (default 50, max 200). next_from_date says
|
|
758
|
+
where to continue.
|
|
759
|
+
|
|
760
|
+
Returns:
|
|
761
|
+
The unwrapped ``data`` object from the response.
|
|
762
|
+
"""
|
|
763
|
+
return self._call(
|
|
764
|
+
"get_prop_history",
|
|
765
|
+
{
|
|
766
|
+
"player_id": player_id,
|
|
767
|
+
"market": market,
|
|
768
|
+
"from_date": from_date,
|
|
769
|
+
"to_date": to_date,
|
|
770
|
+
"bookmaker": bookmaker,
|
|
771
|
+
"limit": limit,
|
|
772
|
+
},
|
|
773
|
+
)
|
fastballapi/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fastballapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the FastballAPI MLB data API. No dependencies.
|
|
5
|
+
Project-URL: Homepage, https://fastballapi.com
|
|
6
|
+
Project-URL: Documentation, https://fastballapi.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/noahowsh/puckapi
|
|
8
|
+
Project-URL: Sign up, https://fastballapi.com/signup
|
|
9
|
+
Author-email: FastballAPI <support@fastballapi.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: api-client,betting,fastballapi,mlb,odds,player-props,sports-data
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Provides-Extra: pandas
|
|
26
|
+
Requires-Dist: pandas>=1.5; extra == 'pandas'
|
|
27
|
+
Provides-Extra: test
|
|
28
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# FastballAPI for Python
|
|
32
|
+
|
|
33
|
+
Python client for the [FastballAPI](https://fastballapi.com) MLB data API. It has no required dependencies (standard library only) and works on Python 3.9 and newer. Pandas is optional.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install fastballapi
|
|
39
|
+
pip install "fastballapi[pandas]" # only if you want DataFrames
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Set your key
|
|
43
|
+
|
|
44
|
+
Get a free key at https://fastballapi.com/signup. Free accounts get 500 credits a month.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
export FASTBALLAPI_API_KEY=your_key_here
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from fastballapi import Client
|
|
52
|
+
|
|
53
|
+
client = Client() # reads FASTBALLAPI_API_KEY
|
|
54
|
+
client = Client(api_key="your_key") # or pass it in
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Examples
|
|
58
|
+
|
|
59
|
+
### 1. Player props for one game
|
|
60
|
+
|
|
61
|
+
`get_player_props` returns lines by sportsbook. Here are home run props for one game.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from fastballapi import Client, to_dataframe
|
|
65
|
+
|
|
66
|
+
client = Client()
|
|
67
|
+
|
|
68
|
+
props = client.get_player_props(
|
|
69
|
+
game_id="401815991",
|
|
70
|
+
market="batter_home_runs",
|
|
71
|
+
)
|
|
72
|
+
df = to_dataframe(props, key="props")
|
|
73
|
+
print(df[["player_name", "bookmaker", "line", "over_odds", "under_odds"]].head(10))
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 2. A pitcher's pitch mix
|
|
77
|
+
|
|
78
|
+
Find the player id with `search_players`, then ask for usage, velocity and whiff rate by pitch type.
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from fastballapi import Client, to_dataframe
|
|
82
|
+
|
|
83
|
+
client = Client()
|
|
84
|
+
|
|
85
|
+
ohtani = client.search_players("Ohtani", limit=1)["players"][0]
|
|
86
|
+
mix = client.get_pitch_mix(ohtani["player_id"])
|
|
87
|
+
print(to_dataframe(mix, key="mix")[["name", "usage", "avg_velocity", "whiff_rate"]])
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 3. League leaders
|
|
91
|
+
|
|
92
|
+
`get_leaders` ranks qualified hitters or pitchers by a stat.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from fastballapi import Client
|
|
96
|
+
|
|
97
|
+
client = Client()
|
|
98
|
+
|
|
99
|
+
leaders = client.get_leaders("ops", limit=5)
|
|
100
|
+
for row in leaders["leaders"]:
|
|
101
|
+
print(row["name"], row["team"], row["ops"])
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Credits
|
|
105
|
+
|
|
106
|
+
Every method returns the `data` object from the response. After each call, `client.last_credits_used` and `client.last_credits_remaining` hold the counters from the `X-Credits-Used` and `X-Credits-Remaining` headers. Methods that take `estimate_only=True` return the price of a call without running or charging it.
|
|
107
|
+
|
|
108
|
+
## Pandas
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from fastballapi import to_dataframe
|
|
112
|
+
|
|
113
|
+
df = to_dataframe(data) # finds the main list in the response
|
|
114
|
+
df = to_dataframe(data, key="rows") # or name the list yourself
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Nested fields become dotted columns. Install pandas separately or with `pip install "fastballapi[pandas]"`.
|
|
118
|
+
|
|
119
|
+
## Errors
|
|
120
|
+
|
|
121
|
+
Every error is an `APIError` subclass, with the server's message and the HTTP status.
|
|
122
|
+
|
|
123
|
+
| Exception | Status | Meaning |
|
|
124
|
+
| --- | --- | --- |
|
|
125
|
+
| `AuthError` | 401 | Missing, invalid or revoked key |
|
|
126
|
+
| `InsufficientCreditsError` | 402 | Not enough credits for the call |
|
|
127
|
+
| `NotFoundError` | 404 | The id or name does not exist |
|
|
128
|
+
| `RateLimitError` | 429 | Too many requests; has `.retry_after` when the server sends it |
|
|
129
|
+
| `APIError` | 400, 5xx | Bad arguments or a server problem |
|
|
130
|
+
| `APIConnectionError` | none | No response (network or timeout) |
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from fastballapi import Client, APIError, InsufficientCreditsError, RateLimitError
|
|
134
|
+
|
|
135
|
+
client = Client()
|
|
136
|
+
try:
|
|
137
|
+
data = client.list_teams()
|
|
138
|
+
except InsufficientCreditsError:
|
|
139
|
+
print("Out of credits, top up at https://fastballapi.com")
|
|
140
|
+
except RateLimitError as exc:
|
|
141
|
+
print("Slow down, retry after", exc.retry_after)
|
|
142
|
+
except APIError as exc:
|
|
143
|
+
print(exc.status_code, exc.message)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The client retries 429 and 5xx responses and connection failures up to 3 times with backoff, and honors `Retry-After`. Set `Client(max_retries=0)` to turn that off.
|
|
147
|
+
|
|
148
|
+
If you see `CERTIFICATE_VERIFY_FAILED` on a python.org install for macOS, run the "Install Certificates.command" script that came with Python, or `pip install certifi` (the client uses it when present).
|
|
149
|
+
|
|
150
|
+
## Options
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
Client(
|
|
154
|
+
api_key=None, # defaults to $FASTBALLAPI_API_KEY
|
|
155
|
+
base_url="https://mcp.fastballapi.com", # point at another host
|
|
156
|
+
timeout=60.0, # seconds per request
|
|
157
|
+
max_retries=3,
|
|
158
|
+
)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`client.call("tool_name", {"arg": "value"})` calls any tool by name, which helps when the API adds a tool before this package does.
|
|
162
|
+
|
|
163
|
+
## Tools
|
|
164
|
+
|
|
165
|
+
Method names match the API tool names. Arguments are keyword arguments; required ones can also be passed positionally. Each method's docstring lists its arguments (`help(client.list_teams)`).
|
|
166
|
+
|
|
167
|
+
| Method | Credits | What it does |
|
|
168
|
+
| --- | --- | --- |
|
|
169
|
+
| `list_teams` | 1 | List teams |
|
|
170
|
+
| `get_games` | 2 | Games |
|
|
171
|
+
| `get_schedule` | 2 | Schedule |
|
|
172
|
+
| `get_game` | 5 | Game |
|
|
173
|
+
| `get_standings` | 2 | Standings |
|
|
174
|
+
| `get_injuries` | 2 | Injuries |
|
|
175
|
+
| `search_players` | 1 | Search players |
|
|
176
|
+
| `get_player` | 5 | Player |
|
|
177
|
+
| `get_player_games` | 5 | Player games |
|
|
178
|
+
| `get_leaders` | 5 | Leaders |
|
|
179
|
+
| `get_team_stats` | 5 | Team stats |
|
|
180
|
+
| `get_plate_appearances` | 10 | Plate appearances |
|
|
181
|
+
| `get_pitches` | 10 | Pitches |
|
|
182
|
+
| `get_pitch_mix` | 5 | Pitch mix |
|
|
183
|
+
| `get_spray_chart` | 10 | Spray chart |
|
|
184
|
+
| `get_odds` | 5 | Odds |
|
|
185
|
+
| `get_line_movement` | 10 | Line movement |
|
|
186
|
+
| `get_ratings` | 2 | Ratings |
|
|
187
|
+
| `get_player_props` | 10 | Player props |
|
|
188
|
+
| `get_prop_history` | 10 | Prop history |
|
|
189
|
+
|
|
190
|
+
Full API reference: https://fastballapi.com/docs
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
fastballapi/__init__.py,sha256=_-bSwdL2ZRzjOVTXU1lDbdVQHLrVWKkoaX4y_CDmuXk,513
|
|
2
|
+
fastballapi/_core.py,sha256=F4yf3Wyd7iChpEHT7Khy1HbBQNUTmcg1k3AEOAqPJCE,10614
|
|
3
|
+
fastballapi/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
4
|
+
fastballapi/client.py,sha256=2eMu97IGLFbymYmGwbJcKCsXMFicmBTd1_qG3Jw7CIQ,26310
|
|
5
|
+
fastballapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
fastballapi-0.1.0.dist-info/METADATA,sha256=hjJ7KdMpBkyQhWHXyTEvMG0GdnOlDO5vZtmlv8T4O1c,6455
|
|
7
|
+
fastballapi-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
8
|
+
fastballapi-0.1.0.dist-info/licenses/LICENSE,sha256=V2IlG89uYfGvraoEIwvWnl8uOKLDrYbkQpolsKxJdZ8,1068
|
|
9
|
+
fastballapi-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 FastballAPI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|