TMDB API Java tutorial: an episode guide with HttpClient

A TMDB API Java client needs only the JDK HttpClient and Jackson. This tutorial builds an episode guide that prints every episode of a TV season with number, air date and runtime, at 1 request per season. It uses the TMDB v3 JSON shape against https://api.amodb.dev/3 and needs Java 17 and Maven 3.9.

.java Java Updated View as Markdown

The TMDB API works from Java with the JDK HttpClient and Jackson: one GET call returns a whole season as JSON that maps straight to records. The code uses the TMDB v3 JSON shape and runs against amodb at https://api.amodb.dev/3, so only the base URL and the key differ from TMDB. One season costs 1 request, and a repeat run inside 6 hours costs 0.

What do you need to follow this tutorial?

You need Java 17 or newer, Maven 3.9, an amodb key and about 20 minutes.

You needDetails
Java17 or newer, for records and java.net.http
Build toolMaven 3.9
Dependencyjackson-databind 2.18.2, or a newer 2.x release
API keyAn amodb key: 32 lowercase hex characters, the same shape as a TMDB v3 key. Plans start at $5.19 a month and there is no free tier.
Base URLhttps://api.amodb.dev/3 (TMDB uses https://api.themoviedb.org/3)
TimeAbout 20 minutes
ResultA program named EpisodeGuide that prints number, air date, runtime and name for each episode

Which call does the program make, and what does it cost?

The program sends 1 call per season, and each call counts as 1 request toward the 20, 40 or 120 requests per minute of your key.

TaskPathEdge cacheCost in requests
One seasonGET /3/tv/{tv_id}/season/{season_number}6 hours1
A whole show with 5 seasons, such as series 1396The same path, once per season6 hours each5
Same season again, inside 6 hoursRead from the amodb-cache folderNot applicable0

A reply served from the edge cache still counts as a request, but a file hit costs 0. On the 20 requests per minute plan you can read about 20 fresh seasons a minute.

Step 1: Get an API key

Buy a plan on amodb pricing with your email, sign in with the 6 digit code amodb then emails you, copy the first key, which is shown once, and export it as AMODB_KEY.

A key needs a paid plan, because amodb has no free tier. The plans differ in requests per minute: 20, 40 or 120. Every plan has every TMDB v3 compatible endpoint, the OMDb compatible endpoint, images, 14 languages and the extensions, and only Pro+ adds the all in one endpoint GET /3/all/{movie|tv|person}/{id}, which this program does not use. Card, Apple Pay and Google Pay payments are prepaid and do not renew automatically, while Patreon renews monthly until you cancel there. The key is 32 lowercase hex characters, like a TMDB API key. Export it:

The program reads System.getenv("AMODB_KEY") and refuses to start without it.

Shell
export AMODB_KEY="YOUR_API_KEY"

Step 2: Create the project

Create a project folder, a minimal pom.xml that lists Jackson as the only dependency, and the source directory.

A newer 2.x release of jackson-databind works as well.

Shell
mkdir episode-guide && cd episode-guide
mkdir -p src/main/java
cat > pom.xml <<'EOF'
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>example</groupId>
  <artifactId>episode-guide</artifactId>
  <version>1.0</version>
  <properties>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.18.2</version>
    </dependency>
  </dependencies>
</project>
EOF

Step 3: Send the first request

Send a first request to GET /3/tv/{tv_id}/season/{season_number} with the JDK HttpClient and print the status code.

Breaking Bad is series 1396, so the class below asks for its first season. Save it as src/main/java/First.java to try it alone. The run command in step 7 works for it too if you set -Dexec.mainClass=First.

Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class First {
    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.amodb.dev/3/tv/1396/season/1"))
                .timeout(Duration.ofSeconds(10))
                .header("Authorization", "Bearer " + System.getenv("AMODB_KEY"))
                .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
    }
}

Step 4: Map the JSON to records

Map the season JSON to two records, Episode and Season, and let Jackson ignore every property you do not declare.

A season reply has a name and an episodes array. Each episode has episode_number, name, air_date and runtime, and the last two can be null for an episode that has not aired. Use Integer for a number that can be missing. The full field list is on the seasons and episodes API page.

Java
@JsonIgnoreProperties(ignoreUnknown = true)
public record Episode(
        @JsonProperty("episode_number") int number,
        String name,
        @JsonProperty("air_date") String airDate,
        Integer runtime) {}

Step 5: Handle errors and rate limits

Read the status before you touch the body, and give 200, 401, 404, 429 and network failures their own outcome.

StatusWhat the program does
200Returns the body for Jackson.
401Throws IOException naming AMODB_KEY. A bad key fails every call, so there is no retry.
404Throws with the status_message, for example when the season does not exist.
429Reads Retry-After, sleeps 1 to 30 seconds and sends the request again, 3 attempts at most.
Timeout or connection failureRethrown as network error with the cause attached.

The error body is the TMDB shape, so status_message is the text to show. The error codes page lists every code, and rate limits explains the 60 second window.

Step 6: Cache replies in files

Write each body to a file in the temp directory, named from the request path, and read it back while the file is younger than the TTL.

The edge keeps details for 6 hours, so an episode list rarely changes between runs. A cache hit sends nothing and uses none of your requests per minute.

Step 7: The complete program

Save the program as src/main/java/EpisodeGuide.java and run it with Maven for series 1396, season 1.

Java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;

public class EpisodeGuide {
    private static final String BASE = "https://api.amodb.dev/3";
    private static final String KEY = System.getenv("AMODB_KEY");
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final HttpClient CLIENT = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();
    private static final Path CACHE_DIR = Path.of(System.getProperty("java.io.tmpdir"), "amodb-cache");

    @JsonIgnoreProperties(ignoreUnknown = true)
    public record Episode(
            @JsonProperty("episode_number") int number,
            String name,
            @JsonProperty("air_date") String airDate,
            Integer runtime) {}

    @JsonIgnoreProperties(ignoreUnknown = true)
    public record Season(String name, List<Episode> episodes) {}

    static String get(String path) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(URI.create(BASE + path))
                .timeout(Duration.ofSeconds(10))
                .header("Authorization", "Bearer " + KEY)
                .header("Accept", "application/json")
                .GET()
                .build();
        for (int attempt = 1; ; attempt++) {
            HttpResponse<String> response;
            try {
                response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
            } catch (IOException e) {
                throw new IOException("network error: " + e, e);
            }
            int status = response.statusCode();
            if (status == 200) {
                return response.body();
            }
            if (status == 401) {
                throw new IOException("401: the key is invalid or suspended, check AMODB_KEY");
            }
            if (status == 429 && attempt < 3) {
                long seconds = response.headers().firstValueAsLong("Retry-After").orElse(1);
                Thread.sleep(Math.min(Math.max(seconds, 1), 30) * 1000);
                continue;
            }
            throw new IOException("amodb returned " + status + ": " + message(response.body()));
        }
    }

    static String message(String body) {
        try {
            return MAPPER.readTree(body).path("status_message").asText("no message");
        } catch (IOException e) {
            return "no message";
        }
    }

    static String cachedGet(String path, Duration ttl) throws IOException, InterruptedException {
        Files.createDirectories(CACHE_DIR);
        Path file = CACHE_DIR.resolve(path.replaceAll("[^A-Za-z0-9]", "_") + ".json");
        if (Files.exists(file)) {
            Instant modified = Files.getLastModifiedTime(file).toInstant();
            if (modified.plus(ttl).isAfter(Instant.now())) {
                return Files.readString(file);
            }
        }
        String body = get(path);
        Files.writeString(file, body);
        return body;
    }

    public static void main(String[] args) {
        if (args.length != 2) {
            System.err.println("Usage: EpisodeGuide <tv_id> <season_number>");
            System.exit(2);
        }
        if (KEY == null || KEY.isBlank()) {
            System.err.println("Set AMODB_KEY first.");
            System.exit(2);
        }
        String path;
        try {
            path = "/tv/" + Integer.parseInt(args[0]) + "/season/" + Integer.parseInt(args[1]) + "?language=en-US";
        } catch (NumberFormatException e) {
            System.err.println("The series id and season number must be integers.");
            System.exit(2);
            return;
        }
        try {
            Season season = MAPPER.readValue(cachedGet(path, Duration.ofHours(6)), Season.class);
            System.out.println(season.name() + ", " + season.episodes().size() + " episodes");
            for (Episode ep : season.episodes()) {
                System.out.printf("%2d  %-10s  %-7s  %s%n",
                        ep.number(),
                        Objects.requireNonNullElse(ep.airDate(), "TBA"),
                        ep.runtime() == null ? "?" : ep.runtime() + " min",
                        ep.name());
            }
        } catch (IOException e) {
            System.err.println("error: " + e.getMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.exit(1);
        }
    }
}

Compile and run it for season 1 of series 1396:

The output has one header line with the season name and the episode count, then one row per episode. An episode without an air date shows TBA, and one without a runtime shows ?. Run the command twice: the second run reads the file from the temp directory and sends no request, until 6 hours have passed. Delete the amodb-cache folder to force fresh data.

Keep the HttpClient and the ObjectMapper in static fields. Both are thread safe and expensive to build, so one instance per process is the normal pattern, including in a web service.

Shell
mvn -q compile exec:java -Dexec.mainClass=EpisodeGuide -Dexec.args="1396 1"

How do I switch this code between TMDB and amodb?

Change the BASE constant and the key, and keep the records and the retry loop.

  • Base URL TMDB uses https://api.themoviedb.org/3. amodb uses https://api.amodb.dev/3.
  • Key Use your TMDB key on TMDB and your amodb key on amodb. amodb takes it as Authorization: Bearer or ?api_key=.
  • Season fields episode_number, name, air_date and runtime keep the TMDB v3 names, so the Episode record works on both.
  • Rate limit TMDB allows about 40 requests per second per IP and says that could change. amodb counts 20, 40 or 120 requests per minute per account.
  • Write methods Rating an episode or editing a list is a write call. amodb answers those with HTTP 405 and status_code 37.

Is the TMDB API free to use in a Java app?

The TMDB API is free in a Java app only until the app earns money, and amodb has no free tier.

TMDB staff said on the TMDB forum (2026-10-15) that an app is commercial once it earns revenue from ads, in-app purchases, donations or subscriptions. That covers a desktop tool with a paid license and a mobile app with ads. TMDB's commercial plan costs $149 a month for companies under $1M revenue, with a custom quote above (TMDB staff, 2026-03-31), and its API terms require the TMDB logo plus a not-endorsed notice. amodb starts at $5.19 a month, which is 3.5% of $149, charges nothing extra for commercial use and needs no amodb logo or credit line. Third party credits still apply: credit JustWatch for where to watch data, and show the attribution credit wherever a text or image carries one. Sources read 2026-10-19. See amodb pricing for the plans, or Is the TMDB API free? for the longer answer.

What should I build next?

  • Loop from season 1 to number_of_seasons from the TMDB TV API details and print the whole show.
  • Show the next episode of a running series with next_episode_to_air. The TV episode API overview covers air dates and schedules.
  • Add a third argument for the language parameter, and see which tags are served on the language codes page.
  • Compare with the same pattern in TMDB API in Go, read the quickstart or browse all tutorials.