TMDB API golang tutorial: top rated movies with net/http
A TMDB API golang client needs only the standard library. This tutorial builds a command line tool that lists the best rated movies of a genre and year, decodes JSON into typed structs, retries a 429 and caches replies on disk. It uses the TMDB v3 shape against https://api.amodb.dev/3 and needs Go 1.22.
The TMDB API works from Go with the standard library alone: net/http sends the call and encoding/json decodes it into typed structs. The code uses the TMDB v3 JSON shape and runs against amodb at https:/, so only the base URL and the key differ from TMDB. One run costs 1 request, and the same command costs 0 for the next 30 minutes.
What do you need to follow this tutorial?
You need Go 1.22 or newer, an amodb key and about 20 minutes, and no third party module.
| You need | Details |
|---|---|
| Go | 1.22 or newer, checked with go version |
| Modules | None, only the standard library |
| API key | An 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 URL | https:/ (TMDB uses https:/) |
| Time | About 20 minutes |
| Result | A command line tool named topfilms that prints the best rated movies of a genre and year |
Which call does the tool make, and what does it cost?
The tool makes 1 call per run, and that call counts as 1 request toward the 20, 40 or 120 requests per minute of your key.
| Call | Path | Edge cache | Cost in requests |
|---|---|---|---|
| Discover movies | GET /3/discover/movie with with_genres, primary_release_year, sort_by and vote_count.gte | 30 minutes | 1 |
| Same command again, inside 30 minutes | Read from the user cache folder | Not applicable | 0 |
One discover page holds 20 results, so the -n flag accepts 1 to 20. A reply served from the edge cache still counts as a request, but a file hit costs 0.
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.
There is 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 /, which this tool does not call. You can pay by card, Apple Pay or Google Pay for 1 to 24 months, prepaid with no automatic renewal, or monthly through Patreon, which renews on Patreon until you cancel there. A key is 32 lowercase hex characters, like a TMDB API key. Export it:
The program reads it with os.Getenv("AMODB_KEY"), so it never sits in the source.
export AMODB_KEY="YOUR_API_KEY"Step 2: Create the module
Make a folder and initialize a Go module with go mod init, because there is nothing to download.
go version should print 1.22 or higher. Put all code below in a file named main.go.
mkdir topfilms && cd topfilms
go mod init topfilms
go versionStep 3: Send the first request
Send a first request to GET /3/discover/movie with an http.Client that has a timeout and your key in the Authorization header.
That endpoint filters and sorts the catalog. Genre 878 is Science Fiction, and the full id list is on the TMDB genre ids page. This complete program only prints the status line.
Never use http.DefaultClient for API calls, because it has no timeout.
package main
import (
"fmt"
"net/http"
"os"
"time"
)
func main() {
url := "https://api.amodb.dev/3/discover/movie?with_genres=878"
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("AMODB_KEY"))
res, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
fmt.Println(res.Status)
}Step 4: Decode into typed structs
Declare structs with only the fields you read, because encoding/json ignores the rest and new fields in the reply cannot break the tool.
The query asks for sort_ and vote_count.gte=500. Without the vote floor, titles with a single 10 star vote would lead the list. Every filter is documented on the TMDB discover API page.
type Movie struct {
ID int `json:"id"`
Title string `json:"title"`
ReleaseDate string `json:"release_date"`
VoteAverage float64 `json:"vote_average"`
VoteCount int `json:"vote_count"`
}
type DiscoverPage struct {
TotalResults int `json:"total_results"`
Results []Movie `json:"results"`
}Step 5: Retry on 429 and report errors
Read the body once, then decide what to do from the status code: cache and decode a 200, stop on a 401, retry a 429 and report everything else.
The client treats each status like this:
| Status | What the client does |
|---|---|
| 200 | Writes the cache file and decodes the body. |
| 401 | Returns an error that names AMODB_KEY. No retry, because the next call would fail too. |
| 429 | Sleeps for Retry-After seconds (1 if missing, 30 at most) and tries again, up to 3 attempts. |
| Other 4xx and 5xx | Returns the status_code and status_message from the TMDB error body. |
| Transport error | Returns network error wrapped with %w. |
The delay helper is small:
See error codes for every code and rate limits for the sliding window.
func retryDelay(header string) time.Duration {
seconds, err := strconv.Atoi(header)
if err != nil || seconds < 1 {
seconds = 1
}
return time.Duration(min(seconds, 30)) * time.Second
}Step 6: Cache replies on disk
Save each successful body in the user cache folder under the SHA-256 of the full URL, and serve it again while the file is younger than the TTL.
The edge holds discover lists for 30 minutes, and the client uses the same lifetime. A repeated command then makes no request.
Step 7: The complete program
Replace main.go with the complete program and run go run . -genre 878 -year 2010 -n 10.
The tool takes three flags:
| Flag | Default | Meaning |
|---|---|---|
-genre | 878 | Genre id for with_genres. 878 is Science Fiction and 18 is Drama. |
-year | 2010 | Value for primary_release_year. |
-n | 10 | How many movies to print, 1 to 20. |
Try other filters with the flags. go run . -genre 18 -year 1999 -n 5 lists the five best-rated dramas from 1999. Run the same command twice and the second run answers from the cache file without touching the network, until 30 minutes have passed. If no movie has 500 votes for your combination, the tool prints No movies matched. and exits normally.
The retry loop returns from inside the switch in every case except a 429 that still has attempts left. That is why the function ends with a plain error: the compiler needs a return after the loop, and the message would only appear if the loop logic were changed.
package main
import (
"crypto/sha256"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"time"
)
const baseURL = "https://api.amodb.dev/3"
type Movie struct {
ID int `json:"id"`
Title string `json:"title"`
ReleaseDate string `json:"release_date"`
VoteAverage float64 `json:"vote_average"`
VoteCount int `json:"vote_count"`
}
type DiscoverPage struct {
TotalResults int `json:"total_results"`
Results []Movie `json:"results"`
}
type apiError struct {
StatusCode int `json:"status_code"`
StatusMessage string `json:"status_message"`
}
type Client struct {
key string
hc *http.Client
cacheDir string
}
func NewClient(key string) (*Client, error) {
base, err := os.UserCacheDir()
if err != nil {
base = os.TempDir()
}
dir := filepath.Join(base, "amodb-top-films")
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
return &Client{key: key, hc: &http.Client{Timeout: 10 * time.Second}, cacheDir: dir}, nil
}
func (c *Client) Get(path string, query url.Values, ttl time.Duration, out any) error {
endpoint := baseURL + path + "?" + query.Encode()
cacheFile := filepath.Join(c.cacheDir, fmt.Sprintf("%x.json", sha256.Sum256([]byte(endpoint))))
if info, err := os.Stat(cacheFile); err == nil && time.Since(info.ModTime()) < ttl {
if body, err := os.ReadFile(cacheFile); err == nil {
return json.Unmarshal(body, out)
}
}
for attempt := 1; attempt <= 3; attempt++ {
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.key)
res, err := c.hc.Do(req)
if err != nil {
return fmt.Errorf("network error: %w", err)
}
body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return fmt.Errorf("reading reply: %w", err)
}
switch {
case res.StatusCode == http.StatusOK:
_ = os.WriteFile(cacheFile, body, 0o644)
return json.Unmarshal(body, out)
case res.StatusCode == http.StatusTooManyRequests && attempt < 3:
time.Sleep(retryDelay(res.Header.Get("Retry-After")))
default:
return statusError(res.StatusCode, body)
}
}
return errors.New("retries exhausted")
}
func retryDelay(header string) time.Duration {
seconds, err := strconv.Atoi(header)
if err != nil || seconds < 1 {
seconds = 1
}
return time.Duration(min(seconds, 30)) * time.Second
}
func statusError(status int, body []byte) error {
if status == http.StatusUnauthorized {
return errors.New("401: the key is invalid or suspended, check AMODB_KEY")
}
var e apiError
if json.Unmarshal(body, &e) == nil && e.StatusMessage != "" {
return fmt.Errorf("amodb returned %d (status_code %d): %s", status, e.StatusCode, e.StatusMessage)
}
return fmt.Errorf("amodb returned %d", status)
}
func yearOf(date string) string {
if len(date) >= 4 {
return date[:4]
}
return "n/a"
}
func main() {
genre := flag.Int("genre", 878, "genre id, 878 is Science Fiction")
year := flag.Int("year", 2010, "primary release year")
limit := flag.Int("n", 10, "how many movies to print, 1 to 20")
flag.Parse()
key := os.Getenv("AMODB_KEY")
if key == "" {
fmt.Fprintln(os.Stderr, "Set AMODB_KEY first.")
os.Exit(1)
}
client, err := NewClient(key)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
query := url.Values{}
query.Set("language", "en-US")
query.Set("with_genres", strconv.Itoa(*genre))
query.Set("primary_release_year", strconv.Itoa(*year))
query.Set("sort_by", "vote_average.desc")
query.Set("vote_count.gte", "500")
var page DiscoverPage
if err := client.Get("/discover/movie", query, 30*time.Minute, &page); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
if len(page.Results) == 0 {
fmt.Println("No movies matched.")
return
}
fmt.Printf("%d movies match, best first:\n", page.TotalResults)
for i, m := range page.Results {
if i >= *limit {
break
}
fmt.Printf("%2d. %s (%s) %.1f from %d votes\n", i+1, m.Title, yearOf(m.ReleaseDate), m.VoteAverage, m.VoteCount)
}
}How do I switch this code between TMDB and amodb?
Change the baseURL constant and the key, and keep the structs and the retry logic.
| Setting | TMDB | amodb |
|---|---|---|
baseURL | https:/ | https:/ |
| Key | Your TMDB key | Your amodb key, sent as Authorization: Bearer or ?api_key= |
| Scores | vote_average and vote_count, TMDB's own user score | The same fields, plus a ratings object on a movie call with append_ |
| Rate limit | About 40 requests per second per IP, and TMDB says it could change | 20, 40 or 120 requests per minute per account, sliding 60 second window |
The Movie struct reads only id, title, release_date, vote_average and vote_count, so it decodes the same way from both services.
Is the TMDB API free to use in a Go service?
The TMDB API is free in a Go service only until the service earns money, and amodb has no free tier.
TMDB staff said on the TMDB forum (2026-10-15) that a project is commercial once it earns revenue from ads, in-app purchases, donations or subscriptions. TMDB's API terms shape the rest of the deal, as the table shows. Sources read 2026-10-19.
| Point | TMDB | amodb |
|---|---|---|
| Price while you earn nothing | Free | From $5.19 a month, no free tier and no trial |
| Price once you earn money | $149 a month for companies under $1M revenue, custom quote above | From $5.19 a month, up to $7.19 on Pro+ |
| Logo | TMDB logo plus a not-endorsed notice | No amodb logo; credit JustWatch and licensed texts and images as marked |
| License | TMDB decides what counts as commercial and may end the license at any time | No extra charge for commercial use, and the terms do not prohibit it. Do not resell raw API access, share keys or put keys in client side code. |
The Lite price of $5.19 is 3.5% of $149, and the Pro+ price of $7.19 is 4.8%. See amodb pricing for every plan, or Is the TMDB API free? for the longer answer.
What should I build next?
- Add a
-pageflag and pass it as thepageparameter to walk further down the list. - Resolve each movie id with the movie details API and add
append_to read the IMDb score fromto_ response= ratings ratings.imdb.value. - Run several genres at once with goroutines, and keep them under your plan's requests per minute.
- Port the same idea to TMDB API in Java or TMDB API in PHP, read the quickstart or browse all tutorials.