DEV Community

Mason K
Mason K

Posted on

How to upload, process and play video with the FastPix Java SDK

TL;DR

We take a video from a local file to a playable HLS URL with the FastPix Java SDK: add one Maven dependency, request a signed upload, push the bytes, find the media, poll until it is ready, and mint a playback ID. Every snippet below compiles against io.fastpix:sdk:1.1.0.

📦 SDK: github.com/FastPix/fastpix-java

Most Java video tutorials stop at "call the REST API with OkHttp and parse the JSON yourself", which is how you end up maintaining a hand-rolled client with no retries and DTOs that drift every time the API adds a field. FastPix publishes a generated SDK on Maven Central, so this is the version where you write none of that.

One note on method: I compiled everything here against the real 1.1.0 jar rather than copying from docs. That caught two things the docs would have let me ship broken, and I have called both out where they bite.

1. Add the dependency ☕

<!-- pom.xml -->
<dependency>
    <groupId>io.fastpix</groupId>
    <artifactId>sdk</artifactId>
    <version>1.1.0</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode
// build.gradle
implementation 'io.fastpix:sdk:1.1.0'
Enter fullscreen mode Exit fullscreen mode

Java 11 is the floor, 17+ recommended. The upload step below uses java.net.http.HttpClient, which is JDK 11 and up anyway.

2. Build the client

import io.fastpix.sdk.FastPixSDK;
import io.fastpix.sdk.models.components.Security;

FastPixSDK sdk = FastPixSDK.builder()
        .security(Security.builder()
                .username(System.getenv("FASTPIX_USERNAME"))   // Access Token ID
                .password(System.getenv("FASTPIX_PASSWORD"))   // Secret Key
                .build())
        .build();
Enter fullscreen mode Exit fullscreen mode

Basic auth, Access Token ID as username, Secret Key as password, both from the dashboard. The base URL defaults to https://api.fastpix.com/v1/, so you only set .serverURL(...) if you have a reason.

💡 Tip: building the client makes no network call, so construct one at startup and hold it. It is thread-safe to share.

3. The easy path: ingest from a URL

If the source is already reachable over HTTP, you never touch the bytes:

import io.fastpix.sdk.models.components.*;
import io.fastpix.sdk.models.operations.*;

CreateMediaResponse res = sdk.inputVideos().create()
        .request(CreateMediaRequest.builder()
                .inputs(List.of(Input.of(PullVideoInput.builder()
                        .url("https://static.fastpix.com/fp-sample-video.mp4")
                        .build())))
                .metadata(Map.ofEntries(Map.entry("source", "demo")))
                .build())
        .call();

String mediaId = res.createMediaSuccessResponse()
        .flatMap(b -> b.data())
        .flatMap(d -> d.id())
        .orElseThrow(() -> new IllegalStateException("no media id"));
Enter fullscreen mode Exit fullscreen mode

Everything in this SDK is Optional, two or three levels deep, so flatMap chains are the idiom. Input.of(...) is the sum-type wrapper: inputs can also be WatermarkInput, AudioInput or SubtitleInput.

4. The real path: push a local file

Users hand you files, not URLs. You ask for a signed upload, then send the bytes yourself.

String tag = UUID.randomUUID().toString();   // so we can find the media later, see step 5

DirectUploadVideoMediaResponse up = sdk.inputVideos().upload()
        .request(DirectUploadVideoMediaRequest.builder()
                .corsOrigin("*")
                .pushMediaSettings(PushMediaSettings.builder()
                        .accessPolicy(DirectUploadVideoMediaAccessPolicy.PUBLIC)
                        .maxResolution(MaxResolution.ONE_THOUSAND_AND_EIGHTYP)
                        .metadata(Map.ofEntries(Map.entry("uploadTag", tag)))
                        .build())
                .build())
        .call();

DirectUpload du = up.object().orElseThrow().data();
String uploadId = du.uploadId().orElseThrow();
String signedUrl = du.url().orElseThrow();
double expiresIn  = du.timeout().orElse(0d);
Enter fullscreen mode Exit fullscreen mode

Now the part the SDK does not do for you. The signed URL is a Google Cloud Storage resumable endpoint, so it is a two-request dance, not a single PUT: start a session, read the Location header, then PUT the file at the URL that comes back.

HttpClient http = HttpClient.newHttpClient();

HttpResponse<Void> start = http.send(
        HttpRequest.newBuilder(URI.create(signedUrl))
                .header("x-goog-resumable", "start")
                .header("Content-Type", "video/mp4")
                .POST(HttpRequest.BodyPublishers.noBody())
                .build(),
        HttpResponse.BodyHandlers.discarding());

String sessionUrl = start.headers().firstValue("Location").orElseThrow(
        () -> new IllegalStateException("no Location header; status " + start.statusCode()));

HttpResponse<String> put = http.send(
        HttpRequest.newBuilder(URI.create(sessionUrl))
                .header("Content-Type", "video/mp4")
                .PUT(HttpRequest.BodyPublishers.ofFile(Path.of("talk.mp4")))
                .build(),
        HttpResponse.BodyHandlers.ofString());
Enter fullscreen mode Exit fullscreen mode

⚠️ FastPix's own docs label the session-start step "Web Only", because their browser and mobile SDKs do it for you and also handle chunking and resume. From a JVM you do it yourself. Verify against your own workspace before shipping: if a plain PUT straight at signedUrl works for you, drop the handshake.

BodyPublishers.ofFile streams from disk rather than loading the file into the heap, which matters the first time somebody uploads a 4 GB screen recording. That expiresIn value is the signed URL's lifetime, so do not stash the URL in a queue and use it an hour later.

5. Finding the media your upload became

Here is the gap nobody warns you about. The upload response gives you an uploadId. The rest of the API works on a mediaId. Nothing in the upload response, and nothing in listUploads(), maps one to the other.

Two ways out. The clean one is the video.media.created webhook, which arrives with the media ID and is what you want in a real service. If you are writing a script and want to stay synchronous, tag the upload with unique metadata and match on it:

String mediaId = null;
for (int i = 0; i < 30 && mediaId == null; i++) {
    ListMediaResponse list = sdk.manageVideos().list()
            .limit(25L).offset(1L).orderBy(SortOrder.DESC).call();

    mediaId = list.object().flatMap(ListMediaResponseBody::data).orElse(List.of()).stream()
            .filter(m -> tag.equals(m.metadata().orElse(Map.of()).get("uploadTag")))
            .findFirst()
            .flatMap(GetAllMediaResponse::id)
            .orElse(null);

    if (mediaId == null) Thread.sleep(5_000);
}
Enter fullscreen mode Exit fullscreen mode

That is the uploadTag from step 4 earning its keep. It is a workaround, and the webhook is the right answer past a prototype.

6. Poll until it is ready

GetMediaDetailResponseStatus status = null;
for (int i = 0; i < 60; i++) {
    status = sdk.manageVideos().get().mediaId(mediaId).call()
            .object().flatMap(GetMediaResponseBody::data)
            .flatMap(GetMediaDetailResponse::status)
            .orElse(null);

    if (GetMediaDetailResponseStatus.READY.equals(status)
            || GetMediaDetailResponseStatus.FAILED.equals(status)) break;

    Thread.sleep(5_000);
}
Enter fullscreen mode Exit fullscreen mode

There are eight states, not two: CREATED, DOWNLOADING, DOWNLOADED, VALIDATING, IN_QUEUE, PROCESSING, READY, FAILED. Breaking only on READY means a failed encode spins your loop for the full timeout and then falls through as if nothing happened, which is exactly the bug you do not want at 2am. Break on FAILED too, and treat anything that is not READY at the end as an error.

7. Playback ID, then HLS 🎥

A media ID is not a playback URL. You mint a playback ID, and the access policy you pick here decides who can watch.

String playbackId = sdk.playback().createId()
        .mediaId(mediaId)
        .body(CreateMediaPlaybackIdRequestBody.builder()
                .accessPolicy(AccessPolicy.PUBLIC)   // also PRIVATE and DRM
                .resolution(io.fastpix.sdk.models.operations.Resolution.ONE_THOUSAND_AND_EIGHTYP)
                .build())
        .call()
        .object().flatMap(CreateMediaPlaybackIdResponseBody::data)
        .flatMap(CreatePlaybackId::id)
        .orElseThrow();
Enter fullscreen mode Exit fullscreen mode

⚠️ That fully qualified Resolution is not me being pedantic. There is a Resolution in models.components and one in models.operations, they have identical constant names, and createId wants the operations one. Wildcard-import both packages and the compiler calls it ambiguous; import only components and you get a confusing "cannot be converted" error. Same trap with CreateMediaResponse, which exists in both packages.

The stream URL is a template, and it is ordinary HLS:

<video id="v" controls></video>
<script type="module">
  import Hls from 'https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.mjs';
  const src = 'https://stream.fastpix.com/PLAYBACK_ID.m3u8';
  const v = document.getElementById('v');
  if (v.canPlayType('application/vnd.apple.mpegurl')) v.src = src;   // Safari
  else { const hls = new Hls(); hls.loadSource(src); hls.attachMedia(v); }
</script>
Enter fullscreen mode Exit fullscreen mode

8. Failures, because they happen

try {
    // ... any sdk call
} catch (FastpixException e) {
    System.err.println(e.code() + " " + e.message());      // code() is the HTTP status
    System.err.println(e.bodyAsString().orElse(""));       // Optional, not String
} catch (UncheckedIOException e) {
    System.err.println("network failure: " + e.getMessage());
}
Enter fullscreen mode Exit fullscreen mode

Everything the SDK throws extends FastpixException, and you get code(), message(), headers(), body(), bodyAsString() and rawResponse(). Retries are built in and configurable per call or per client with RetryConfig and BackoffStrategy from io.fastpix.sdk.utils. Logging goes through SLF4J. For non-blocking services, FastPixSDK.builder()...build().async() gives an AsyncFastPixSDK whose calls return CompletableFuture.

What's next

Replace step 5 and step 6 with a single webhook endpoint. That removes both loops, and the same event stream carries the AI results (chapters, summaries) instead of needing a second integration. After that, sdk.manageVideos() has what an admin screen needs: list() with paging and SortOrder, addTrack(), generateSubtitles() and updateSourceAccess().

The Java SDK docs cover what I skipped: live streams, signing keys for private playback, DRM configurations and the analytics endpoints.

Worth saying plainly: this shape is not vendor-specific. Create an asset, wait on an async encode, mint a playback handle, serve HLS. You will write nearly the same steps against Mux, api.video or Cloudflare Stream, and the parts worth comparing are language coverage, whether retries and errors are handled for you, and how fast you can get off polling and onto webhooks. #java #api

Top comments (0)