DEV Community

Cover image for Validate Your Odds Stream Subscription Before Opening a WebSocket
E. Mitev
E. Mitev

Posted on

Validate Your Odds Stream Subscription Before Opening a WebSocket

A connection failure is a slow way to discover that we requested the wrong data.

Before opening an odds stream, we can check whether the requested bookmaker, sport and feed kind form a supported combination. This catches configuration mistakes before they become repeated connection attempts in our logs.

In this tutorial, we build a small preflight validator for PulseScore Stream API. It reads public capabilities, checks an explicit subscription list and prints the declaration only when every entry passes.

Discovery is different from authorization

PulseScore publishes a public capabilities endpoint:

GET https://api.pulsescore.net/api/stream/capabilities
Enter fullscreen mode Exit fullscreen mode

It does not require an API key. Its bookmaker entries include:

  • liveSports
  • prematchSports
  • racingSports

These fields tell us which combinations the service advertises.

They do not prove that our account can subscribe, that another process has left enough connection capacity, or that a particular board contains events right now. The authenticated connection remains authoritative.

Our preflight therefore answers one narrow question:

Does our requested combination appear in the capability document we just read?

Keep subscriptions explicit

Suppose we want live soccer and pre-match soccer from one source. We represent those as two declarations:

{
  "streams": [
    {
      "bookmaker": "bet365",
      "kind": "live",
      "sport": "soccer"
    },
    {
      "bookmaker": "bet365",
      "kind": "prematch",
      "sport": "soccer"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

This makes each requested combination visible, rather than relying on several lists and assuming every combination exists.

Explicit declarations also make review easier. A teammate can see exactly what a deployment intends to consume without mentally expanding a cross-product of bookmakers, sports and feed kinds.

Build the preflight validator

We need Python 3.10 or newer. The example uses only the standard library.

Save the following as preflight.py:

import json
from urllib.request import Request, urlopen

CAPABILITIES_URL = (
    "https://api.pulsescore.net/api/stream/capabilities"
)

FIELDS = {
    "live": "liveSports",
    "prematch": "prematchSports",
    "racing": "racingSports",
}


def validate(capabilities, requested):
    rows = capabilities.get("bookmakers")

    if not isinstance(rows, list):
        raise ValueError(
            "Capabilities must contain a bookmakers list"
        )

    books = {
        row["id"]: row
        for row in rows
        if isinstance(row, dict) and "id" in row
    }

    errors = []
    seen = set()

    for index, item in enumerate(requested, start=1):
        identity = tuple(
            item.get(key)
            for key in ("bookmaker", "kind", "sport")
        )
        bookmaker, kind, sport = identity

        if identity in seen:
            errors.append(
                f"Entry {index}: duplicate declaration {identity}"
            )
            continue

        seen.add(identity)

        if kind not in FIELDS:
            errors.append(
                f"Entry {index}: unsupported kind {kind!r}"
            )
            continue

        if bookmaker not in books:
            errors.append(
                f"Entry {index}: unknown bookmaker {bookmaker!r}"
            )
            continue

        offered = books[bookmaker].get(FIELDS[kind], [])

        if not isinstance(offered, list) or sport not in offered:
            errors.append(
                f"Entry {index}: {identity} is not advertised"
            )

    if not requested:
        errors.append("At least one stream is required")

    return errors


def fetch_capabilities():
    request = Request(
        CAPABILITIES_URL,
        headers={"Accept": "application/json"},
    )

    with urlopen(request, timeout=15) as response:
        document = json.load(response)

    if not isinstance(document, dict):
        raise ValueError("Expected a capabilities object")

    return document


if __name__ == "__main__":
    # Synthetic data for checking the validation logic locally.
    fixture = {
        "bookmakers": [
            {
                "id": "demo",
                "liveSports": ["soccer"],
                "prematchSports": ["tennis"],
                "racingSports": [],
            }
        ]
    }

    valid = [
        {
            "bookmaker": "demo",
            "kind": "live",
            "sport": "soccer",
        }
    ]

    assert validate(fixture, valid) == []
    assert validate(fixture, valid + valid)
    assert validate(
        fixture,
        [{**valid[0], "kind": "prematch"}],
    )
    assert validate(fixture, [])

    requested = [
        {
            "bookmaker": "bet365",
            "kind": "live",
            "sport": "soccer",
        },
        {
            "bookmaker": "bet365",
            "kind": "prematch",
            "sport": "soccer",
        },
    ]

    capabilities = fetch_capabilities()
    errors = validate(capabilities, requested)

    if errors:
        raise SystemExit(
            "Preflight failed:\n" + "\n".join(errors)
        )

    print(
        json.dumps(
            {"streams": requested},
            indent=2,
        )
    )
Enter fullscreen mode Exit fullscreen mode

Run it with:

python preflight.py
Enter fullscreen mode Exit fullscreen mode

The fixture assertions check the validation logic locally. The final section makes one public HTTPS request.

The script does not open a WebSocket or use an API key.

Understand what the checks cover

The synthetic fixture advertises live soccer and pre-match tennis for a fictional bookmaker named demo.

The assertions verify that:

  • An advertised combination passes.
  • A duplicate declaration produces an error.
  • Pre-match soccer fails when only pre-match tennis is advertised.
  • An empty subscription list produces an error.

The real request then validates our configured streams against the current capability document.

If both requested combinations are advertised, the script prints the JSON declaration. If either is unsupported, it exits with an explanation.

A successful result means that the combinations passed discovery validation. It does not mean the server has accepted a subscription.

Handle discovery failures explicitly

If the capabilities request fails or returns an unexpected document, the script exits instead of pretending that validation succeeded.

A production service might use a previously validated configuration during a temporary discovery failure. If we choose that behavior, we should track how old the discovery data is and make the fallback visible in our logs.

An unavailable discovery response and an unsupported subscription are different problems. Keeping them distinguishable helps us investigate the right cause.

What the validator leaves out

Our function checks a small, application-controlled subscription list. It is not a complete validator for arbitrary user input or every protocol option.

It does not validate:

  • League, market or date filters.
  • Account entitlements.
  • Available connection slots.
  • Other consumers running under the same account.

It also does not submit the declaration.

A broader deployment check can combine supported combinations from discovery with account limits and application-specific constraints on how much data a worker should process.

We should not turn a successful preflight into an authorization cache. Configuration and account state can change between discovery and connection.

Make configuration errors actionable

An error such as “entry 2 is not advertised” becomes more useful when it includes the requested bookmaker, kind and sport.

An entire authenticated URL containing an API key is not useful diagnostic context.

Keep discovery results and secret credentials separate. Store the validated declaration as normal configuration, then inject the API key at runtime when the stream client connects.

For a deployment pipeline, the same pure validate function can run against saved fixtures. A separate integration check can retrieve current capabilities.

This keeps deterministic configuration tests independent from a remote service's momentary availability.

Confirm the accepted subscription

After connecting, inspect the server's connected frame to confirm which streams were accepted.

Discovery helps us construct a supported request. The authenticated connection confirms the subscription, and the incoming board shows what data is currently available.

Keeping those steps separate gives us clearer failures and more useful logs before we expand to additional sources.

References

Top comments (0)