TMDB API Python tutorial: search a movie and read ratings
A TMDB API Python client needs only the requests library. This tutorial builds a command line tool that searches a title, then fetches details, cast and ratings in one more call, so 2 requests per fresh title. It uses the TMDB v3 JSON shape against https://api.amodb.dev/3, needs Python 3.10 and takes 15 minutes.
The TMDB API works from Python with the requests library: send a GET call, pass the key in a header and read the JSON. The code on this page uses the TMDB v3 JSON shape and runs against amodb at https:/, so only the base URL and the key differ from TMDB. One fresh title costs 2 requests, and a repeat run inside the cache time costs 0.
What do you need to follow this tutorial?
You need Python 3.10 or newer, the requests library, an amodb key and about 15 minutes.
| You need | Details |
|---|---|
| Python | 3.10 or newer |
| Library | requests, installed with pip install requests. Everything else is 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 15 minutes |
| Result | A script named movie.py that prints year, runtime, genres, top cast, IMDb rating and a poster URL |
Which calls does the script make, and what do they cost?
The script sends 2 calls per fresh title, and each call counts as 1 request toward the 20, 40 or 120 requests per minute of your key.
| Call | Path | Edge cache | Cost in requests |
|---|---|---|---|
| Search by title | GET / | 10 minutes | 1 |
| Details, cast and ratings | GET / | 6 hours | 1 |
| Poster image | https:/ | 30 days | 0, no key needed |
On the 20 requests per minute plan that is about 10 fresh titles a minute. A reply served from the edge cache still counts as a request, but a reply read from the script's own file cache (Step 6) costs 0. Without append_to_response, cast and scores would need extra calls, so one title would cost more.
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.
amodb has no free tier. Card, Apple Pay and Google Pay payments are prepaid for 1 to 24 months and do not renew automatically, while Patreon is monthly and renews on Patreon until you cancel there. Every plan has every TMDB v3 compatible endpoint, the OMDb compatible endpoint, images, 14 languages and the extensions, and the plans differ in requests per minute: 20, 40 or 120. Pro+ also has the all in one endpoint GET /, which this tutorial does not use.
A key is 32 lowercase hex characters, the same shape as a TMDB API key, but it works on api.amodb.dev and not on api.themoviedb.org. Export it as an environment variable so it stays out of your source code:
On Windows PowerShell the same line is $env:AMODB_.
export AMODB_KEY="YOUR_API_KEY"Step 2: Set up the project
Create a virtual environment and install the requests library with pip.
On Windows run .venv\Scripts\activate instead of the second line.
python -m venv .venv
source .venv/bin/activate
pip install requestsStep 3: Send the first request
Send a GET request to /3/search/movie with a query parameter and your key in the Authorization: Bearer header.
This snippet prints the HTTP status and the id of the best match. Always pass a timeout, because requests waits forever by default.
The reply has the TMDB shape: a results array sorted by relevance, plus page and total_results. See the TMDB search API page for every filter.
import os
import requests
res = requests.get(
"https://api.amodb.dev/3/search/movie",
params={"query": "fight club", "language": "en-US"},
headers={"Authorization": f"Bearer {os.environ['AMODB_KEY']}"},
timeout=10,
)
print(res.status_code, res.json()["results"][0]["id"])Step 4: Fetch details, cast and ratings
Take the id from the best match and call GET / with append_ to get details, cast and ratings in one request.
Search results are short, so this second call adds the cast and the IMDb, Kinopoisk, Metacritic, Rotten Tomatoes and TMDB scores. Each score is an object with value and votes, or null when the source is not known, so test before you print. IMDb, Kinopoisk and TMDB values are out of 10, Metacritic and Rotten Tomatoes values are out of 100. Details are on the movie details API and movie ratings API pages. In the final script session is a requests.Session that already carries the Authorization header.
params = {"language": "en-US", "append_to_response": "credits,ratings"}
movie = session.get(f"{BASE}/movie/{movie_id}", params=params, timeout=10).json()
imdb = (movie.get("ratings") or {}).get("imdb")Step 5: Handle errors and rate limits
Check the status code before you parse the body, and handle 401, 404, 429 and network failures separately.
Errors use the TMDB body with success, status_code and status_message. Replies also carry X-RateLimit-Remaining, the requests left in the current 60 second window.
| Status | Meaning | What the script does |
|---|---|---|
| 401 | Invalid or suspended key | Stops and says to check AMODB_KEY. Retrying cannot help. |
| 404 | No such id | Prints the status_message. |
| 429 | Over your requests per minute | Sleeps for Retry-After seconds (cap 30), then retries up to twice. |
| 504 | Backend timeout | Printed as an error. Run the command again. |
| Network failure | No connection or timeout | Caught as requests.RequestException and reported. |
The retry loop is short:
More codes are listed on error codes, and the sliding window is explained on rate limits.
for attempt in range(3):
res = session.get(url, params=params, timeout=10)
if res.status_code != 429 or attempt == 2:
break
time.sleep(min(int(res.headers.get("Retry-After", "1")), 30))Step 6: Cache responses on disk
Store each successful reply in a file named after a hash of the path and parameters, and reuse the file while it is younger than its lifetime.
The edge keeps details for 6 hours and search for 10 minutes. Your own cache saves the round trip and spends no request from your limit, so the script uses the same lifetimes: 10 minutes for search and 6 hours for details. A shorter local cache only adds requests.
Step 7: The complete program
Save the complete program as movie.py and run it with python movie.py "fight club".
The output has one header line with title, year and runtime, then genres, cast, the IMDb rating, the poster URL and the overview. A cold run sends 2 requests. Run the same title again within 10 minutes and it sends 0. After 10 minutes only the search goes out again (1 request), because details stay in the file for 6 hours.
import hashlib
import json
import os
import sys
import time
from pathlib import Path
import requests
BASE = "https://api.amodb.dev/3"
POSTER = "https://img.amodb.dev/t/p/w342"
CACHE_DIR = Path.home() / ".cache" / "amodb-movie-cli"
SEARCH_TTL = 10 * 60
DETAILS_TTL = 6 * 60 * 60
class ApiError(Exception):
pass
def error_message(res):
try:
return res.json()["status_message"]
except (ValueError, KeyError):
return res.reason
def get(session, path, params, ttl):
CACHE_DIR.mkdir(parents=True, exist_ok=True)
stamp = f"{path}?{json.dumps(params, sort_keys=True)}"
cache_file = CACHE_DIR / (hashlib.sha256(stamp.encode()).hexdigest() + ".json")
if cache_file.exists() and time.time() - cache_file.stat().st_mtime < ttl:
return json.loads(cache_file.read_text(encoding="utf-8"))
for attempt in range(3):
try:
res = session.get(BASE + path, params=params, timeout=10)
except requests.RequestException as exc:
raise ApiError(f"network error: {exc}") from exc
if res.status_code != 429 or attempt == 2:
break
time.sleep(min(int(res.headers.get("Retry-After", "1")), 30))
if res.status_code == 401:
raise ApiError("401: the key is invalid or suspended. Check AMODB_KEY.")
if res.status_code != 200:
raise ApiError(f"{res.status_code}: {error_message(res)}")
cache_file.write_text(res.text, encoding="utf-8")
return res.json()
def search_movie(session, title):
data = get(session, "/search/movie", {"query": title, "language": "en-US"}, SEARCH_TTL)
if not data["results"]:
raise ApiError(f"no movie found for {title!r}")
return data["results"][0]["id"]
def movie_details(session, movie_id):
params = {"language": "en-US", "append_to_response": "credits,ratings"}
return get(session, f"/movie/{movie_id}", params, DETAILS_TTL)
def print_card(movie):
year = (movie.get("release_date") or "")[:4] or "unknown year"
genres = ", ".join(g["name"] for g in movie["genres"])
cast = ", ".join(p["name"] for p in movie["credits"]["cast"][:3])
imdb = (movie.get("ratings") or {}).get("imdb")
print(f"{movie['title']} ({year}), {movie.get('runtime') or '?'} min")
print(f"Genres: {genres or 'none listed'}")
print(f"Cast: {cast or 'none listed'}")
print(f"IMDb: {imdb['value']} ({imdb['votes']} votes)" if imdb else "IMDb: not known")
if movie.get("poster_path"):
print(f"Poster: {POSTER}{movie['poster_path']}")
print(movie.get("overview") or "No overview in this language.")
def main():
if len(sys.argv) < 2:
sys.exit('Usage: python movie.py "fight club"')
key = os.environ.get("AMODB_KEY")
if not key:
sys.exit("Set AMODB_KEY first.")
session = requests.Session()
session.headers["Authorization"] = f"Bearer {key}"
try:
movie_id = search_movie(session, " ".join(sys.argv[1:]))
print_card(movie_details(session, movie_id))
except ApiError as exc:
sys.exit(f"error: {exc}")
if __name__ == "__main__":
main()How do I switch this code between TMDB and amodb?
Change the base URL and the key, keep the rest of the script, and read the score fields that your service returns.
| Setting | TMDB | amodb |
|---|---|---|
| Base URL | https:/ | https:/ |
| Key | Your TMDB key | Your amodb key, sent as Authorization: Bearer or ?api_key= |
| Scores | vote_average, vote_count (TMDB's own user score) and imdb_id | A ratings object with IMDb, Kinopoisk, Metacritic, Rotten Tomatoes and TMDB, each can be null |
| Write methods (rate a movie, lists, account) | Available | HTTP 405 with status_code 37 |
| 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, no daily cap |
TMDB has no ratings object, so read vote_average and vote_count when you point the script at TMDB. For a side by side view of both services, read amodb vs TMDB.
Is the TMDB API free to use from Python?
The TMDB API is free only until your 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, and TMDB's terms say TMDB decides what counts as commercial. The table shows what each case costs.
| Project | TMDB API | amodb |
|---|---|---|
| Personal, earns nothing | Free key under TMDB's terms | From $5.19 a month, no free tier and no trial |
| Earns from ads, purchases, donations or subscriptions | Commercial plan: $149 a month for companies under $1M revenue, custom quote above | From $5.19 a month. No extra charge; the terms do not prohibit it |
| Attribution | TMDB logo plus a not-endorsed notice, and a JustWatch credit for watch provider data | No amodb logo; credit JustWatch and licensed texts and images as marked |
$5.19 a month is 3.5% of the $149 TMDB plan. The lowest amodb price is $3.11 a month, which is the Lite plan prepaid for 24 months at $74.74. Sources: TMDB API terms and TMDB staff replies on the TMDB forum, read 2026-10-19. See amodb pricing for every plan, Is the TMDB API free? for the longer answer, or the TMDB API alternative page for the full comparison.
What should I build next?
- Print a poster in another size. The image host takes any of the sizes listed on the TMDB image URL page, and needs no key.
- Add a
yearfilter to the search call, or switch to the TMDB discover API for filtered lists. - Show a mood meter next to the rating by adding
moodstoappend_to_response. Each entry inmoods.resultshas anameand anavgon a 0 to 10 scale. See the movie mood API. - Read the quickstart for the same flow in curl, then try the TMDB API in JavaScript tutorial for a batch version, or browse all tutorials.