Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .github/workflows/starter.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: Installed Python starter
on:
pull_request:
paths:
- 'examples/odds_workspace.py'
- 'examples/test_odds_workspace.py'
- 'parlay_api/**'
- 'tests/**'
- 'pyproject.toml'
- '.github/workflows/starter.yml'
push:
branches: [main]
paths:
- 'examples/odds_workspace.py'
- 'parlay_api/**'
- 'pyproject.toml'
permissions:
contents: read
jobs:
installed:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
python: ['3.9', '3.13']
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- run: python -m pip install . pytest
- name: Exercise the installed CLI outside the checkout
working-directory: ${{ runner.temp }}
run: |
python "$GITHUB_WORKSPACE/tests/test_installed_package.py"
python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py"
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## 0.3.4 - 2026-11-30

- Add an opt-in, keyless `--find-example` command. It checks up to three distinct public boards and advances only after a successful empty response. Existing single-sport and authenticated commands retain their request behavior.
- Add a single-sport first-run command and explain how to read an empty CSV.

## 0.3.3 - 2026-09-05

- Bundle the existing standalone odds workspace starter in the installed package.
Expand Down
26 changes: 19 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,34 @@
Python 3.9+ SDK for [ParlayAPI](https://parlay-api.com). The default install has
no runtime dependencies and includes a one-request odds-to-CSV starter.

## First response, no key
## Get your first CSV without a key

Install the SDK, then choose a sport for a single public request. For example:

```bash
python -m pip install --upgrade parlay-api
python -m parlay_api
python -m parlay_api --sport basketball_nba > odds.csv
```

The second command requests the public MLB demo once and prints CSV to your
terminal. It ignores any API key in your environment. Save the response or
choose another supported sport:
Open `odds.csv` and look for an event, bookmaker, outcome and price. A header
alone means there were no usable rows in this response. You can also
[inspect the NBA demo in your browser](https://parlay-api.com/v1/try/basketball_nba/odds).

The [0.3.4 release](https://github.com/JacobiusMakes/parlay-api-python/releases/tag/v0.3.4)
adds a command for developers who want a sample from any available board:

```bash
python -m parlay_api --sport americanfootball_nfl > odds.csv
python -m parlay_api --help
python -m parlay_api --find-example > odds.csv
```

It checks NBA, MLB and NHL in order and moves on only when the previous
board returned zero events. It stops on a nonempty board or an error, including
a rate limit. Diagnostics go to stderr and the CSV goes to stdout. With no
arguments the CLI still makes one MLB request. Both demo modes ignore any API
key in the environment.

When your example has the fields you need, [create an account for your own API key](https://parlay-api.com/signup?utm_source=python_sdk&utm_medium=quickstart&utm_campaign=first_csv). Check account access and cost for the sport and market you plan to request.

The demo returns at most the first five US moneyline events, with a shared limit
of 60 requests per hour per IP. Supported demo sports are `baseball_mlb`,
`basketball_nba`, `americanfootball_nfl`, `icehockey_nhl`, `soccer_epl` and
Expand Down
52 changes: 41 additions & 11 deletions examples/odds_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""Export one ParlayAPI odds response to CSV. Python 3.9+, standard library only.

After installing parlay-api, the same starter runs as:
python -m parlay_api
python -m parlay_api --find-example
python -m parlay_api --full --markets h2h,spreads,totals > odds.csv

No key or package installation is needed for the default demo request:
Expand Down Expand Up @@ -291,7 +291,8 @@ def parse_args(argv=None, prog=None):
parser = argparse.ArgumentParser(
prog=prog, description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
examples = parser.add_mutually_exclusive_group()
examples.add_argument(
"--sport",
choices=sorted(SPORTS),
default="baseball_mlb",
Expand All @@ -314,7 +315,14 @@ def parse_args(argv=None, prog=None):
default=None,
help="full mode: include commenced games; enabled by default; --no-include-live requests pregame",
)
examples.add_argument(
"--find-example",
action="store_true",
help="try up to three distinct public demo boards, continuing only after an empty board",
)
args = parser.parse_args(argv)
if args.full and args.find_example:
parser.error("--find-example uses public demo boards only")
if not args.full and (args.markets != ["h2h"] or args.include_live is not None):
parser.error(
"market and live filters require --full. The demo always returns US moneyline; it accepts no live filter."
Expand Down Expand Up @@ -363,6 +371,17 @@ def validate_response(payload, args):
return rows, issues


def fetch_payload(args, headers):
request = Request(request_url(args), headers=headers)
with build_opener(NoRedirect()).open(request, timeout=30) as response:
if response.status != 200:
raise ValueError("Expected HTTP 200")
body = response.read(10_000_001)
if len(body) > 10_000_000:
raise ValueError("Response exceeds the 10 MB safety limit")
return json.loads(body)


def main(argv=None, prog=None):
args = parse_args(argv, prog=prog)
headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
Expand All @@ -384,16 +403,19 @@ def main(argv=None, prog=None):
"Demo: first five US moneyline events; shared limit 60 requests/hour per IP. PARLAY_API_KEY is ignored.",
file=sys.stderr,
)
request = Request(request_url(args), headers=headers)
sports = ("basketball_nba", "baseball_mlb", "icehockey_nhl") if args.find_example else (args.sport,)
try:
with build_opener(NoRedirect()).open(request, timeout=30) as response:
if response.status != 200:
raise ValueError("Expected HTTP 200")
body = response.read(10_000_001)
if len(body) > 10_000_000:
raise ValueError("Response exceeds the 10 MB safety limit")
payload = json.loads(body)
rows, issues = validate_response(payload, args)
for sport in sports:
args.sport = sport
payload = fetch_payload(args, headers)
rows, issues = validate_response(payload, args)
if not args.find_example:
break
if payload.get("sport_key", sport) != sport:
raise ResponseContractError("demo wrapper does not match the requested sport")
print(f"{sport}: {len(payload['events'])} events, {len(rows)} usable rows.", file=sys.stderr)
if payload["events"]:
break
except HTTPError as error:
retry = error.headers.get("Retry-After") if error.headers else None
suffix = " Retry-After: " + str(retry)[:80] if error.code == 429 and retry else ""
Expand Down Expand Up @@ -432,11 +454,19 @@ def main(argv=None, prog=None):
)
for issue in issues[:25]:
print(json.dumps(issue, ensure_ascii=True), file=sys.stderr)
if rows and args.find_example:
print(
"To request your own sport and markets, create an account for an API key: "
"https://parlay-api.com/signup?utm_source=python_sdk&utm_medium=cli&utm_campaign=first_csv",
file=sys.stderr,
)
if not rows:
print(
"No usable rows returned. This response does not establish coverage or explain why data is absent.",
file=sys.stderr,
)
if not args.full and not args.find_example:
print("For a sample from another sport, run again with --find-example.", file=sys.stderr)
return 0


Expand Down
38 changes: 38 additions & 0 deletions examples/test_odds_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,44 @@ def test_csv_formula_escaping_preserves_numeric_prices(self):
self.assertEqual(exported[1]["outcome_name"], "'\t@SUM(A1)")
self.assertEqual(exported[1]["price"], "-138")

def test_find_example_advances_only_after_an_empty_board(self):
empty = FakeResponse(b'{"demo":true,"sport_key":"basketball_nba","events":[]}')
sample = FakeResponse(json.dumps(CAPTURE).encode())
code, stdout, stderr, opener = self.run_cli(
["--find-example"], error=[empty, sample], environ={"PARLAY_API_KEY": "offline-only"}
)
self.assertEqual(code, 0)
self.assertTrue(list(csv.DictReader(io.StringIO(stdout))))
requests = [call.args[0] for call in opener.open.call_args_list]
self.assertEqual([r.full_url.split("/")[-2] for r in requests], ["basketball_nba", "baseball_mlb"])
self.assertTrue(all(not r.has_header("X-api-key") for r in requests))
self.assertIn("basketball_nba: 0 events", stderr)
self.assertIn("utm_medium=cli", stderr)
self.assertNotIn("utm_medium=cli", stdout)

def test_find_example_stops_on_empty_limit_or_error(self):
empty = b'{"demo":true,"events":[]}'
code, stdout, _, opener = self.run_cli(["--find-example"], body=empty)
self.assertEqual((code, opener.open.call_count), (0, 3))
self.assertEqual(list(csv.DictReader(io.StringIO(stdout))), [])
for body in (b'{}', b'{"demo":true,"sport_key":"soccer_epl","events":[]}'):
code, stdout, _, opener = self.run_cli(["--find-example"], body=body)
self.assertEqual((code, stdout, opener.open.call_count), (1, "", 1))
rate_limit = HTTPError("https://example.invalid", 429, "", {}, io.BytesIO(b""))
code, stdout, _, opener = self.run_cli(["--find-example"], error=rate_limit)
self.assertEqual((code, stdout, opener.open.call_count), (1, "", 1))

def test_find_example_preserves_nonempty_board_diagnostics(self):
body = b'{"demo":true,"events":[{"sport_key":"basketball_nba"}]}'
code, stdout, stderr, opener = self.run_cli(["--find-example"], body=body)
self.assertEqual((code, opener.open.call_count), (0, 1))
self.assertIn("1 events, 0 usable rows", stderr)
self.assertNotIn("utm_medium=cli", stderr)
self.assertEqual(list(csv.DictReader(io.StringIO(stdout))), [])
for flags in (["--full"], ["--sport", "soccer_epl"]):
with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
starter.parse_args(["--find-example"] + flags)

def test_empty_success_is_csv_header_and_explicit_diagnostic(self):
for args, body in (([], b'{"demo":true,"events":[]}'), (["--full"], b"[]")):
code, stdout, stderr, _ = self.run_cli(
Expand Down
2 changes: 1 addition & 1 deletion parlay_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"""
from __future__ import annotations

__version__ = "0.3.3"
__version__ = "0.3.4"

import json
import os
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "parlay-api"
version = "0.3.3"
version = "0.3.4"
description = "Python SDK for parlay-api.com with a no-key odds demo, CSV starter, and authenticated API client."
readme = "README.md"
authors = [
Expand Down
2 changes: 1 addition & 1 deletion tests/test_installed_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def test_imports_are_installed_outside_checkout(self):
self.assertNotIn(ROOT, Path(module.__file__).resolve().parents)

def test_version_matches_distribution(self):
self.assertEqual(parlay_api.__version__, "0.3.3")
self.assertEqual(parlay_api.__version__, "0.3.4")
self.assertEqual(importlib.metadata.version("parlay-api"), parlay_api.__version__)

def test_installed_starter_is_exact_standalone_source(self):
Expand Down
Loading