Skip to content

SDKs

FrameWorks publishes SDKs for TypeScript, Go, and Python. All three are generated from the public GraphQL schema and the same operation documents, share one version, and pass the same conformance fixtures, so they behave the same way. Every example on this page is a file in the repository that CI compiles or type-checks (tsc, go vet, mypy).

Every public root query, mutation, and subscription that is not deprecated, and every field that takes arguments, has a generated typed method in each SDK. A namespace root such as analytics, whose data sits behind fields that take arguments, has no method of its own; those fields have theirs. Fields without arguments nested deeper than a method’s default selection are typed only through the TypeScript custom selections; in Go and Python you reach them with your own GraphQL document. The GraphQL schema reference lists the method names under each root field.

LanguageInstallNeedsRegistry and source
TypeScriptnpm install @livepeer-frameworks/api (plus graphql-ws for subscriptions)Node 22+ or a browsernpm · source
Gogo get github.com/Livepeer-FrameWorks/sdk-goGo 1.27+pkg.go.dev · source
Pythonpip install livepeer-frameworksPython 3.10+PyPI · source

Other languages use the GraphQL API directly and a Standard Webhooks library for webhooks.

TypeScript provides named methods through getSdk(client) from @livepeer-frameworks/api/operations (sdk.getStream({ id })), as well as typed documents (GetStreamDocument, passed to client.request). Go exposes a function per operation (frameworks.GetStream(ctx, client, id)), and Python exposes a method on its client (client.get_stream(id=...)). The operations come from two sources:

  • Default operations. One per public root field and one per field that takes arguments on a type reached from Query through single (non-list) objects. A nested operation selects the path from the root down to its field and takes every argument on that path as a variable: the streamAnalyticsSummary(streamId:) field under analytics.usage.streaming is GetStreamAnalyticsSummary(streamId, timeRange). A field that takes arguments on a type reachable only through a list, union, or interface is reached through node(id:) when the type implements Node: InfrastructureNode.metricsConnection is GetInfrastructureNodeMetricsConnection(id, page, timeRange), which selects node(id:) { ... on InfrastructureNode { metricsConnection } }.
  • Hand-written operations. Documents with a curated selection (for example CreateStream, ListStreams, ListPushTargets). A hand-written operation replaces the default operation of the field it addresses.

Names. A default query is Get<Field> and a default mutation or subscription is <Field>, in PascalCase; Python uses the snake_case form (get_stream_analytics_summary). A nested query is Get plus its field, or Get plus every field on its path when another query ends in a field of the same name (GetAnalyticsInfraServiceInstancesHealth). A query through node(id:) is Get plus the type and the field (GetInfrastructureNodeMetricsConnection). A name equal to a schema type gets the operation kind as suffix (CryptoTopupStatusMutation). Go subscriptions are Subscribe<Operation>.

Default selection. A default operation selects the returned type’s scalar and enum fields and its argument-free object, union, and interface fields to depth 2. Connections select edges { cursor node }, pageInfo, and totalCount. Unions and interfaces select __typename and each member’s fields. Fields that take arguments are never part of a selection; they have operations of their own. For anything deeper, see Custom selections.

Each domain page of the schema reference lists the operations of its root fields, with the TypeScript, Go, and Python names: Streams, Media and storage, Access and playback, Live subscriptions, Analytics, Webhooks, Incidents, Account and tenant, Billing and usage, Clusters and infrastructure, Platform, Skipper, and Support conversations.

Around the operations, each SDK has the same small runtime:

  • Authentication. Pass a developer token, or a function that returns the current one. The client reads it for every request, and a subscription reads it again for every reconnect.
  • Retries. Queries are retried on network errors and HTTP 408, 429, 500, 502, 503, and 504, with backoff and Retry-After. A mutation is retried only when the request provably never reached the server: the connection was refused, the host name did not resolve, or the gateway answered 429. A mutation that timed out, lost its connection after sending, or got a 5xx may have run, and the gateway does not deduplicate replayed mutations, so the client returns the error instead; check the outcome before you send it again. Paid mutations settled with x402 need an idempotency key, and the gateway deduplicates those by it.
  • Subscriptions. A connection the gateway closes with 4403 before acknowledging it has an invalid or expired token and fails with AuthenticationError. Any other close or network error, before or after the acknowledgement, reconnects with backoff; each acknowledged connection starts the reconnect budget again.
  • Typed errors. Every failure is a subclass of FrameWorksError with the same name in each language: NetworkError, AuthenticationError, PaymentRequiredError, RateLimitError, ServerError, HTTPError, ProtocolError, GraphQLError, SchemaMismatchError, ResultError, ServerTooOldError, UnsupportedOperationError, and UploadError.
  • Partial results. A response whose errors all sit below a root field that came back (a nullable field the server set to null, such as Stream.metrics for a token without analytics:read) returns its data, and the errors go to a handler: onPartialErrors on the client or per request in TypeScript, ClientOptions.OnPartialErrors or frameworks.WithPartialErrors(ctx, fn) in Go, and on_partial_errors= on the client or per call in Python. UNAUTHORIZED, RATE_LIMITED, document errors, errors without a path, and errors that null a root field still fail the call. See Partial results.
  • Scopes. The stream operations (ListStreams, GetStream, CreateStream, UpdateStream, RefreshStreamKey) need only streams:read and streams:write. Live state is in GetStreamMetrics and ListStreamMetrics, which need analytics:read. The stream key needs streams:write: CreateStream and RefreshStreamKey return it and GetStreamKey reads it; ListStreams, GetStream, and UpdateStream do not select it. See Token scopes.
  • Result unions. Most mutations return a union of the result and typed errors. expectResult returns the result or raises a ResultError naming the error member, its message, and the input field or resource it concerns.
  • Pagination. Iterators for the three list shapes: relay cursors (streamsConnection), offsets (storageArtifactsConnection), and page tokens (dvrChapters).
  • Server check. Before operations the client reads serverInfo, shared per URL and read again after five minutes. See Versions.
quickstart.ts
// Create a stream, then list every stream page by page.
import { createClient, expectResult, paginateRelay, ResultError } from "@livepeer-frameworks/api";
import { getSdk } from "@livepeer-frameworks/api/operations";
const client = createClient({
url: "https://bridge.example.com/graphql",
token: process.env.FRAMEWORKS_API_TOKEN,
});
const sdk = getSdk(client);
try {
const created = await sdk.createStream({
input: { name: "Launch stream", record: true },
});
const stream = expectResult(created.createStream, "Stream");
console.log(
`created ${stream.name}: stream key ${stream.streamKey}, playback ID ${stream.playbackId}`
);
} catch (err) {
if (err instanceof ResultError && err.typename === "ValidationError") {
console.error(`invalid ${err.field}: ${err.message}`);
}
throw err;
}
const streams = paginateRelay(
(page) => sdk.listStreams({ page }).then((data) => data.streamsConnection),
{ pageSize: 50 }
);
for await (const stream of streams) {
console.log(stream.name, stream.playbackId);
}

The upload helper calls createVodUpload, sends the file’s parts to the presigned URLs with bounded concurrency, retries a failed part, and completes the upload with the part ETags. If anything fails after the upload is created, it calls abortVodUpload before raising the error.

upload.ts
// Upload a local file as a VOD asset.
import { openAsBlob } from "node:fs";
import { createClient, uploadVod } from "@livepeer-frameworks/api";
const client = createClient({
url: "https://bridge.example.com/graphql",
token: process.env.FRAMEWORKS_API_TOKEN,
});
const file = await openAsBlob("./talk.mp4");
const asset = await uploadVod(client, file, {
filename: "talk.mp4",
contentType: "video/mp4",
title: "Conference talk",
concurrency: 4,
onProgress: (sent, total) => console.log(`${Math.round((sent / total) * 100)}%`),
});
console.log(`uploaded ${asset.id}; playback ID ${asset.playbackId}, status ${asset.status}`);

For content with a JWT playback policy, sign viewer tokens on your backend with the private key createSigningKey returned. The signer puts the key’s kid in the header and sets exp, iat, and optionally nbf, sub, aud, and your own claims, which must match the policy’s requiredAudience and requiredClaimsJson.

playbackToken.ts
// Sign a viewer token for content with a JWT playback policy, and resolve
// the viewer endpoint with it.
import {
createClient,
ResolveViewerEndpointDocument,
signPlaybackToken,
} from "@livepeer-frameworks/api";
const token = await signPlaybackToken({
privateKeyPem: process.env.FRAMEWORKS_SIGNING_KEY_PEM ?? "",
kid: process.env.FRAMEWORKS_SIGNING_KID ?? "",
expiresIn: 300,
subject: "viewer-42",
audience: "viewer",
claims: { tier: "pro" },
});
const client = createClient({ url: "https://bridge.example.com/graphql" });
const data = await client.request(
ResolveViewerEndpointDocument,
{ contentId: "k3v9x2m7q4w8", protocol: "HLS" },
{ playbackToken: token }
);
// The media URL itself also needs the token: append ?jwt=<token>.
console.log(`${data.resolveViewerEndpoint?.primary?.url}?jwt=${token}`);

Verification uses the official Standard Webhooks library of each language. Pass the raw request body: parsing and re-serializing the JSON changes the bytes that were signed. Parsing decodes the payload into a type generated from the event catalog. An event type the SDK does not know yet comes back as a raw event, not as an error.

webhooks.ts
// Receive FrameWorks webhooks: verify the signature on the raw body, then
// handle the typed event.
import { createServer } from "node:http";
import { createWebhookReceiver, WebhookVerificationError } from "@livepeer-frameworks/api/webhooks";
const receiver = createWebhookReceiver(process.env.FRAMEWORKS_WEBHOOK_SECRET ?? "");
createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => {
let event;
try {
event = receiver.receive(Buffer.concat(chunks), req.headers);
} catch (err) {
res.writeHead(err instanceof WebhookVerificationError ? 401 : 400).end();
return;
}
if (event.known) {
switch (event.type) {
case "stream.live":
console.log(`stream ${event.data.streamId} is live`);
break;
case "clip.ready":
console.log(
`clip ${event.data.artifact?.artifactId} ready, ${event.data.sizeBytes} bytes`
);
break;
}
} else {
console.log(`event type ${event.type} is newer than this SDK`);
}
res.writeHead(204).end();
});
}).listen(8080);

tenantEvents delivers the same events as webhooks over a WebSocket. When the gateway closes the connection before acknowledging it, the token is invalid or expired: the SDK raises AuthenticationError and does not reconnect. After any other drop it reconnects, reading the token again.

Every public subscription is generated the same way, with the same connection handling: in TypeScript, pass its document (LiveStreamEventsDocument) to the subscription client’s subscribe, which yields the document’s result type; in Go, call Subscribe<Operation> (SubscribeLiveStreamEvents), which returns an iter.Seq2 of the operation’s response type; in Python, iterate the async client’s method (live_stream_events). The sync Python client has no subscriptions, because ariadne-codegen generates them only for an async client.

subscription.ts
// Follow a stream's lifecycle and recording events as they happen.
import { TenantEventsDocument } from "@livepeer-frameworks/api";
import { createSubscriptionClient } from "@livepeer-frameworks/api/subscriptions";
const subscriptions = createSubscriptionClient({
url: "wss://bridge.example.com/graphql/ws",
// Read again for every connection, so a refreshed token is used after a reconnect.
token: () => process.env.FRAMEWORKS_API_TOKEN,
});
for await (const { tenantEvents: event } of subscriptions.subscribe(TenantEventsDocument, {
types: ["stream.live", "stream.idle", "recording.ready"],
})) {
switch (event.data.__typename) {
case "StreamLive":
console.log(`${event.data.streamId} went live at ${event.time}`);
break;
case "RecordingReady":
console.log(`recording ${event.data.artifact?.artifactId} is ready`);
break;
default:
console.log(event.type);
}
}

Every generated operation has a default selection. For fields beyond it:

  • TypeScript has typed selections over the whole public schema in @livepeer-frameworks/api/select, generated with Genql. createSelectClient wraps a client (and optionally a subscription client), so a selection runs with the same authentication, retries, typed errors, and server check as a generated document. __args passes arguments, on_<Type> selects a union member or interface implementation, and a selected field the schema does not have throws before anything is sent. The entry holds the schema’s type map (about 20 kB gzipped); the main entry does not load it. client.request also accepts a document string, with an untyped result.
  • Go takes your own genqlient documents written against schema.public.graphql: *frameworks.Client implements genqlient’s graphql.Client, and MakeRequest sends any query or mutation through the SDK runtime.
  • Python has no typed builder. ariadne-codegen’s custom operation builder covers only queries and mutations and returns untyped dictionaries with undecoded scalars, so send your own document through execute (or execute_ws on the async client for subscriptions).

Custom operation names are yours to choose. Operation-specific version checks apply only when the selected document matches a packaged operation’s canonical identity; changing its selection, arguments, or defaults makes it a custom document. The SDK still checks its minimum server version.

select.ts
// Select fields beyond the generated documents' default selection.
import { createClient } from "@livepeer-frameworks/api";
import { createSelectClient } from "@livepeer-frameworks/api/select";
import { createSubscriptionClient } from "@livepeer-frameworks/api/subscriptions";
const token = () => process.env.FRAMEWORKS_API_TOKEN;
const select = createSelectClient(
createClient({ url: "https://bridge.example.com/graphql", token }),
// Only needed for select.subscription.
{ subscriptions: createSubscriptionClient({ url: "wss://bridge.example.com/graphql/ws", token }) }
);
const { stream } = await select.query({
stream: {
__args: { id: "c3RyZWFtOjE" },
name: true,
metrics: { status: true, currentViewers: true, startedAt: true },
},
});
if (stream) {
console.log(
`${stream.name}: ${stream.metrics?.status}, ${stream.metrics?.currentViewers} viewers`
);
}
const { createClip } = await select.mutation({
createClip: {
__args: {
input: { streamId: "c3RyZWFtOjE", title: "Last 30 s", mode: "CLIP_NOW", duration: 30 },
},
__typename: true,
on_Clip: { id: true, status: true },
on_ValidationError: { message: true, field: true },
},
});
if (createClip.__typename === "Clip") {
console.log(`clip ${createClip.id} is ${createClip.status}`);
}
for await (const { tenantEvents: event } of select.subscription({
tenantEvents: {
__args: { types: ["stream.live"] },
time: true,
data: { __typename: true, on_StreamLive: { streamId: true } },
},
})) {
if (event.data.__typename === "StreamLive") {
console.log(`${event.data.streamId} went live at ${event.time}`);
}
}

The SDKs are 0.x until the platform reaches 1.0, and the three languages always share a version. Under 0.x each minor version is a line: 0.1, 0.2, and so on. A line names the oldest FrameWorks release it supports and supports every stable release from there on.

The current package version is 0.5.1, on SDK line 0.5. It supports FrameWorks v0.3.11 and later and includes 231 operation documents. Lines 0.1 and 0.2 are retired. The operation-method entry is optional: importing the main client does not load the method table.

Within a line, operations are only added; a breaking change starts a new minor line. The public schema follows the same rule from FrameWorks v0.3.11 on: a field, argument, enum value, or union member a client can use is deprecated before it is removed, and removed only after every supported line’s oldest release has it deprecated. A field marked Experimental in the schema reference is exempt until the release its badge names. Before the first operation, the client reads the server’s serverInfo:

  • A stable release older than the line’s minimum raises ServerTooOldError.
  • An operation added after the server’s release raises UnsupportedOperationError and is not sent.
  • Development builds and release candidates are not checked.
  • If the check itself fails, for example on a network error, the call goes ahead and the next call checks again. A v0.3.10 gateway answers an anonymous serverInfo with HTTP 402; that is no verdict either, and the client does not ask that gateway again for five minutes.
  • The answer is reused for five minutes. The client asks again at once before a cached answer would fail a call as too old, and when an operation fails schema validation; if the fresh answer fails the check, the call fails with that error instead.