Skip to content

Repository files navigation

FastPix Java SDK

Maven Central license Java 11+

A robust, type-safe Java SDK designed for seamless integration with the FastPix API platform.

The FastPix Java SDK is a type-safe Java client for the FastPix video API. From any Java 11+ application (Maven or Gradle) you can upload and manage videos, run live streams and simulcasts, create and secure playback IDs, manage playlists and signing keys, pull video analytics (views, metrics, dimensions, and errors), and drive in-video AI features such as subtitles, chapters, summaries, and content moderation - with both synchronous and asynchronous APIs.

Works with: Java 11+ · Maven and Gradle · sync and async (CompletableFuture / Reactive Streams) · Spring Boot and any JVM app · Maven Central io.fastpix:sdk

📖 Docs: https://fastpix.com/docs/language-sdks/java-sdk  ·  🚀 Free account: https://dashboard.fastpix.com

Jump to

Skip straight to a section without scrolling:

Get started Reference Advanced & more
Start here Available resources & operations Async support
Before you begin Error handling Retries
Add the SDK Server selection Custom HTTP client
Create your first media FAQ Debugging
Media workflow Which SDK? Examples

Start here

If you are using the FastPix Java SDK for the first time, follow these steps in order:

  1. Check your Java version
  2. Add the SDK to your project
  3. Configure authentication
  4. Initialize the FastPix client
  5. Create your first media
  6. Verify your integration
  7. Understand the media workflow

Do not skip the verification steps. If a build, dependency, or authentication problem occurs, fix it before continuing to the next API operation.


Before you begin

To use the SDK, make sure you have:

  • Java 11 or later (JDK).
  • Maven or Gradle.
  • Internet access.
  • A FastPix account.
  • A FastPix Access Token.
  • A FastPix Secret Key.

Environment and Version Support

Requirement Version Description
Java 11+ Core runtime environment (JDK)
Maven/Gradle Latest Build tool and dependency management
Internet Required API communication and authentication

Pro Tip: We recommend using Java 17+ for optimal performance and the latest language features.

FastPix uses Basic Authentication:

SDK value FastPix credential
username Access Token
password Secret Key

Follow the steps in the Authentication with Basic Auth guide to obtain your credentials.

Optionally, store your credentials as environment variables:

# Set your FastPix credentials
export FASTPIX_USERNAME="your-access-token"
export FASTPIX_PASSWORD="your-secret-key"

Security Note: Never commit your credentials to version control. Use environment variables or secure credential management systems.


Check your Java version

Confirm your Java version before you add the SDK:

java -version

The output is similar to:

openjdk version "17.0.8" 2023-07-18

If your version is earlier than Java 11, install a supported JDK before continuing.

Confirm your build tool is available:

mvn -version

or:

gradle -version

Add the SDK to your project

Install the FastPix Java SDK using your preferred build tool.

Gradle

Add the dependency to your build.gradle:

dependencies {
    implementation 'io.fastpix:sdk:1.1.0'
}

Maven

Add the dependency to your pom.xml:

<dependency>
    <groupId>io.fastpix</groupId>
    <artifactId>sdk</artifactId>
    <version>1.1.0</version>
</dependency>

Build from source (optional)

After cloning the git repository to your file system, you can build the SDK artifact from source to the build directory by running:

On Unix/Linux/macOS:

./gradlew build

On Windows:

gradlew.bat build

If you wish to build from source and publish the SDK artifact to your local Maven repository, use:

On Unix/Linux/macOS:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

Configure authentication

FastPix uses Basic Authentication. Set your Access Token and Secret Key as environment variables so they stay out of your source code:

export FASTPIX_USERNAME="your-access-token"
export FASTPIX_PASSWORD="your-secret-key"

Confirm both variables are set, without printing their values.

On Unix/Linux/macOS:

[ -n "$FASTPIX_USERNAME" ] && echo "Access Token: set" || echo "Access Token: missing"
[ -n "$FASTPIX_PASSWORD" ] && echo "Secret Key: set" || echo "Secret Key: missing"

Initialize the FastPix client

Initialize the FastPix SDK with your credentials:

// Import required classes from the FastPix SDK
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.Security;

FastPixSDK sdk = FastPixSDK.builder()
    .security(Security.builder()
        .username("your-access-token")
        .password("your-secret-key")
        .build())
    .build();

Or using environment variables:

// Import required classes from the FastPix SDK
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.Security;

FastPixSDK sdk = FastPixSDK.builder()
    .security(Security.builder()
        .username(System.getenv("FASTPIX_USERNAME")) // Your Access Token
        .password(System.getenv("FASTPIX_PASSWORD")) // Your Secret Key
        .build())
    .build();

What this code does

FastPixSDK.builder() creates the top-level SDK client, and the Security object holds the credentials used to authenticate API requests. Building the client does not call the API. A request happens only when you call an operation, such as sdk.inputVideos().create().request(req).call().


Create your first media

The easiest way to verify your integration is to create media from a publicly accessible video URL. FastPix provides a sample video at https://static.fastpix.com/fp-sample-video.mp4.

For runnable, end-to-end flows (direct upload, webhook verification, playlists, live streaming, a Spring Boot app, and more), see the examples/ directory.

Note: In the examples below, package hello.world; is used for demonstration purposes. When creating your own Java files, ensure the package name matches your directory structure (e.g., if your file is at src/main/java/com/example/MyApp.java, use package com.example;).

// Package declaration - adjust to match your project's directory structure
package hello.world;

// Import required classes from the FastPix SDK
import java.lang.Exception;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.*;
import io.fastpix.sdk.models.operations.CreateMediaResponse;
import io.fastpix.sdk.utils.JSON;

public class Application {
    public static void main(String[] args) throws Exception {
        FastPixSDK sdk = FastPixSDK.builder()
                .security(Security.builder()
                    .username("your-access-token")
                    .password("your-secret-key")
                    .build())
            .build();
        CreateMediaRequest req = CreateMediaRequest.builder()
                .inputs(List.of(
                    Input.of(PullVideoInput.builder()
                        .url("https://static.fastpix.com/fp-sample-video.mp4")
                        .build())))
                .metadata(Map.ofEntries(
                    Map.entry("key1", "value1")))
                .build();
        CreateMediaResponse res = sdk.inputVideos().create()
                .request(req)
                .call();
        if (res.createMediaSuccessResponse().isPresent()) {
            var mapper = JSON.getMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            System.out.println(mapper.writeValueAsString(res.createMediaSuccessResponse().get()));
        }
    }
}

Compile and run Application with your build tool or IDE. For a Maven project with the exec-maven-plugin, run:

mvn -q compile exec:java -Dexec.mainClass="hello.world.Application"

Verify your integration

Run the example above to verify that your FastPix Java SDK integration is working.

A successful response includes:

{
  "success": true,
  "data": {
    "id": "..."
  }
}

The data.id value is the unique media ID assigned to the uploaded media.

If the request fails, check that:

  • Your FastPix access token and secret key are correct.
  • Your credentials belong to the same FastPix workspace.
  • Your environment variables are set correctly.
  • The io.fastpix:sdk dependency is declared in your Maven or Gradle build and resolved on the classpath.
  • You have an active internet connection.

Security: Never commit your access token or secret key to version control. Use environment variables or a secure credential-management system.


Understand the media workflow

Creating media is usually the first operation in an on-demand video workflow. You carry the media ID from one call to the next.

FastPix media workflow: create media returns a media ID, retrieve the media, check status until ready, create a playback ID, then play the video.

A playback ID is created separately, only when you need playback access.


Next steps

After verifying your integration, you can use the SDK to:

  • Manage media: list, retrieve, update, and delete media.
  • Create playback IDs: generate playback access for your media.
  • Manage live streams: create and manage live streaming sessions.
  • Create playlists: organize media into playlists.
  • Manage signing keys: create and manage keys for secure playback.
  • Analyze video performance: retrieve metrics, views, dimensions, and errors.
  • Use in-video AI: generate subtitles, summaries, chapters, and named entities.
  • Manage media tracks: add, update, and delete audio or subtitle tracks.

See Available Resources and Operations for the complete list.


Asynchronous Support

The SDK provides comprehensive asynchronous support using Java's CompletableFuture<T> and Reactive Streams Publisher<T> APIs. This design makes no assumptions about your choice of reactive toolkit, allowing seamless integration with any reactive library.

Why Use Async?

Asynchronous operations provide several key benefits:

  • Non-blocking I/O: Your threads stay free for other work while operations are in flight
  • Better resource utilization: Handle more concurrent operations with fewer threads
  • Improved scalability: Build highly responsive applications that can handle thousands of concurrent requests
  • Reactive integration: Works seamlessly with reactive streams and backpressure handling
Reactive Library Integration

The SDK returns Reactive Streams Publisher<T> instances for operations dealing with streams involving multiple I/O interactions. We use Reactive Streams instead of JDK Flow API to provide broader compatibility with the reactive ecosystem, as most reactive libraries natively support Reactive Streams.

Why Reactive Streams over JDK Flow?

  • Broader ecosystem compatibility: Most reactive libraries (Project Reactor, RxJava, Akka Streams, etc.) natively support Reactive Streams
  • Industry standard: Reactive Streams is the de facto standard for reactive programming in Java
  • Better interoperability: Seamless integration without additional adapters for most use cases

Integration with Popular Libraries:

  • Project Reactor: Use Flux.from(publisher) to convert to Reactor types
  • RxJava: Use Flowable.fromPublisher(publisher) for RxJava integration
  • Akka Streams: Use Source.fromPublisher(publisher) for Akka Streams integration
  • Vert.x: Use ReadStream.fromPublisher(vertx, publisher) for Vert.x reactive streams
  • Mutiny: Use Multi.createFrom().publisher(publisher) for Quarkus Mutiny integration

For JDK Flow API Integration:

If you need JDK Flow API compatibility (e.g., for Quarkus/Mutiny 2), you can use adapters:

// Convert Reactive Streams Publisher to Flow Publisher
Flow.Publisher<T> flowPublisher = FlowAdapters.toFlowPublisher(reactiveStreamsPublisher);

// Convert Flow Publisher to Reactive Streams Publisher
Publisher<T> reactiveStreamsPublisher = FlowAdapters.toPublisher(flowPublisher);

For standard single-response operations, the SDK returns CompletableFuture<T> for straightforward async execution.

Asynchronous Example

// Package declaration - adjust to match your project's directory structure
package hello.world;

// Import required classes from the FastPix SDK
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.fastpix.sdk.AsyncFastPixSDK;
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.*;
import io.fastpix.sdk.models.operations.async.CreateMediaResponse;
import io.fastpix.sdk.utils.JSON;

public class Application {
    public static void main(String[] args) {
        AsyncFastPixSDK sdk = FastPixSDK.builder()
                .security(Security.builder()
                    .username("your-access-token")
                    .password("your-secret-key")
                    .build())
            .build()
            .async();
        CreateMediaRequest req = CreateMediaRequest.builder()
                .inputs(List.of(
                    Input.of(PullVideoInput.builder()
                        .url("https://static.fastpix.com/fp-sample-video.mp4")
                        .build())))
                .metadata(Map.ofEntries(
                    Map.entry("key1", "value1")))
                .build();
        CompletableFuture<CreateMediaResponse> resFut = sdk.inputVideos().create()
                .request(req)
                .call();
        resFut.thenAccept(res -> {
            if (res.createMediaSuccessResponse().isPresent()) {
                try {
                    var mapper = JSON.getMapper();
                    mapper.enable(SerializationFeature.INDENT_OUTPUT);
                    System.out.println(mapper.writeValueAsString(res.createMediaSuccessResponse().get()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).join();
    }
}

Available Resources and Operations

Comprehensive Java SDK for FastPix platform integration with full API coverage.

Media API

Upload, manage, and transform video content with comprehensive media management capabilities.

For detailed documentation, see FastPix Video on Demand Overview.

Input Video

Manage Videos

Playback

Playlist

Signing Keys

DRM Configurations

Live API

Stream, manage, and transform live video content with real-time broadcasting capabilities.

For detailed documentation, see FastPix Live Stream Overview.

Start Live Stream

  • Create Stream - Initialize new live streaming session with DVR mode support

Manage Live Stream

Live Playback

Simulcast Stream

Video Data API

Monitor video performance and quality with comprehensive analytics and real-time metrics.

For detailed documentation, see FastPix Video Data Overview.

Metrics

Views

Dimensions

Errors

  • List Errors - Get playback errors and performance issues

Transformations

Transform and enhance your video content with powerful AI and editing capabilities.

In-Video AI Features

Enhance video content with AI-powered features including moderation, summarization, and intelligent categorization.

Media Clips

Subtitles

Media Tracks

Access Control

Format Support

Video Summary


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, you can provide a RetryConfig object through the retryConfig builder method:

// Package declaration - adjust to match your project's directory structure
package hello.world;

// Import required classes from the FastPix SDK
import java.lang.Exception;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.*;
import io.fastpix.sdk.models.operations.CreateMediaResponse;
import io.fastpix.sdk.utils.BackoffStrategy;
import io.fastpix.sdk.utils.RetryConfig;
import io.fastpix.sdk.utils.JSON;

public class Application {
    public static void main(String[] args) throws Exception {
        FastPixSDK sdk = FastPixSDK.builder()
                .security(Security.builder()
                    .username("your-access-token")
                    .password("your-secret-key")
                    .build())
            .build();
        CreateMediaRequest req = CreateMediaRequest.builder()
                .inputs(List.of(
                    Input.of(PullVideoInput.builder()
                        .url("https://static.fastpix.com/fp-sample-video.mp4")
                        .build())))
                .metadata(Map.ofEntries(
                    Map.entry("key1", "value1")))
                .build();
        CreateMediaResponse res = sdk.inputVideos().create()
                .request(req)
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(100L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .call();
        if (res.createMediaSuccessResponse().isPresent()) {
            var mapper = JSON.getMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            System.out.println(mapper.writeValueAsString(res.createMediaSuccessResponse().get()));
        }
    }
}

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

// Package declaration - adjust to match your project's directory structure
package hello.world;

// Import required classes from the FastPix SDK
import java.lang.Exception;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.*;
import io.fastpix.sdk.models.operations.CreateMediaResponse;
import io.fastpix.sdk.utils.BackoffStrategy;
import io.fastpix.sdk.utils.RetryConfig;
import io.fastpix.sdk.utils.JSON;

public class Application {
    public static void main(String[] args) throws Exception {
        FastPixSDK sdk = FastPixSDK.builder()
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(100L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .security(Security.builder()
                    .username("your-access-token")
                    .password("your-secret-key")
                    .build())
            .build();
        CreateMediaRequest req = CreateMediaRequest.builder()
                .inputs(List.of(
                    Input.of(PullVideoInput.builder()
                        .url("https://static.fastpix.com/fp-sample-video.mp4")
                        .build())))
                .metadata(Map.ofEntries(
                    Map.entry("key1", "value1")))
                .build();
        CreateMediaResponse res = sdk.inputVideos().create()
                .request(req)
                .call();
        if (res.createMediaSuccessResponse().isPresent()) {
            var mapper = JSON.getMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            System.out.println(mapper.writeValueAsString(res.createMediaSuccessResponse().get()));
        }
    }
}

Error Handling

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

Method Type Description
message() String Error message
code() int HTTP response status code eg 404
headers() Map<String, List<String>> HTTP response headers
body() Optional<byte[]> HTTP body as a byte array. Can be empty if no body is returned.
bodyAsString() String HTTP body as a UTF-8 string. Can be empty string if no body is returned.
rawResponse() HttpResponse<?> Raw HTTP response (body already read and not available for re-read)

Example

// Package declaration - adjust to match your project's directory structure
package hello.world;

// Import required classes from the FastPix SDK
import java.io.UncheckedIOException;
import java.lang.Exception;
import java.util.*;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.*;
import io.fastpix.sdk.models.errors.FastpixException;
import io.fastpix.sdk.models.operations.CreateMediaResponse;
import io.fastpix.sdk.utils.JSON;

public class Application {
    public static void main(String[] args) throws Exception {
        FastPixSDK sdk = FastPixSDK.builder()
                .security(Security.builder()
                    .username("your-access-token")
                    .password("your-secret-key")
                    .build())
            .build();
        try {
            CreateMediaRequest req = CreateMediaRequest.builder()
                    .inputs(List.of(
                        Input.of(PullVideoInput.builder()
                            .url("https://static.fastpix.com/fp-sample-video.mp4")
                            .build())))
                    .metadata(Map.ofEntries(
                        Map.entry("key1", "value1")))
                    .build();
            CreateMediaResponse res = sdk.inputVideos().create()
                    .request(req)
                    .call();
            if (res.createMediaSuccessResponse().isPresent()) {
                var mapper = JSON.getMapper();
                mapper.enable(SerializationFeature.INDENT_OUTPUT);
                System.out.println(mapper.writeValueAsString(res.createMediaSuccessResponse().get()));
            }
        } catch (FastpixException ex) { // all SDK exceptions inherit from FastpixException
            // ex.toString() provides a detailed error message including
            // HTTP status code, headers, and error payload (if any)
            System.out.println(ex);
            // Base exception fields
            var rawResponse = ex.rawResponse();
            var headers = ex.headers();
            var contentType = headers.get("Content-Type").stream().findFirst();
            int statusCode = ex.code();
            Optional<byte[]> responseBody = ex.body();
            Optional<String> bodyAsString = ex.bodyAsString();
        } catch (UncheckedIOException ex) {
            // handle IO error (connection, timeout, etc)
        }
    }
}

Error Classes

Primary error:

Less common errors

Network errors:

  • java.io.IOException (always wrapped by java.io.UncheckedIOException). Commonly encountered subclasses of IOException include java.net.ConnectException, java.net.SocketTimeoutException, EOFException (there are many more subclasses in the JDK platform).

Inherit from FastpixException:

  • Additional error classes may be defined for specific error scenarios.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

// Package declaration - adjust to match your project's directory structure
package hello.world;

// Import required classes from the FastPix SDK
import java.lang.Exception;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.*;
import io.fastpix.sdk.models.operations.CreateMediaResponse;
import io.fastpix.sdk.utils.JSON;

public class Application {
    public static void main(String[] args) throws Exception {
        FastPixSDK sdk = FastPixSDK.builder()
                .serverURL("https://api.fastpix.com/v1/")
                .security(Security.builder()
                    .username("your-access-token")
                    .password("your-secret-key")
                    .build())
            .build();
        CreateMediaRequest req = CreateMediaRequest.builder()
                .inputs(List.of(
                    Input.of(PullVideoInput.builder()
                        .url("https://static.fastpix.com/fp-sample-video.mp4")
                        .build())))
                .metadata(Map.ofEntries(
                    Map.entry("key1", "value1")))
                .build();
        CreateMediaResponse res = sdk.inputVideos().create()
                .request(req)
                .call();
        if (res.createMediaSuccessResponse().isPresent()) {
            var mapper = JSON.getMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            System.out.println(mapper.writeValueAsString(res.createMediaSuccessResponse().get()));
        }
    }
}

Custom HTTP Client

The Java SDK makes API calls using an HTTPClient that wraps the native HttpClient. This client 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 interface allows you to either use the default FastpixHTTPClient that comes with the SDK, or provide your own custom implementation with customized configuration such as custom executors, SSL context, connection pools, and other HTTP client settings.

The interface provides synchronous (send) methods and asynchronous (sendAsync) methods. The sendAsync method is used to power the async SDK methods and returns a CompletableFuture<HttpResponse<Blob>> for non-blocking operations.

The following example shows how to add a custom header and handle errors:

// Import required classes from the FastPix SDK
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.utils.HTTPClient;
import io.fastpix.sdk.utils.FastpixHTTPClient;
import io.fastpix.sdk.utils.Utils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;

public class Application {
    public static void main(String[] args) {
        // Create a custom HTTP client with hooks
        HTTPClient httpClient = new HTTPClient() {
            private final HTTPClient defaultClient = new FastpixHTTPClient();
            
            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                // Add custom header and timeout using Utils.copy()
                HttpRequest modifiedRequest = Utils.copy(request)
                    .header("x-custom-header", "custom value")
                    .timeout(Duration.ofSeconds(30))
                    .build();
                    
                try {
                    HttpResponse<InputStream> response = defaultClient.send(modifiedRequest);
                    // Log successful response
                    System.out.println("Request successful: " + response.statusCode());
                    return response;
                } catch (Exception error) {
                    // Log error
                    System.err.println("Request failed: " + error.getMessage());
                    throw error;
                }
            }
        };
        FastPixSDK sdk = FastPixSDK.builder()
            .client(httpClient)
            .build();
    }
}
Custom HTTP Client Configuration

You can also provide a completely custom HTTP client with your own configuration:

// Import required classes from the FastPix SDK
import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.utils.HTTPClient;
import io.fastpix.sdk.utils.Blob;
import io.fastpix.sdk.utils.ResponseWithBody;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.CompletableFuture;

public class Application {
    public static void main(String[] args) {
        // Custom HTTP client with custom configuration
        HTTPClient customHttpClient = new HTTPClient() {
            private final HttpClient client = HttpClient.newBuilder()
                .executor(Executors.newFixedThreadPool(10))
                .connectTimeout(Duration.ofSeconds(30))
                // .sslContext(customSslContext) // Add custom SSL context if needed
                .build();
            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                return client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            }
            @Override
            public CompletableFuture<HttpResponse<Blob>> sendAsync(HttpRequest request) {
                // Convert response to HttpResponse<Blob> for async operations
                return client.sendAsync(request, HttpResponse.BodyHandlers.ofPublisher())
                    .thenApply(resp -> new ResponseWithBody<>(resp, Blob::from));
            }
        };
        FastPixSDK sdk = FastPixSDK.builder()
            .client(customHttpClient)
            .build();
    }
}

Debugging

Debug & Logging

SLF4j Logging

This SDK uses SLF4j for structured logging across HTTP requests, retries, pagination, streaming, and hooks. SLF4j provides comprehensive visibility into SDK operations.

Log Levels:

  • DEBUG: High-level operations (HTTP requests/responses, retry attempts, page fetches, hook execution, stream lifecycle)
  • TRACE: Detailed information (request/response bodies, backoff calculations, individual items processed)

Configuration:

Add your preferred SLF4j implementation to your project. For example, using Logback:

dependencies {
    implementation 'ch.qos.logback:logback-classic:1.4.14'
}

Configure logging levels in your logback.xml:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- SDK-wide logging -->
    <logger name="io.fastpix.sdk" level="DEBUG"/>
    
    <!-- Component-specific logging -->
    <logger name="io.fastpix.sdk.utils.FastpixHTTPClient" level="DEBUG"/>
    <logger name="io.fastpix.sdk.utils.Retries" level="DEBUG"/>
    <logger name="io.fastpix.sdk.utils.pagination" level="DEBUG"/>
    <logger name="io.fastpix.sdk.utils.Hooks" level="TRACE"/>
    
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

What Gets Logged:

  • HTTP Client: Request/response details, headers (with sensitive headers redacted), bodies (at TRACE level)
  • Retries: Retry attempts, backoff delays, exhaustion, non-retryable exceptions
  • Pagination: Page fetches, pagination state, errors
  • Streaming: Stream initialization, item processing, closure
  • Hooks: Hook execution counts, operation IDs, exceptions

Legacy Debug Logging

For backward compatibility, you can still use the legacy debug logging method:

FastPixSDK sdk = FastPixSDK.builder()
    .enableHTTPDebugLogging(true)
    .build();

Warning

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.

Example output:

Sending request: http://localhost:35123/bearer#global GET
Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-fastpix-user-agent=[fastpix-sdk/java 0.0.1 internal 0.1.0 io.fastpix.sdk]}
Received response: (GET http://localhost:35123/bearer#global) 200
Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]}
Response body:
{
  "authenticated": true, 
  "token": "global"
}

Note: Authorization headers are redacted by default. You can specify additional redacted header names via FastpixHTTPClient.setRedactedHeaders.

Note: This is a convenience method that calls HTTPClient.enableDebugLogging(). The FastpixHTTPClient honors this setting. If you are using a custom HTTP client, it is up to the custom client to honor this setting.

JDK HTTP Client Logging

Another option is to set the System property -Djdk.httpclient.HttpClient.log=all. However, this option does not log request/response bodies.


FAQ

How do I install the FastPix Java SDK? Add io.fastpix:sdk to your build - implementation 'io.fastpix:sdk:<version>' for Gradle, or the equivalent <dependency> for Maven. See Add the SDK to your project.

How do I authenticate the SDK? FastPix uses Basic Auth: build a Security with your access token as username and secret key as password, then pass it to FastPixSDK.builder(). See Configure authentication.

How do I upload a video in Java? Create media from a URL or a direct upload through sdk.inputVideos(). See Create your first media and Available Resources and Operations.

Does the SDK support async / reactive? Yes - it provides asynchronous APIs using CompletableFuture and Reactive Streams Publisher, so it integrates with Reactor, RxJava, and other reactive libraries. See Asynchronous Support.

How do I start a live stream? Use the Live API resources to create and manage streams, simulcasts, and live playback IDs. See Available Resources and Operations.

How do I get video analytics and metrics in Java? The Video Data API exposes metrics, views, dimensions, and errors for quality-of-experience monitoring. See Available Resources and Operations.

How do I handle API errors? Catch FastpixException (the base class for HTTP error responses); it exposes the message, status code, headers, and body. See Error Handling.

How do I configure automatic retries? Provide a RetryConfig per call or at SDK initialization to control the backoff strategy. See Retries.

How do I use a custom HTTP client, proxy, or timeout? Provide your own HTTPClient implementation (custom executors, SSL context, connection pools, hooks) or wrap the default. See Custom HTTP Client.

How do I enable debug logging? The SDK logs through SLF4j; you can also use enableHTTPDebugLogging(true). See Debugging.

Which Java versions are supported? Java 11 and above (JDK). See Before you begin.


Which FastPix SDK should I use?

FastPix publishes a server SDK for every major backend language, each generated from the same API specification:

Language Repo Install
Java (this repo) fastpix-java io.fastpix:sdk (Maven/Gradle)
Node.js / TypeScript node-sdk npm install @fastpix/fastpix-node
Python fastpix-python pip install fastpix-python
PHP fastpix-php composer require fastpix/sdk
Go fastpix-go go get github.com/FastPix/fastpix-go
C# / .NET fastpix-sdk-csharp dotnet add package Fastpix
Ruby fastpix-ruby gem install fastpixapi

To upload and play the media these SDKs create, use the FastPix browser libraries: web-uploads-sdk, react-web-uploader, and web-player-component. Browse everything in the FastPix organization.


Development

This Java SDK is programmatically generated from our API specifications. Any manual modifications to internal files will be overwritten during subsequent generation cycles.

We value community contributions and feedback. Feel free to submit pull requests or open issues with your suggestions, and we'll do our best to include them in future releases.

Detailed Usage

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

The API reference offers complete documentation for all available endpoints and features, enabling developers to integrate and leverage FastPix APIs effectively.

Support

About

Official FastPix Java SDK - a type-safe Java client for the FastPix video API: media uploads, live streaming, playback IDs, playlists, video analytics, and in-video AI. Maven Central: io.fastpix:sdk

Topics

Resources

Contributing

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages