Type-safe and developer-friendly TypeScript SDK for integration with the FastPix platform API.
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)
- 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.
- 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.
- 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.
- 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.
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.
You can install the FastPix TypeScript SDK using your preferred Node.js package manager:
npm install @fastpix/fastpix-node
pnpm add @fastpix/fastpix-node
bun add @fastpix/fastpix-node
yarn add @fastpix/fastpix-node
For supported JavaScript runtimes, please consult RUNTIMES.md. This package is published with CommonJS and ES Modules (ESM) support.
- SDK Example Usage
- Available Resources and Operations
- Retries
- Error Handling
- Server Selection
- Custom HTTP Client
- Debugging
- Detailed Usage
- Support
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 methods
- listDimensions - List the dimensions
- listFilterValuesForDimension - List the filter values for a dimension
- getDrmConfiguration - Get list of DRM configuration IDs
- getDrmConfigurationById - Get DRM configuration by ID
- listErrors - List errors
- createMedia - Create media from URL
- directUploadVideoMedia - Upload media from device
- updateMediaSummary - Generate video summary
- updateMediaChapters - Generate video chapters
- updateMediaNamedEntities - Generate named entities
- updateMediaModeration - Enable video moderation
- createPlaybackIdOfStream - Create a playbackId
- deletePlaybackIdOfStream - Delete a playbackId
- getLiveStreamPlaybackId - Get playbackId details
- getAllStreams - Get all live streams
- getLiveStreamViewerCountById - Get stream views by ID
- getLiveStreamById - Get stream by ID
- deleteLiveStream - Delete a stream
- updateLiveStream - Update a stream
- enableLiveStream - Enable a stream
- disableLiveStream - Disable a stream
- completeLiveStream - Complete a stream
- listMedia - Get list of all media
- listLiveClips - Get all clips of a live stream
- getMedia - Get a media by ID
- updatedMedia - Update a media by ID
- deleteMedia - Delete a media by ID
- addMediaTrack - Add audio / subtitle track
- cancelUpload - Cancel ongoing upload
- updateMediaTrack - Update audio / subtitle track
- deleteMediaTrack - Delete audio / subtitle track
- generateSubtitleTrack - Generate track subtitle
- updatedSourceAccess - Update the source access of a media by ID
- updatedMp4Support - Update the mp4Support of a media by ID
- retrieveMediaInputInfo - Get info of media inputs
- listUploads - Get all unused upload URLs
- getMediaClips - Get all clips of a media
- listBreakdownValues - List breakdown values
- listOverallValues - List overall values
- getTimeseriesData - Get timeseries data
- listComparisonValues - List comparison values
- createMediaPlaybackId - Create a playback ID
- deleteMediaPlaybackId - Delete a playback ID
- getPlaybackId - Get a playback ID
- createAPlaylist - Create a new playlist
- getAllPlaylists - Get all playlists
- getPlaylistById - Get a playlist by ID
- updateAPlaylist - Update a playlist by ID
- deleteAPlaylist - Delete a playlist by ID
- addMediaToPlaylist - Add media to a playlist by ID
- changeMediaOrderInPlaylist - Change media order in a playlist by ID
- deleteMediaFromPlaylist - Delete media in a playlist by ID
- createSigningKey - Create a signing key
- listSigningKeys - Get list of signing key
- deleteSigningKey - Delete a signing key
- getSigningKeyById - Get signing key by ID
- createSimulcastOfStream - Create a simulcast
- deleteSimulcastOfStream - Delete a simulcast
- getSpecificSimulcastOfStream - Get a specific simulcast
- updateSpecificSimulcastOfStream - Update a simulcast
- createNewStream - Create a new stream
- listVideoViews - List video views
- getVideoViewDetails - Get details of video view
- listByTopContent - List by top content
- getDataViewlistCurrentViewsGetTimeseriesViews - Get concurrent viewers timeseries
- getDataViewlistCurrentViewsFilter - Get concurrent viewers breakdown by dimension
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();
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. |
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();
Primary errors:
FastpixError
: The base class for HTTP error responses.InvalidPermissionError
: *ValidationErrorResponse
: Status code422
. *
Less common errors (28)
Network errors:
ConnectionError
: HTTP client was unable to make a request to a server.RequestTimeoutError
: HTTP request timed out due to an AbortSignal signal.RequestAbortedError
: HTTP request was aborted by the client.InvalidRequestError
: Any input used to create a request is invalid.UnexpectedClientError
: Unrecognised or unexpected error.
Inherit from FastpixError
:
ForbiddenError
: Status code403
. Applicable to 26 of 66 methods.*UnauthorizedError
: Applicable to 24 of 66 methods.*MediaNotFoundError
: Status code404
. Applicable to 17 of 66 methods.*BadRequestError
: Bad Request. Status code400
. Applicable to 10 of 66 methods.*NotFoundError
: Status code404
. Applicable to 8 of 66 methods.*ViewNotFoundError
: View Not Found. Status code404
. Applicable to 7 of 66 methods.*LiveNotFoundError
: Stream Not Found. Status code404
. Applicable to 6 of 66 methods.*InvalidPlaylistIdResponseError
: Payload Validation Failed. Status code422
. Applicable to 6 of 66 methods.*UnAuthorizedResponseError
: response for unauthorized request. Status code401
. Applicable to 4 of 66 methods.*ForbiddenResponseError
: response for forbidden request. Status code403
. Applicable to 4 of 66 methods.*TrackDuplicateRequestError
: Duplicate language name. Status code400
. Applicable to 3 of 66 methods.*NotFoundErrorSimulcast
: Stream/Simulcast Not Found. Status code404
. Applicable to 3 of 66 methods.*MediaOrPlaybackNotFoundError
: Status code404
. Applicable to 2 of 66 methods.*NotFoundErrorPlaybackId
: Status code404
. Applicable to 2 of 66 methods.*SigningKeyNotFoundError
: Bad Request. Status code404
. Applicable to 2 of 66 methods.*DuplicateMp4SupportError
: Mp4Support value already exists. Status code400
. Applicable to 1 of 66 methods.*TrialPlanRestrictionError
: Bad Request – Stream is either already enabled or cannot be enabled on trial plan. Status code400
. Applicable to 1 of 66 methods.*StreamAlreadyEnabledError
: Bad Request – Stream is either already enabled or cannot be enabled on trial plan. Status code400
. Applicable to 1 of 66 methods.*StreamAlreadyDisabledError
: Stream already disabled. Status code400
. Applicable to 1 of 66 methods.*SimulcastUnavailableError
: Simulcast is not available for trial streams. Status code400
. Applicable to 1 of 66 methods.*MediaClipNotFoundError
: media workspace relation not found. Status code404
. Applicable to 1 of 66 methods.*DuplicateReferenceIdErrorResponse
: Displays the result of the request. Status code409
. Applicable to 1 of 66 methods.*ResponseValidationError
: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValue
for the raw value anderror.pretty()
for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
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();
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 });
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.
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.
If you have any queries, please reach out to support@fastpix.io.