Twitch Viewer Count API Returns stream: null: Offline, Absent or Zero?

Published October 28, 2026

One field decides whether your dashboard is right or quietly wrong:

"user": { "id": "19571641", "stream": null, "__typename": "User" }

That is what the Twitch data API returned for the ninja channel while it was offline, with HTTP 200 and status set to ok. It is not an error, not a missing channel and not a count of zero. Official Helix tutorials answer this with "empty data array means offline", which does not map onto this shape, and code built around the null goes wrong in two ways: it stores 0 viewers, or it treats the null as a failure and wakes someone up. This page separates the null from what it gets confused with, and ends with a poller that stores NULL plus a state column.

Three endpoints return the same null; only one says why

For the offline channel, three operations answered with an identical data.user object. They differ only in message.

Operationdata.usermessage
get-stream-detailsid, stream: null, __typenamechannel is currently offline
list-stream-tagsid, stream: null, __typenamenull
get-stream-viewer-countid, stream: null, __typenamenull

A tags or viewer-count client therefore sees a null stream with no explanation. The operation notes allow two readings: the channel is not broadcasting, or no stream payload was available at request time. Only the details route helps you tell them apart.

The request shape is the same for all three, with the channel login in the query:

https://api.opendata-api.com/api/project/twitch-scraper/get-stream-details?key=YOUR_API_KEY&channel=ninja

Replace the placeholder only in an authorized environment and redact the key from URL logs. No Twitch developer app or token is involved. Read the layers in order: HTTP status, then the gateway's code, then the status and message inside the payload. HTTP 200 alone proves nothing about the channel.

Settle whether the channel exists before reading any stream field

A null stream only means "not broadcasting" once you know the channel is real. Call get-channel-details once per login and keep data.user.id. The channel input is the login from the public URL (ninja), not the display title (Ninja); if you only have a name, search-channels returns candidates with their logins, about fifteen in the probe. The same profile call returns followers.totalCount, so you get the follower figure and the existence proof together.

Every stream response echoes data.user.id, even offline. Compare it with the id you stored. A match means the null is about the broadcast, not the account. A missing data.user, a missing id or a different id means you do not know the channel's state.

I did not probe a login that does not exist, so I cannot say what shape a miss takes. The decision below does not depend on it: a response without a matching id is neither live nor offline.

Sort every response into live, offline or unresolved

Signalliveofflineunresolved
HTTP and gateway codesuccesssuccessanything else
payload statusokoknot ok or absent
data.user.idmatches stored idmatches stored idmissing or different
data.user.streampopulated objectnullkey absent, or null with no offline message
details messagenot neededmentions offlinenone, or unrecognized

The last row is the tie-breaker. Tags and viewer count carry a null message even when the channel is offline, so when either returns a null stream, ask get-stream-details for the same channel and read its message. "Currently offline" settles it. A null stream with no such sentence stays unresolved.

The live column is deliberately thin. I only saw the offline branch, so I will not name fields inside a populated stream object, including the viewer-count key. Run the poller below against a channel that is on air and read the first live response yourself before mapping anything.

Write NULL, never 0, into the viewer snapshot table

This line is the bug:

# Wrong: an absent stream silently becomes a zero.
viewers = (user.get("stream") or {}).get(VIEWER_KEY, 0)

Suppose twelve hourly samples, two of them live at 800 and 1,000 viewers and ten offline. Stored as zeros, the average is 150. Stored as NULL, AVG(viewers) skips the offline rows and reports 900, the number you wanted. A "viewers under 50" alert has the same problem: with zeros it fires on every offline channel.

The opposite mistake is just as costly. A client that raises on a null stream pages someone for a normal offline channel, and a retry loop around it burns requests on an answer that will not change. Offline is a result; only a failed request or an unresolved state deserves a retry policy. A real zero, if it exists, would sit inside a populated stream object, so confirm that against a live reading.

Stream tags inherit the same absence

list-stream-tags returned the identical null, so "no tags" is not a property of the channel. It means there was no current stream to read tags from. Do not write an empty list over what you stored last time, and do not display older tags as current.

Tags also change between broadcasts and do not prove the channel is still live when you show them later. Keep the payload exactly as returned, with the poll timestamp. The tag field names were not observed offline, so store the raw stream object and map it once you have seen a live one.

What a single point-in-time reading cannot give you

Each response describes the channel at the moment of the request, and nothing is recorded. These operations offer no viewer history or time series, so the answer to "can I get historical Twitch viewer counts" is the table you build yourself. Poll spacing sets your resolution: a stream that starts and ends between two polls never appears.

Keep neighbouring numbers apart. followers.totalCount from the profile is not the live audience. list-channel-videos returns past broadcasts, each with a viewCount that counts video views, not concurrent viewers. Clips and videos continue with a numeric cursor returned for the same channel, twelve entries per page in the probe; search has no cursor.

A rejected platform key is a request failure, not a state of the channel. Log nothing about the channel and fix the key.

A poller that logs the state beside the number

Run this once per schedule tick from cron. Set PLATFORM_API_KEY in the environment, pass one or more logins, and read twitch_snapshots.db afterwards. Exceptions are logged by type only, because their text can include the key-bearing URL. VIEWER_KEY stays None until you have inspected a live raw_stream value, so viewers remain NULL rather than guessed.

import json
import os
import sqlite3
import sys
from datetime import datetime, timezone

import requests

BASE = "https://api.opendata-api.com/api/project/twitch-scraper"
KEY = os.environ["PLATFORM_API_KEY"]  # authorized key, never hard-coded
# Name of the viewer field inside the stream object; set it after reading a live response.
VIEWER_KEY = None


def call(operation, channel):
    """Return (user, message); (None, reason) when the response is unusable."""
    try:
        reply = requests.get(f"{BASE}/{operation}",
                             params={"key": KEY, "channel": channel}, timeout=30)
        reply.raise_for_status()
        body = reply.json()
    except (requests.RequestException, ValueError) as exc:
        return None, type(exc).__name__  # type only: the text may hold the key
    if not isinstance(body, dict) or str(body.get("code")) != "200":
        return None, "gateway"
    inner = body.get("data")
    if not isinstance(inner, dict) or inner.get("status") != "ok":
        return None, "status"
    user = (inner.get("data") or {}).get("user")
    return (user, inner.get("message")) if isinstance(user, dict) else (None, "no user")


def classify(user, channel_id, details_message):
    if user is None or str(user.get("id")) != channel_id or "stream" not in user:
        return "unresolved"
    stream = user["stream"]
    if isinstance(stream, dict) and stream:
        return "live"
    if stream is None and "offline" in (details_message or "").lower():
        return "offline"
    return "unresolved"


def sample(db, login):
    row = db.execute("SELECT channel_id FROM channels WHERE login = ?", (login,)).fetchone()
    if row is None:  # existence proof, once per login
        profile, why = call("get-channel-details", login)
        if profile is None or not profile.get("id"):
            return "unresolved", None, why, None
        db.execute("INSERT INTO channels VALUES (?, ?)", (login, str(profile["id"])))
        row = (str(profile["id"]),)
    user, message = call("get-stream-viewer-count", login)
    if user is not None and user.get("stream") is None:
        _, message = call("get-stream-details", login)  # the tie-breaker
    state = classify(user, row[0], message)
    viewers = user["stream"].get(VIEWER_KEY) if state == "live" and VIEWER_KEY else None
    viewers = viewers if isinstance(viewers, int) else None  # NULL, never 0
    raw = json.dumps(user["stream"]) if state == "live" else None
    return state, viewers, message, raw


def main(logins):
    db = sqlite3.connect("twitch_snapshots.db")
    db.execute("CREATE TABLE IF NOT EXISTS channels (login TEXT PRIMARY KEY, channel_id TEXT)")
    db.execute("CREATE TABLE IF NOT EXISTS snapshots (login TEXT, polled_at TEXT, "
               "state TEXT, viewers INTEGER, detail TEXT, raw_stream TEXT)")
    for login in logins:
        stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
        state, viewers, detail, raw = sample(db, login)
        db.execute("INSERT INTO snapshots VALUES (?, ?, ?, ?, ?, ?)",
                   (login, stamp, state, viewers, detail, raw))
        print(login, state, "NULL" if viewers is None else viewers)
    db.commit()


if __name__ == "__main__":
    main(sys.argv[1:])