diff --git a/.github/workflows/fastapi-example.yml b/.github/workflows/fastapi-example.yml new file mode 100644 index 0000000..f9919fe --- /dev/null +++ b/.github/workflows/fastapi-example.yml @@ -0,0 +1,28 @@ +name: FastAPI coverage example +on: + pull_request: + paths: + - 'examples/fastapi-coverage/**' + - 'parlay_api/**' + - '.github/workflows/fastapi-example.yml' + push: + branches: [main] + paths: + - 'examples/fastapi-coverage/**' + - 'parlay_api/**' + - '.github/workflows/fastapi-example.yml' +permissions: + contents: read +jobs: + coverage-example: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.12' + - run: python -m pip install . -r examples/fastapi-coverage/requirements.txt pytest httpx2 + - run: python -m pytest -q examples/fastapi-coverage/test_app.py diff --git a/README.md b/README.md index f8e2143..76e8d95 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,13 @@ and invalid outcomes are excluded with diagnostics on stderr. Missing timestamps stay empty; timestamps are not freshness guarantees. The starter makes no rankings or profit claims, and has no automatic retries, polling or key storage. +### Serve a private FastAPI snapshot + +[Run the FastAPI coverage starter](examples/fastapi-coverage/) to read game and +source counts from a local endpoint. Start with fictional NBA data, then use +your server-side key for a single coverage snapshot. Refreshing the local +endpoint reuses that snapshot. + ## Plan a request schedule before polling Use the free [API workload planner](https://parlay-api.com/tools/api-workload?utm_source=github&utm_medium=sdk_readme&utm_campaign=parlay-api-python) diff --git a/examples/fastapi-coverage/README.md b/examples/fastapi-coverage/README.md new file mode 100644 index 0000000..4719897 --- /dev/null +++ b/examples/fastapi-coverage/README.md @@ -0,0 +1,36 @@ +# Serve a private coverage snapshot with FastAPI + +Read one NBA coverage result from a local HTTP endpoint. The starter runs with fictional counts first, so you can wire a consumer and test an empty board before connecting an account. It binds to the loopback interface and keeps one snapshot in process memory. + +## Run the fictional example + +With Python 3.12 and a checkout of this repository, run these commands from the repository root. + +```sh +python3.12 -m venv .venv +. .venv/bin/activate +python -m pip install . -r examples/fastapi-coverage/requirements.txt +python examples/fastapi-coverage/app.py +``` + +In a second terminal, read the snapshot. + +```sh +curl --fail http://127.0.0.1:8080/coverage +``` + +The response identifies its mode as `fictional` and reports three distinct games across two contributing sources. Its fixed January observation time belongs to the sample. Refreshing the URL reads the same snapshot. Press Ctrl-C in the first terminal to stop the server. + +## Read your account's coverage once + +Use this mode for a private evaluation after checking the sport, route access and permitted use for your account. The MIT license covers the starter code. Consult your API agreement before exposing data to other users. [Account and plan details](https://parlay-api.com/pricing) + +Supply your own `PARLAY_API_KEY` through the server process environment and start the example with `--account`. Keep the key out of URLs and client code. Run from the same virtual environment. [Get an account key](https://parlay-api.com/signup?utm_source=github&utm_medium=fastapi_example&utm_campaign=fastapi_coverage) + +```sh +python examples/fastapi-coverage/app.py --account +``` + +The installed repository SDK makes one authenticated GET to `/v1/sports/basketball_nba/odds/coverage`, requesting US pregame moneylines with a 900-second freshness threshold. The adapter exposes the report's observation time and its two aggregate counts. Read `distinct_games` across sources as the number of distinct games covered in that response. A game appearing at two sources counts once. Zero is a valid result. + +Every local GET reads the startup snapshot. Check `observed_at` before using a result. Restarting in account mode requests a new snapshot. A denied request, rate limit, timeout or unexpected response ends startup. The starter has no scheduled refresh. [SDK coverage request and filters](../../README.md#check-game-line-coverage-before-spending-credits) diff --git a/examples/fastapi-coverage/app.py b/examples/fastapi-coverage/app.py new file mode 100644 index 0000000..54a7f02 --- /dev/null +++ b/examples/fastapi-coverage/app.py @@ -0,0 +1,102 @@ +"""Serve a single private coverage snapshot on the loopback interface.""" + +import argparse +import os +from datetime import datetime + +import uvicorn +from fastapi import FastAPI, Response +from starlette.middleware.trustedhost import TrustedHostMiddleware + +from parlay_api import ( + CreditLimitExceededError, + InvalidAPIKeyError, + ParlayAPI, + ParlayAPIError, + RateLimitedError, + TierGatedError, +) + +SPORT = "basketball_nba" +SAMPLE = { + "sport_key": SPORT, + "regions": ["us"], + "markets": ["h2h"], + "serves": "pregame", + "fresh_within_seconds": 900, + "as_of": "2026-01-14T12:00:00+00:00", + "sources_count": 2, + "total_games_covered": 3, +} + + +def summarize(report, mode): + for field in ("sport_key", "regions", "markets", "serves", "fresh_within_seconds"): + if report[field] != SAMPLE[field]: + raise ValueError("Unexpected coverage scope") + fields = ("sources_count", "total_games_covered") + if any(type(report[k]) is not int or report[k] < 0 for k in fields): + raise ValueError("Expected nonnegative coverage counts") + observed = datetime.fromisoformat(report["as_of"].replace("Z", "+00:00")) + if observed.tzinfo is None: + raise ValueError("Missing observation timezone") + return { + "mode": mode, + "sport_key": SPORT, + "regions": ["us"], + "market": "h2h", + "scope": "pregame", + "fresh_within_seconds": 900, + "observed_at": observed.isoformat(), + "sources_with_games": report["sources_count"], + "distinct_games": report["total_games_covered"], + } + + +def make_app(snapshot): + app = FastAPI(title="Private NBA coverage snapshot", docs_url=None, redoc_url=None, + openapi_url=None) + app.add_middleware(TrustedHostMiddleware, allowed_hosts=["localhost", "127.0.0.1"]) + + @app.get("/coverage") + def coverage(response: Response): + response.headers["Cache-Control"] = "no-store" + return snapshot + + return app + + +def load_snapshot(use_account): + if not use_account: + return summarize(SAMPLE, "fictional") + key = os.environ.get("PARLAY_API_KEY", "").strip() + if not key: + raise InvalidAPIKeyError("Account mode needs a server-side key") + report = ParlayAPI(api_key=key, timeout=10).odds_coverage( + SPORT, regions="us", markets="h2h", fresh_within_seconds=900 + ) + return summarize(report, "account") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--account", action="store_true", help="make one private coverage request") + parser.add_argument("--port", type=int, default=8080) + args = parser.parse_args() + if not 1 <= args.port <= 65535: + parser.error("Choose a port from 1 to 65535.") + try: + snapshot = load_snapshot(args.account) + except InvalidAPIKeyError: + parser.exit(1, "Check the private PARLAY_API_KEY in the server environment.\n") + except TierGatedError: + parser.exit(1, "The account was denied access. Check the route and plan.\n") + except CreditLimitExceededError: + parser.exit(1, "The account reached a usage limit. Check its allowance.\n") + except RateLimitedError: + parser.exit(1, "The service rate-limited this request. Wait before starting again.\n") + except (ParlayAPIError, OSError): + parser.exit(1, "The coverage request failed. Check service availability.\n") + except (ValueError, KeyError, TypeError, AttributeError): + parser.exit(1, "The coverage response had an unexpected scope, clock or count.\n") + uvicorn.run(make_app(snapshot), host="127.0.0.1", port=args.port, access_log=False) diff --git a/examples/fastapi-coverage/requirements.txt b/examples/fastapi-coverage/requirements.txt new file mode 100644 index 0000000..a085be1 --- /dev/null +++ b/examples/fastapi-coverage/requirements.txt @@ -0,0 +1,2 @@ +fastapi==0.165.0 +uvicorn==0.55.0 diff --git a/examples/fastapi-coverage/test_app.py b/examples/fastapi-coverage/test_app.py new file mode 100644 index 0000000..204e0ea --- /dev/null +++ b/examples/fastapi-coverage/test_app.py @@ -0,0 +1,67 @@ +from unittest.mock import patch + +import pytest +from fastapi.testclient import TestClient + +from app import SAMPLE, load_snapshot, make_app, summarize +from parlay_api import CreditLimitExceededError, InvalidAPIKeyError, RateLimitedError + + +def test_offline_example_works_with_no_upstream_or_key(monkeypatch): + monkeypatch.setenv("PARLAY_API_KEY", "dummy-private-value") + with patch("app.ParlayAPI", side_effect=AssertionError("unexpected SDK call")): + client = TestClient(make_app(load_snapshot(False)), base_url="http://localhost") + first = client.get("/coverage") + assert first.status_code == 200 + assert first.json()["mode"] == "fictional" + assert first.json()["distinct_games"] == 3 + assert first.headers["cache-control"] == "no-store" + assert client.get("/coverage").json() == first.json() + assert "dummy-private-value" not in first.text + assert client.get("/coverage", headers={"Host": "other.example"}).status_code == 400 + + +def test_account_reads_once_and_excludes_other_fields(monkeypatch): + monkeypatch.setenv("PARLAY_API_KEY", "dummy-key") + with patch("app.ParlayAPI") as sdk: + sdk.return_value.odds_coverage.return_value = dict( + SAMPLE, total_games_covered=0, sources_count=0, private_note="unpublished" + ) + client = TestClient(make_app(load_snapshot(True)), base_url="http://localhost") + for _ in range(3): + response = client.get("/coverage") + assert response.json()["mode"] == "account" + assert response.json()["distinct_games"] == 0 + assert "unpublished" not in response.text + assert "dummy-key" not in response.text + sdk.assert_called_once_with(api_key="dummy-key", timeout=10) + sdk.return_value.odds_coverage.assert_called_once_with( + "basketball_nba", regions="us", markets="h2h", fresh_within_seconds=900 + ) + + +@pytest.mark.parametrize("error", [CreditLimitExceededError, RateLimitedError]) +def test_denial_stops_after_one_attempt(monkeypatch, error): + monkeypatch.setenv("PARLAY_API_KEY", "dummy-key") + with patch("app.ParlayAPI") as sdk: + sdk.return_value.odds_coverage.side_effect = error("upstream detail") + with pytest.raises(error): + load_snapshot(True) + sdk.return_value.odds_coverage.assert_called_once() + + +@pytest.mark.parametrize("change", [ + {"total_games_covered": True}, {"sources_count": -2}, + {"sport_key": "soccer_epl"}, {"regions": ["uk"]}, {"markets": ["totals"]}, + {"serves": "both"}, {"fresh_within_seconds": 60}, {"as_of": "2026-01-14"}, +]) +def test_wrong_scope_counts_and_clocks_fail(change): + with pytest.raises(ValueError): + summarize(dict(SAMPLE, **change), "account") + + +def test_missing_key_stays_offline(monkeypatch): + monkeypatch.delenv("PARLAY_API_KEY", raising=False) + with patch("app.ParlayAPI", side_effect=AssertionError("unexpected SDK call")): + with pytest.raises(InvalidAPIKeyError, match="server-side key"): + load_snapshot(True)