diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index b2b49ea..48d4750 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -33,4 +33,4 @@ jobs: 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" + python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py" "$GITHUB_WORKSPACE/tests/test_first_response.py" diff --git a/CHANGELOG.md b/CHANGELOG.md index de693d6..fbde690 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.3.5 - 2026-12-01 + +- Handle nested service errors on authenticated requests. Monthly credit exhaustion + raises `CreditLimitExceededError` and a historical lookback denial raises + `TierGatedError`. The client reads the service message and closes the HTTP response. +- Add a [six-case first-response guide](examples/first-response/) and an + [optional FastAPI coverage starter](examples/fastapi-coverage/). + ## 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. diff --git a/MANIFEST.in b/MANIFEST.in index 77ffdde..44988d7 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,4 @@ include CHANGELOG.md +include examples/first-response/README.md # The installed-package harness uses the repository's captured fixtures. prune tests diff --git a/README.md b/README.md index 76e8d95..8018c74 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,8 @@ except ParlayAPIError as error: print(type(error).__name__) ``` +[Diagnose six first-response outcomes](https://github.com/JacobiusMakes/parlay-api-python/tree/main/examples/first-response), including an exhausted allowance, a plan lookback, an empty selection and a stale market timestamp. + Practice choosing a next check with the [offline first-response rehearsal](https://github.com/JacobiusMakes/parlayapi-notebooks/tree/main/labs/response-triage). Its twelve invented cases distinguish authentication, access, rate-limit and diff --git a/examples/first-response/README.md b/examples/first-response/README.md new file mode 100644 index 0000000..d40761b --- /dev/null +++ b/examples/first-response/README.md @@ -0,0 +1,18 @@ +# Six checks after your first odds request + +Use the HTTP status and service error code to decide what to do with a failed request. For a successful request, inspect the actual selection and its timestamp before using the price. The examples below use invented records. The structured exception handling described here requires Python SDK 0.3.5. See the [official GitHub releases](https://github.com/JacobiusMakes/parlay-api-python/releases) for installable wheels. + +| What you observe | How to interpret it | Next action | +| --- | --- | --- | +| HTTP 401, `detail.error = UNAUTHORIZED` | Authentication failed. The Python client raises `InvalidAPIKeyError`. | Confirm the intended account key is supplied privately to the client. Keep it out of the URL, logs and support messages. | +| HTTP 403, `detail.error = HISTORICAL_LIMIT` | The chosen date falls outside the plan's historical lookback. The client raises `TierGatedError`. | Check the permitted lookback and whether archive rows exist for your sport and source. If an earlier date is essential, confirm both access and data availability before purchasing. | +| HTTP 403, `detail.error = OUT_OF_USAGE_CREDITS` or `CREDIT_LIMIT_REACHED` | The billing-period allowance is exhausted. The client raises `CreditLimitExceededError`. | Stop scheduled paid reads. Review usage and the reset information your account supplies before resuming. A rapid retry consumes time without replenishing the allowance. | +| A read times out before returning a status | Your client has no usable result. The server may have processed and charged the call. | Record the local UTC time, route template and timeout. Check usage. Decide whether another read fits your request and credit budgets. | +| HTTP 200 with an empty event list or no matching outcome | Your exact selection has no usable quote in this result. | Preserve the requested sport, fixture, source, period, market and outcome. Check sport and source availability. Change a filter only when the revised scope answers your original question. | +| HTTP 200 with a quote older than your cutoff | A successful response can contain an older market observation. | Compare your receipt time with the update time for that same selection or market. Treat an absent or timezone-free timestamp as unknown. Keep stale and unknown prices out of decisions that require freshness. | + +**Worked example.** You receive an NBA moneyline at 12:04:00 UTC. Its market last updated at 12:00:00 UTC. The observed age is 240 seconds. If your application requires a price no older than 90 seconds, withhold the quote. Game start time and a fresh timestamp on a different book cannot establish when this quote changed. + +A separate HTTP 429 means a request-rate limit was reached. Pause callers sharing the limit and respect a supplied `Retry-After`. For a support reproduction, retain the request ID if supplied, the UTC time, status, error code and route template. Keep the key, raw authorization headers and private response out of the report. + +[Check historical coverage](https://parlay-api.com/historical-coverage) · [Check current plan limits](https://parlay-api.com/pricing) · [Rehearse retry decisions offline](https://github.com/JacobiusMakes/parlayapi-notebooks/tree/main/labs/response-triage) · [Inspect an NBA response without a key](https://parlay-api.com/try) diff --git a/parlay_api/__init__.py b/parlay_api/__init__.py index 6141949..145f42c 100644 --- a/parlay_api/__init__.py +++ b/parlay_api/__init__.py @@ -55,7 +55,7 @@ """ from __future__ import annotations -__version__ = "0.3.4" +__version__ = "0.3.5" import json import os @@ -189,7 +189,8 @@ def _request(self, path: str, params: dict[str, Any] | None = None, ) return json.loads(resp.read()) except urllib.error.HTTPError as e: - body = e.read().decode("utf-8", errors="replace") + with e: + body = e.read().decode("utf-8", errors="replace") try: detail = json.loads(body) except json.JSONDecodeError: @@ -199,20 +200,33 @@ def _request(self, path: str, params: dict[str, Any] | None = None, raise ParlayAPIError(f"network error: {e}") def _handle_error(self, status: int, detail: Any) -> None: - msg = "" - if isinstance(detail, dict): - msg = detail.get("message") or detail.get("detail") or str(detail) + # FastAPI usually nests the machine code and message under "detail". + # Older gateways return a top-level message or plain text. + body = detail.get("detail", detail) if isinstance(detail, dict) else detail + if isinstance(body, dict): + code = body.get("error") + message = body.get("message") else: - msg = str(detail) + code = None + message = body + if not isinstance(message, str) and isinstance(detail, dict): + message = detail.get("message") + msg = message if isinstance(message, str) else "" if status == 401: raise InvalidAPIKeyError(msg or "Unauthorized") if status == 403: - if "credit" in msg.lower() or "limit" in msg.lower(): + if code in ("OUT_OF_USAGE_CREDITS", "CREDIT_LIMIT_REACHED"): + raise CreditLimitExceededError(msg or "Credit limit exceeded") + # Some older routes return a generic FORBIDDEN with a textual reason. + legacy_credit_reasons = ("credit limit exceeded", "monthly credit limit reached", + "insufficient credits", "out of credits", + "credit quota exceeded", "credits exhausted") + if code in (None, "FORBIDDEN") and msg.lower().startswith(legacy_credit_reasons): raise CreditLimitExceededError(msg) raise TierGatedError(msg or "Forbidden") if status == 429: raise RateLimitedError(msg or "Rate limited") - raise ParlayAPIError(f"HTTP {status}: {msg}") + raise ParlayAPIError(f"HTTP {status}: {msg}" if msg else f"HTTP {status}") @property def last_quota(self) -> Quota | None: diff --git a/pyproject.toml b/pyproject.toml index 8392518..d744814 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "parlay-api" -version = "0.3.4" +version = "0.3.5" description = "Python SDK for parlay-api.com with a no-key odds demo, CSV starter, and authenticated API client." readme = "README.md" authors = [ diff --git a/tests/test_first_response.py b/tests/test_first_response.py new file mode 100644 index 0000000..cda0b7f --- /dev/null +++ b/tests/test_first_response.py @@ -0,0 +1,62 @@ +"""Run the SDK's ordinary odds call against recorded HTTP shapes, without a network.""" +import io +import json +import unittest +import urllib.error +from unittest.mock import patch + +from parlay_api import ( + CreditLimitExceededError, InvalidAPIKeyError, ParlayAPI, ParlayAPIError, + RateLimitedError, TierGatedError, +) + + +class FirstResponseTests(unittest.TestCase): + def setUp(self): + self.client = ParlayAPI("fixture-key") + + def check_error(self, status, body, expected_class, expected_message): + raw = body if isinstance(body, bytes) else json.dumps(body).encode() + error = urllib.error.HTTPError("https://example.invalid/odds", status, + "fixture", {}, io.BytesIO(raw)) + with patch("urllib.request.urlopen", side_effect=error) as transport: + with self.assertRaises(expected_class) as raised: + self.client.odds("basketball_nba", markets="h2h") + self.assertIs(type(raised.exception), expected_class) + self.assertEqual(str(raised.exception), expected_message) + transport.assert_called_once() + + def test_structured_refusals(self): + cases = [ + (401, "UNAUTHORIZED", "Invalid key", InvalidAPIKeyError), + (403, "TIER_INSUFFICIENT", "This route requires a different tier", TierGatedError), + (403, "HISTORICAL_LIMIT", "This date exceeds your plan limit", TierGatedError), + (403, "OUT_OF_USAGE_CREDITS", "Monthly allowance reached", CreditLimitExceededError), + (403, "CREDIT_LIMIT_REACHED", "Budget exhausted", CreditLimitExceededError), + (429, "TOO_MANY_REQUESTS", "Requests per second exceeded", RateLimitedError), + ] + for status, code, message, expected in cases: + with self.subTest(code=code): + self.check_error(status, {"detail": {"error": code, "message": message, + "request_id": "fixture-only"}}, + expected, message) + + def test_legacy_shapes_and_missing_messages(self): + cases = [ + (403, {"message": "Credit limit exceeded for free tier"}, + CreditLimitExceededError, "Credit limit exceeded for free tier"), + (403, {"detail": "Insufficient credits"}, CreditLimitExceededError, "Insufficient credits"), + (403, {"detail": {"error": "FORBIDDEN", "message": "Credit limit exceeded"}}, + CreditLimitExceededError, "Credit limit exceeded"), + (403, {"detail": {"error": "OUT_OF_USAGE_CREDITS"}}, + CreditLimitExceededError, "Credit limit exceeded"), + (403, {"detail": {"error": "FORBIDDEN", "message": "Account cannot view credit history"}}, + TierGatedError, "Account cannot view credit history"), + (403, {"detail": {"message": ["unexpected detail"]}}, TierGatedError, "Forbidden"), + (401, b"Missing key", InvalidAPIKeyError, "Missing key"), + (503, {"detail": {"message": "Temporarily unavailable"}}, ParlayAPIError, + "HTTP 503: Temporarily unavailable"), + ] + for status, body, expected, message in cases: + with self.subTest(status=status, body=body): + self.check_error(status, body, expected, message) diff --git a/tests/test_installed_package.py b/tests/test_installed_package.py index 7ada1fd..e8137f4 100644 --- a/tests/test_installed_package.py +++ b/tests/test_installed_package.py @@ -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.4") + self.assertEqual(parlay_api.__version__, "0.3.5") self.assertEqual(importlib.metadata.version("parlay-api"), parlay_api.__version__) def test_installed_starter_is_exact_standalone_source(self):