Typescript SDK

Learn how to use the FastPix Typescript SDK to upload media, stream live, manage playback, and handle media operations in Typescript applications.

The FastPix TypeScript SDK makes it easier to integrate with the FastPix platform. Designed for Node.js (version 18 or later), it offers a type-safe, developer-friendly interface for secure and efficient interaction with the FastPix API. With it, you can seamlessly manage media uploads, live streams, on-demand content, playlists, video analytics, and signing keys for secure access and token management.




Let’s talk features:

Media API

  • Upload Media: Easily upload media files from local devices or external URLs.
  • Manage Media: List, retrieve, update, and delete media assets with minimal effort.
  • Playback IDs: Create and manage playback IDs for flexible, secure access to your content.
  • Advanced Media Tools: Generate video summaries, chapters, named entities, subtitles, and run content moderation.
  • Playlist Management: Build and manage playlists, add or remove media, and control playback order.
  • DRM Support: Configure and manage Digital Rights Management for secure content protection.

Live API

  • Create & Manage Live Streams: Quickly create, update, list, and delete live streams.
  • Access Control: Use playback IDs to securely manage viewer access.
  • Stream Controls: Enable, disable, or end streams with precise control.
  • Simulcast Support: Stream to multiple platforms simultaneously for wider reach.

Signing Keys

  • Generate Signing Keys: Create keys to enable secure, token-based access.
  • Retrieve & Manage Keys: List, fetch details, and manage individual signing keys.
  • Access Control Maintenance: Delete or revoke keys to maintain security and control.

Video Data API

  • View & Analytics: Track video views, retrieve detailed view data, and identify top-performing content.
  • Concurrent Viewers: Access time-series insights for both live and on-demand streams.
  • Custom Reporting: Filter by dimensions, generate breakdowns, and compare datasets for deeper insights.
  • Error Diagnostics: Retrieve logs and monitor errors to ensure reliability and performance.

For complete usage instructions, see the FastPix API Reference.


Prerequisites

Before you start using the FastPix Node.js SDK, make sure you have the following:

  1. To authenticate with the FastPix APIs, you'll need an Access Token and a Secret Key. You can generate these credentials by following the steps in the Authentication with Access Tokens guide.
  2. Node.js (version >= 18): This SDK is compatible with Node.js version 18 or higher on the server side.

Installation:

The FastPix TypeScript SDK is distributed as an NPM package and works with all popular Node.js package managers. Ensure you’re using Node.js v18 or later before installation.

Using npm:

npm install @fastpix/fastpix-node

Using pnpm:

pnpm add @fastpix/fastpix-node

Using Bun:

bun add @fastpix/fastpix-node

Using Yarn:

yarn add @fastpix/fastpix-node

Requirements

For supported JavaScript runtimes, see RUNTIMES.md.

This package provides both CommonJS (CJS) and ES Modules (ESM) builds, so you can use it in projects with either module system.


Import the SDK

import { Fastpix } from "@fastpix/fastpix-node"; 

Initialization

Initialize FastPix Node.js SDK with AccessToken and SecretKey.

import { Fastpix } from "@fastpix/fastpix-node"; 

const fastpix = new Fastpix({ 
  security: { 
  username: "your-access-token", 
  password: "secret-key", 
	}, 
}); 

Example usage:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  security: {
    username: "your-access-token",
    password: "secret-key",
  },
});

async function run() {
  const result = await fastpix.inputVideo.createMedia({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.io/sample.mp4",
      },
    ],
    metadata: {
      key1: "value1",
    },
    accessPolicy: "public",
  });

  console.log(result);
}

run();

Available Resources and Operations

The FastPix SDK provides resources and methods to manage media workflows, live streaming, analytics, DRM, and secure access. Below, resources are categorized by their primary use for easier navigation.


1. Video On-Demand

Resources for uploading, managing, and enhancing on-demand videos.


Input Video

Upload and create media assets from URLs or local files.

MethodDescriptionHTTP Request
createMediaCreate media from a remote URLPOST /on-demand
directUploadVideoMediaUpload video directly from your devicePOST /on-demand/upload

In-Video AI Features

Enhance videos with AI-powered analysis.

MethodDescriptionHTTP Request
updateMediaSummaryGenerate video summaryPATCH /on-demand/{mediaId}/summary
updateMediaChaptersGenerate video chaptersPATCH /on-demand/{mediaId}/chapters
updateMediaNamedEntitiesGenerate named entitiesPATCH /on-demand/{mediaId}/named-entities
updateMediaModerationEnable video moderationPATCH /on-demand/{mediaId}/moderation

Manage Videos

Full lifecycle management of uploaded media.

MethodDescriptionHTTP Request
listMediaGet list of all mediaGET /on-demand
listLiveClipsGet all clips of a live streamGET /on-demand/{livestreamId}/live-clips
getMediaGet a media by IDGET /on-demand/{mediaId}
updatedMediaUpdate a media by IDPATCH /on-demand/{mediaId}
deleteMediaDelete a media by IDDELETE /on-demand/{mediaId}
addMediaTrackAdd audio / subtitle trackPOST /on-demand/{mediaId}/tracks
cancelUploadCancel ongoing uploadPOST /on-demand/{uploadId}/cancel
updateMediaTrackUpdate audio / subtitle trackPATCH /on-demand/{mediaId}/tracks/{trackId}
deleteMediaTrackDelete audio / subtitle trackDELETE /on-demand/{mediaId}/tracks/{trackId}
generateSubtitleTrackGenerate track subtitlePOST /on-demand/{mediaId}/tracks/generate
updatedSourceAccessUpdate the source access of mediaPATCH /on-demand/{mediaId}/source-access
updatedMp4SupportUpdate the mp4Support of mediaPATCH /on-demand/{mediaId}/update-mp4Support
retrieveMediaInputInfoGet info of media inputsGET /on-demand/{mediaId}/input-info
listUploadsGet all unused upload URLsGET /on-demand/uploads
getMediaClipsGet all clips of a mediaGET /on-demand/{mediaId}/clips

Playback

Manage secure playback access.

MethodDescriptionHTTP Request
createMediaPlaybackIdCreate a playback IDPOST /on-demand/{mediaId}/playback-ids
deleteMediaPlaybackIdDelete a playback IDDELETE /on-demand/{mediaId}/playback-ids/{playbackId}
getPlaybackIdGet a playback IDGET /on-demand/{mediaId}/playback-ids/{playbackId}

Playlist

Organize videos into playlists.

MethodDescriptionHTTP Request
createAPlaylistCreate a new playlistPOST /on-demand/playlists
getAllPlaylistsGet all playlistsGET /on-demand/playlists
getPlaylistByIdGet a playlist by IDGET /on-demand/playlists/{playlistId}
updateAPlaylistUpdate a playlist by IDPATCH /on-demand/playlists/{playlistId}
deleteAPlaylistDelete a playlist by IDDELETE /on-demand/playlists/{playlistId}
addMediaToPlaylistAdd media to a playlist by IDPATCH /on-demand/playlists/{playlistId}/media
changeMediaOrderInPlaylistChange media order in a playlistPUT /on-demand/playlists/{playlistId}/media
deleteMediaFromPlaylistDelete media from a playlist by IDDELETE /on-demand/playlists/{playlistId}/media

DRM Configurations

Manage DRM for protected content.

MethodDescriptionHTTP Request
getDrmConfigurationGet list of DRM configuration IDsGET /on-demand/drm-configurations
getDrmConfigurationByIdGet DRM configuration by IDGET /on-demand/drm-configurations/{drmConfigurationId}


2. Live Stream

Resources for live streaming, simulcasting, and playback.


Start Live Stream

MethodDescriptionHTTP Request
createNewStreamCreate a new streamPOST /live/streams

Simulcast Stream

MethodDescriptionHTTP Request
createSimulcastOfStreamCreate a simulcastPOST /live/streams/{streamId}/simulcast
deleteSimulcastOfStreamDelete a simulcastDELETE /live/streams/{streamId}/simulcast/{simulcastId}
getSpecificSimulcastOfStreamGet a specific simulcastGET /live/streams/{streamId}/simulcast/{simulcastId}
updateSpecificSimulcastOfStreamUpdate a simulcastPATCH /live/streams/{streamId}/simulcast/{simulcastId}

Manage Live Stream

MethodDescriptionHTTP Request
getAllStreamsGet all live streamsGET /live/streams
getLiveStreamViewerCountByIdGet stream views by IDGET /live/streams/{streamId}/viewer-count
getLiveStreamByIdGet stream by IDGET /live/streams/{streamId}
deleteLiveStreamDelete a streamDELETE /live/streams/{streamId}
updateLiveStreamUpdate a streamPATCH /live/streams/{streamId}
enableLiveStreamEnable a streamPUT /live/streams/{streamId}/live-enable
disableLiveStreamDisable a streamPUT /live/streams/{streamId}/live-disable
completeLiveStreamComplete a streamPUT /live/streams/{streamId}/finish

Live Playback

MethodDescriptionHTTP Request
createPlaybackIdOfStreamCreate a playbackIdPOST /live/streams/{streamId}/playback-ids
deletePlaybackIdOfStreamDelete a playbackIdDELETE /live/streams/{streamId}/playback-ids/{playbackId}
getLiveStreamPlaybackIdGet playbackId detailsGET /live/streams/{streamId}/playback-ids/{playbackId}


3. Video Data

Resources for analytics, insights, and system monitoring.


Views

Viewer analytics for on-demand and live content.

MethodDescriptionHTTP Request
listVideoViewsList video viewsGET /data/viewlist
getVideoViewDetailsGet details of a video viewGET /data/viewlist/{viewId}
listByTopContentList by top contentGET /data/viewlist/top-content
getDataViewlistCurrentViewsGetTimeseriesViewsGet concurrent viewers timeseriesGET /data/viewlist/current-views/getTimeseriesViews
getDataViewlistCurrentViewsFilterGet concurrent viewers breakdown by dimensionGET /data/viewlist/current-views/filter

Dimensions

Categorize and filter video data for analytics.

MethodDescriptionHTTP Request
listDimensionsList the dimensionsGET /data/dimensions
listFilterValuesForDimensionList the filter values for a dimensionGET /data/dimensions/{dimensionsId}

Errors

Monitor and troubleshoot system errors.

MethodDescriptionHTTP Request
listErrorsList errorsGET /data/errors

Metrics

Access analytics and performance metrics.

MethodDescriptionHTTP Request
listBreakdownValuesList breakdown valuesGET /data/metrics/{metricId}/breakdown
listOverallValuesList overall valuesGET /data/metrics/{metricId}/overall
getTimeseriesDataGet timeseries dataGET /data/metrics/{metricId}/timeseries
listComparisonValuesList comparison valuesGET /data/metrics/comparison

Retries

Some endpoints in the FastPix SDK support automatic retries. By default, the SDK uses the retry strategy provided by the API. You can customize this strategy per operation or globally for the SDK.


1. Per-Operation Retry Configuration

To override the retry strategy for a single API call, provide a retryConfig object as the second argument to the call:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  security: {
    username: "your-access-token",
    password: "secret-key",
  },
});

async function run() {
  const result = await fastpix.inputVideo.createMedia(
    {
      inputs: [
        {
          type: "video",
          url: "https://static.fastpix.io/sample.mp4",
        },
      ],
      metadata: {
        key1: "value1",
      },
      accessPolicy: "public",
    },
    {
      retries: {
        strategy: "backoff",
        backoff: {
          initialInterval: 1,
          maxInterval: 50,
          exponent: 1.1,
          maxElapsedTime: 100,
        },
        retryConnectionErrors: false,
      },
    }
  );

  console.log(result);
}

run();

2. Global Retry Configuration

To apply a retry strategy across all SDK operations that support retries, pass a retryConfig object when initializing the SDK:

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  security: {
    username: "your-access-token",
    password: "secret-key",
  },
});

async function run() {
  const result = await fastpix.inputVideo.createMedia({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.io/sample.mp4",
      },
    ],
    metadata: {
      key1: "value1",
    },
    accessPolicy: "public",
  });

  console.log(result);
}

run();

Error Handling

The FastPix SDK provides structured error handling through the FastpixError class, which serves as the base for all HTTP error responses.


Error Properties

PropertyTypeDescription
error.messagestringError message
error.statusCodenumberHTTP response status code, e.g., 404
error.headersHeadersHTTP response headers
error.bodystringHTTP response body. Can be an empty string if no body is returned.
error.rawResponseResponseRaw HTTP response
error.data-Optional structured data for certain errors

Example Usage:

import { Fastpix } from "@fastpix/fastpix-node";
import * as errors from "@fastpix/fastpix-node/models/errors";

const fastpix = new Fastpix({
  security: {
    username: "your-access-token",
    password: "secret-key",
  },
});

async function run() {
  try {
    const result = await fastpix.inputVideo.createMedia({
      inputs: [
        {
          type: "video",
          url: "https://static.fastpix.io/sample.mp4",
        },
      ],
      metadata: {
        key1: "value1",
      },
      accessPolicy: "public",
    });

    console.log(result);
  } catch (error) {
    // The base class for HTTP error responses
    if (error instanceof errors.FastpixError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);

      // Depending on the method, different errors may be thrown
      if (error instanceof errors.BadRequestError) {
        console.log(error.data$.success); // boolean
        console.log(error.data$.error);   // models.BadRequestError
      }
    }
  }
}

run();

Error Classes

Primary Errors


Less Common Errors


HTTP Errors inheriting from FastpixError:



Server Selection

The FastPix SDK uses a default server endpoint, but you can override it per client instance by specifying the serverURL parameter during initialization.

import { Fastpix } from "@fastpix/fastpix-node";

const fastpix = new Fastpix({
  serverURL: "https://api.fastpix.io/v1/",
  security: {
    username: "your-access-token",
    password: "secret-key",
  },
});

async function run() {
  const result = await fastpix.inputVideo.createMedia({
    inputs: [
      {
        type: "video",
        url: "https://static.fastpix.io/sample.mp4",
      },
    ],
    metadata: {
      key1: "value1",
    },
    accessPolicy: "public",
  });

  console.log(result);
}

run();

Note

This allows you to point the SDK to different environments such as staging, testing, or custom endpoints.


Custom HTTP Client

The FastPix TypeScript SDK uses an HTTPClient that wraps the native Fetch API. This client provides hooks to modify requests, add custom headers, handle errors, or mock requests for testing.


Using a Custom HTTP Client

import { Fastpix } from "@fastpix/fastpix-node";
import { HTTPClient } from "@fastpix/fastpix-node/lib/http";

const httpClient = new HTTPClient({
  // fetcher takes a function that has the same signature as native `fetch`.
  fetcher: (request) => {
    return fetch(request);
  },
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000),
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new Fastpix({ httpClient: httpClient });

Debugging

The FastPix SDK can emit debug logs for all requests and responses, which is useful for development and troubleshooting.


Enable Debug Logging

You can pass a logger object that matches the console interface when initializing the SDK:

import { Fastpix } from "@fastpix/fastpix-node"; 

const sdk = new Fastpix({ debugLogger: console }); 

Warning: Debug logs may expose sensitive information such as API tokens in headers. Use this feature only during development and never in production.