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.
Prerequisites
Import the SDK
Available Resources and Operations
Retries
Error Handling
Server Selection
Debugging
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:
- 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.
- 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.
Method | Description | HTTP Request |
---|---|---|
createMedia | Create media from a remote URL | POST /on-demand |
directUploadVideoMedia | Upload video directly from your device | POST /on-demand/upload |
In-Video AI Features
Enhance videos with AI-powered analysis.
Method | Description | HTTP Request |
---|---|---|
updateMediaSummary | Generate video summary | PATCH /on-demand/{mediaId}/summary |
updateMediaChapters | Generate video chapters | PATCH /on-demand/{mediaId}/chapters |
updateMediaNamedEntities | Generate named entities | PATCH /on-demand/{mediaId}/named-entities |
updateMediaModeration | Enable video moderation | PATCH /on-demand/{mediaId}/moderation |
Manage Videos
Full lifecycle management of uploaded media.
Method | Description | HTTP Request |
---|---|---|
listMedia | Get list of all media | GET /on-demand |
listLiveClips | Get all clips of a live stream | GET /on-demand/{livestreamId}/live-clips |
getMedia | Get a media by ID | GET /on-demand/{mediaId} |
updatedMedia | Update a media by ID | PATCH /on-demand/{mediaId} |
deleteMedia | Delete a media by ID | DELETE /on-demand/{mediaId} |
addMediaTrack | Add audio / subtitle track | POST /on-demand/{mediaId}/tracks |
cancelUpload | Cancel ongoing upload | POST /on-demand/{uploadId}/cancel |
updateMediaTrack | Update audio / subtitle track | PATCH /on-demand/{mediaId}/tracks/{trackId} |
deleteMediaTrack | Delete audio / subtitle track | DELETE /on-demand/{mediaId}/tracks/{trackId} |
generateSubtitleTrack | Generate track subtitle | POST /on-demand/{mediaId}/tracks/generate |
updatedSourceAccess | Update the source access of media | PATCH /on-demand/{mediaId}/source-access |
updatedMp4Support | Update the mp4Support of media | PATCH /on-demand/{mediaId}/update-mp4Support |
retrieveMediaInputInfo | Get info of media inputs | GET /on-demand/{mediaId}/input-info |
listUploads | Get all unused upload URLs | GET /on-demand/uploads |
getMediaClips | Get all clips of a media | GET /on-demand/{mediaId}/clips |
Playback
Manage secure playback access.
Method | Description | HTTP Request |
---|---|---|
createMediaPlaybackId | Create a playback ID | POST /on-demand/{mediaId}/playback-ids |
deleteMediaPlaybackId | Delete a playback ID | DELETE /on-demand/{mediaId}/playback-ids/{playbackId} |
getPlaybackId | Get a playback ID | GET /on-demand/{mediaId}/playback-ids/{playbackId} |
Playlist
Organize videos into playlists.
Method | Description | HTTP Request |
---|---|---|
createAPlaylist | Create a new playlist | POST /on-demand/playlists |
getAllPlaylists | Get all playlists | GET /on-demand/playlists |
getPlaylistById | Get a playlist by ID | GET /on-demand/playlists/{playlistId} |
updateAPlaylist | Update a playlist by ID | PATCH /on-demand/playlists/{playlistId} |
deleteAPlaylist | Delete a playlist by ID | DELETE /on-demand/playlists/{playlistId} |
addMediaToPlaylist | Add media to a playlist by ID | PATCH /on-demand/playlists/{playlistId}/media |
changeMediaOrderInPlaylist | Change media order in a playlist | PUT /on-demand/playlists/{playlistId}/media |
deleteMediaFromPlaylist | Delete media from a playlist by ID | DELETE /on-demand/playlists/{playlistId}/media |
DRM Configurations
Manage DRM for protected content.
Method | Description | HTTP Request |
---|---|---|
getDrmConfiguration | Get list of DRM configuration IDs | GET /on-demand/drm-configurations |
getDrmConfigurationById | Get DRM configuration by ID | GET /on-demand/drm-configurations/{drmConfigurationId} |
2. Live Stream
Resources for live streaming, simulcasting, and playback.
Start Live Stream
Method | Description | HTTP Request |
---|---|---|
createNewStream | Create a new stream | POST /live/streams |
Simulcast Stream
Method | Description | HTTP Request |
---|---|---|
createSimulcastOfStream | Create a simulcast | POST /live/streams/{streamId}/simulcast |
deleteSimulcastOfStream | Delete a simulcast | DELETE /live/streams/{streamId}/simulcast/{simulcastId} |
getSpecificSimulcastOfStream | Get a specific simulcast | GET /live/streams/{streamId}/simulcast/{simulcastId} |
updateSpecificSimulcastOfStream | Update a simulcast | PATCH /live/streams/{streamId}/simulcast/{simulcastId} |
Manage Live Stream
Method | Description | HTTP Request |
---|---|---|
getAllStreams | Get all live streams | GET /live/streams |
getLiveStreamViewerCountById | Get stream views by ID | GET /live/streams/{streamId}/viewer-count |
getLiveStreamById | Get stream by ID | GET /live/streams/{streamId} |
deleteLiveStream | Delete a stream | DELETE /live/streams/{streamId} |
updateLiveStream | Update a stream | PATCH /live/streams/{streamId} |
enableLiveStream | Enable a stream | PUT /live/streams/{streamId}/live-enable |
disableLiveStream | Disable a stream | PUT /live/streams/{streamId}/live-disable |
completeLiveStream | Complete a stream | PUT /live/streams/{streamId}/finish |
Live Playback
Method | Description | HTTP Request |
---|---|---|
createPlaybackIdOfStream | Create a playbackId | POST /live/streams/{streamId}/playback-ids |
deletePlaybackIdOfStream | Delete a playbackId | DELETE /live/streams/{streamId}/playback-ids/{playbackId} |
getLiveStreamPlaybackId | Get playbackId details | GET /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.
Method | Description | HTTP Request |
---|---|---|
listVideoViews | List video views | GET /data/viewlist |
getVideoViewDetails | Get details of a video view | GET /data/viewlist/{viewId} |
listByTopContent | List by top content | GET /data/viewlist/top-content |
getDataViewlistCurrentViewsGetTimeseriesViews | Get concurrent viewers timeseries | GET /data/viewlist/current-views/getTimeseriesViews |
getDataViewlistCurrentViewsFilter | Get concurrent viewers breakdown by dimension | GET /data/viewlist/current-views/filter |
Dimensions
Categorize and filter video data for analytics.
Method | Description | HTTP Request |
---|---|---|
listDimensions | List the dimensions | GET /data/dimensions |
listFilterValuesForDimension | List the filter values for a dimension | GET /data/dimensions/{dimensionsId} |
Errors
Monitor and troubleshoot system errors.
Method | Description | HTTP Request |
---|---|---|
listErrors | List errors | GET /data/errors |
Metrics
Access analytics and performance metrics.
Method | Description | HTTP Request |
---|---|---|
listBreakdownValues | List breakdown values | GET /data/metrics/{metricId}/breakdown |
listOverallValues | List overall values | GET /data/metrics/{metricId}/overall |
getTimeseriesData | Get timeseries data | GET /data/metrics/{metricId}/timeseries |
listComparisonValues | List comparison values | GET /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
Property | Type | Description |
---|---|---|
error.message | string | Error message |
error.statusCode | number | HTTP response status code, e.g., 404 |
error.headers | Headers | HTTP response headers |
error.body | string | HTTP response body. Can be an empty string if no body is returned. |
error.rawResponse | Response | Raw 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
- FastpixError: Base class for HTTP error responses.
- InvalidPermissionError
- ValidationErrorResponse: Status code 422.
Less Common Errors
- ConnectionError: Unable to reach server.
- RequestTimeoutError: Request timed out.
- RequestAbortedError : Request aborted by client.
- InvalidRequestError: Invalid request input.
- UnexpectedClientError: Unexpected error.
HTTP Errors inheriting from FastpixError:
- ForbiddenError: Status 403.
- UnauthorizedError
- MediaNotFoundError: Status 404.
- BadRequestError: Status 400.
- NotFoundError: Status 404.
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.
Updated about 10 hours ago