Skip to content

FastPix/node-sdk

Repository files navigation

FastPix Typescript SDK

Type-safe and developer-friendly TypeScript SDK for integration with the FastPix platform API.

Introduction

The FastPix TypeScript SDK simplifies integration with the FastPix platform. It provides a type-safe and developer-friendly interface for secure and efficient communication with the FastPix API, enabling easy management of media uploads, live streaming, on-demand content, playlists, video analytics, and signing keys for secure access and token management. It is intended for use with Node.js (version >= 18)

Key Features

Media API

  • Upload Media: Seamlessly upload media files from URLs or local devices.
  • Manage Media: List, fetch, update, and delete media assets with ease.
  • Playback IDs: Generate and manage playback IDs for secure and flexible media access.
  • Advanced Media Tools: Generate video summaries, chapters, named entities, subtitles, and perform content moderation.
  • Playlist Management: Create and manage playlists, add or remove media, and adjust playback order.
  • DRM Support: Configure and manage DRM settings for protected content.

Live API

  • Create & Manage Live Streams: Effortlessly create, list, update, and delete live streams.
  • Control Stream Access: Generate playback IDs to manage viewer access securely.
  • Stream Management: Enable, disable, or complete streams with fine-grained control.
  • Simulcast to Multiple Platforms: Broadcast live content to multiple platforms simultaneously.

Signing Keys

  • Create Signing Keys: Generate signing keys for secure token-based access.
  • List & Retrieve Keys: Fetch all keys or get details for a specific key.
  • Manage Keys: Delete or revoke signing keys to maintain secure access control.

Video Data API

  • View Analytics: List video views, get detailed view information, and track top-performing content.
  • Concurrent Viewer Insights: Access timeseries data for live and on-demand streams.
  • Custom Reporting: Filter viewers by dimensions, list breakdowns, and compare metrics across datasets.
  • Error Tracking & Diagnostics: Retrieve logs and analyze errors for proactive monitoring.

For detailed usage, refer to the FastPix API Reference.

Prerequisites:

Getting started with FastPix:

To get started with the FastPix Node SDK, ensure you have the following:

  • The FastPix APIs are authenticated using an Access Token and a Secret Key. You must generate these credentials to use the SDK.

  • Follow the steps in the Authentication with Access Tokens guide to obtain your credentials.

Installation:

You can install the FastPix TypeScript SDK using your preferred Node.js package manager:

npm install @fastpix/fastpix-node

PNPM

pnpm add @fastpix/fastpix-node

Bun

bun add @fastpix/fastpix-node

Yarn

yarn add @fastpix/fastpix-node

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md. This package is published with CommonJS and ES Modules (ESM) support.

Table of Contents

SDK Example Usage

Example

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

Available methods

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object 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();

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:

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

FastpixError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
error.message string Error message
error.statusCode number HTTP response status code eg 404
error.headers Headers HTTP response headers
error.body string HTTP body. Can be empty string if no body is returned.
error.rawResponse Response Raw HTTP response
error.data$ Optional. Some errors may contain structured data. See Error Classes.

Example

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 (28)

Network errors:

Inherit from FastpixError:

* Check the method documentation to see if the error is applicable.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:

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();

Custom HTTP Client

The TypeScript SDK makes API calls using an HTTPClient that wraps the native Fetch API. This client is a thin wrapper around fetch and provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient constructor takes an optional fetcher argument that can be used to integrate a third-party HTTP client or when writing tests to mock out the HTTP client and feed in fixtures.

The following example shows how to use the "beforeRequest" hook to to add a custom header and a timeout to requests and how to use the "requestError" hook to log errors:

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

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches console's interface as an SDK option.

Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

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

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

You can also enable a default debug logger by setting an environment variable FASTPIX_DEBUG to true.

Detailed Usage

For a complete understanding of each API's functionality, including request and response details, parameter descriptions, and additional examples, please refer to the FastPix API Reference.

The API reference provides comprehensive documentation for all available endpoints and features, ensuring developers can integrate and utilize FastPix APIs efficiently.

Support

If you have any queries, please reach out to support@fastpix.io.

Packages

No packages published

Contributors 2

  •  
  •