TMDB API Swift tutorial with SwiftUI
A TMDB API client in Swift needs only URLSession, JSONDecoder and AsyncImage, with no package. This tutorial builds an iOS 16 SwiftUI app that lists 20 trending movies with posters from 1 request, handles 401 and 429, and shows why a released app must call your own server instead of holding the key.
To use the TMDB API from Swift, build a URLRequest with a Bearer header, send it with URLSession and await, and decode the reply with JSONDecoder. This tutorial shows 20 trending movies with posters in a SwiftUI list after 1 request, and the screen reloads at most once every 30 minutes. The code calls amodb, an independent paid API that keeps the TMDB v3 paths and JSON. A released app must not hold the key, so the tutorial also shows why you put a server in between.
What do you need to call the TMDB API from Swift?
You build Trending, an iOS app with one screen: a list of this week's trending movies with a poster, title, year and score.
| You need | Value |
|---|---|
| Language and IDE | Swift 5.9 or newer, Xcode, an iOS 16 deployment target |
| Packages | None. URLSession, JSONDecoder and AsyncImage ship with the SDK |
| Key | An amodb key, 32 lowercase hex characters. The TMDB API key page shows how to get one |
| Plan | Any plan. Lite, at 20 requests per minute, is enough |
| Where the key lives | The AMODB_KEY scheme variable for testing, your own server for a release |
| Time | About 20 minutes |
Which calls does the Swift app make, and what do they cost?
Every call to the API costs 1 request, and a reply served from the edge cache counts as well. Posters come from a separate host that needs no key and is not counted.
| Call | Path | Cost | Cache |
|---|---|---|---|
| Trending this week | GET trending/ | 1 request, 20 movies | The edge keeps it 30 minutes, the view model keeps it 30 minutes |
| Poster | GET https:/ | 0 requests | The image host caches for 30 days |
| Details with ratings, for a detail screen | GET movie/ | 1 request | 6 hours at the edge |
The list screen costs 1 request when it opens and 1 more for each forced refresh, so one user on a phone stays far below 20 requests per minute. A released app with thousands of users is different, because all of them share one key. That is the second reason to put a server in between. The TMDB trending API page lists the other list endpoints.
Is it safe to put the API key in an iOS app?
No. Treat any secret that ships in an app as public. Someone can read strings from the binary, inspect network traffic or read the app's storage. amodb also asks you not to put keys in client side code.
For this tutorial the key comes from an Xcode scheme variable, which is fine on your own device. For an app you release, run a small server that holds the key, forwards the call to amodb and returns the JSON. Set baseURL in the client below to that server and authenticate your users there. The rate limit applies to your whole account, so a server also lets you cache one answer for all of your users.
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 check it from a terminal before you write any Swift.
Every plan has every TMDB v3 compatible endpoint, images, 14 languages and the extensions. The plans differ in rate (Lite 20, Pro 40, Pro+ 120 requests per minute, from $5.19 a month), and only Pro+ also has the all in one endpoint GET /. There is no free tier or trial. The public https:/ endpoint needs no key, so you can test that your network reaches amodb before you pay.
A 200 means the key works. A 401 means it is wrong. The authentication page explains both ways to send the key.
export AMODB_KEY=YOUR_API_KEY
curl -s -o /dev/null -w "%{http_code}\n" \
"https://api.amodb.dev/3/trending/movie/week?api_key=$AMODB_KEY"Step 2: Create the Xcode project
Create an iOS App project named Trending with the SwiftUI interface, set the minimum deployment target to iOS 16 and delete the generated ContentView.swift.
In your scheme, open Edit Scheme, choose Run, then Arguments, and add an environment variable named AMODB_KEY with your key. Xcode passes it to the app only when you run from Xcode.
Step 3: Send the first request
Read the key from the environment, send it as a Bearer header and set a 10 second timeout so a stalled connection ends.
The call prints the status code and the size of the reply in bytes. A 200 and a few kilobytes of JSON mean the first request worked.
let key = ProcessInfo.processInfo.environment["AMODB_KEY"] ?? ""
var request = URLRequest(url: URL(string: "https://api.amodb.dev/3/trending/movie/week?language=en-US")!)
request.timeoutInterval = 10
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
let (data, response) = try await URLSession.shared.data(for: request)
print((response as? HTTPURLResponse)?.statusCode ?? 0, data.count)Step 4: Decode the response and show posters
Declare a Decodable model with optional posterPath and releaseDate, set keyDecodingStrategy to .convertFromSnakeCase and show the poster with AsyncImage.
The reply is a page with a results array of 20 items. Each movie has id, title, release_date, poster_path and vote_average, plus media_type set to movie. Fields you do not declare are ignored, which suits fields that appear later. poster_path can be null and release_date can be missing or an empty string, so the model declares both as optional.
| JSON field | Swift property | Type | Can be missing or null |
|---|---|---|---|
id | id | Int | no |
title | title | String | no |
release_date | releaseDate | String? | yes, or an empty string |
poster_path | posterPath | String? | yes |
vote_average | voteAverage | Double | no, 0 when there are no votes |
poster_path starts with a slash, so the string above joins the size and the file name correctly. Posters come from img.amodb.dev, which needs no key and caches images for 30 days. The TMDB image URL page lists the sizes, from w92 to original.
struct Movie: Decodable, Identifiable {
let id: Int
let title: String
let releaseDate: String?
let posterPath: String?
let voteAverage: Double
var posterURL: URL? {
guard let posterPath else { return nil }
return URL(string: "https://img.amodb.dev/t/p/w185\(posterPath)")
}
}Step 5: Handle errors and rate limits
Map each HTTP status to an error the screen can show.
| Status | Meaning | What the app does |
|---|---|---|
| 401 | Key missing or invalid (status_code 7 for an invalid key) | Show a message, no retry. |
| 402 | The plan period has ended (status_code 36) | Show a message. Renew on amodb pricing. |
| 429 | Over your requests per minute (status_code 25) | Wait Retry-After seconds, capped at 30, retry at most twice. |
| 500 or 504 | Server side failure | Show the status and offer pull to refresh. |
URLError | Offline, timeout, lost connection | Show localizedDescription. |
The error body uses the TMDB shape {"success": false,. See error codes and the TMDB API rate limit page for every code and header.
switch status {
case 200..<300:
return try Self.decoder.decode(T.self, from: data)
case 401:
throw AmodbError.invalidKey
case 429 where attempt < 2:
let header = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Retry-After")
try await Task.sleep(for: .seconds(min(Int(header ?? "") ?? 5, 30)))
attempt += 1
case 429:
throw AmodbError.rateLimited
default:
throw AmodbError.server(status)
}Step 6: Cache the list
Keep the last result in the view model and reload only when it is older than 30 minutes or the user pulls to refresh.
The edge caches trending lists for 30 minutes, so asking again sooner returns the same movies. The rate limit still counts the call, so a cache inside the app is the only way to save requests. A reload inside the 30 minutes costs 0 requests.
Step 7: The complete app
Paste this single file over the generated app file; it holds the models, the client, the view model and the views.
Run the app on a simulator. The list fills after the first call, and pulling down forces a reload. Scores are the aggregate vote_average from the list, and a title with no votes yet shows 0.0. For IMDb or Kinopoisk scores, request a movie with append_. The ratings object holds imdb, kinopoisk, metacritic, rotten_tomatoes and tmdb, each either null or an object with value and votes, as the movie ratings API page shows. IMDb, Kinopoisk and TMDB scores are out of 10, and Metacritic and Rotten Tomatoes are out of 100.
import SwiftUI
// MARK: Models
struct TrendingPage: Decodable {
let results: [Movie]
}
struct Movie: Decodable, Identifiable {
let id: Int
let title: String
let releaseDate: String?
let posterPath: String?
let voteAverage: Double
var year: String { String((releaseDate ?? "").prefix(4)) }
var posterURL: URL? {
guard let posterPath else { return nil }
return URL(string: "https://img.amodb.dev/t/p/w185\(posterPath)")
}
}
// MARK: Client
enum AmodbError: LocalizedError {
case missingKey
case invalidKey
case rateLimited
case server(Int)
var errorDescription: String? {
switch self {
case .missingKey: return "Set AMODB_KEY in the Xcode scheme."
case .invalidKey: return "The API key was rejected (401)."
case .rateLimited: return "Too many requests. Try again in a minute."
case .server(let status): return "The service answered with status \(status)."
}
}
}
struct AmodbClient {
var baseURL = URL(string: "https://api.amodb.dev/3")!
let apiKey: String
private static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
func get<T: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> T {
guard !apiKey.isEmpty else { throw AmodbError.missingKey }
var components = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!
components.queryItems = query
var request = URLRequest(url: components.url!, timeoutInterval: 10)
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
var attempt = 0
while true {
let (data, response) = try await URLSession.shared.data(for: request)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
switch status {
case 200..<300:
return try Self.decoder.decode(T.self, from: data)
case 401:
throw AmodbError.invalidKey
case 429 where attempt < 2:
let header = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Retry-After")
try await Task.sleep(for: .seconds(min(Int(header ?? "") ?? 5, 30)))
attempt += 1
case 429:
throw AmodbError.rateLimited
default:
throw AmodbError.server(status)
}
}
}
}
// MARK: View model
@MainActor
final class TrendingViewModel: ObservableObject {
@Published private(set) var movies: [Movie] = []
@Published private(set) var errorMessage: String?
@Published private(set) var isLoading = false
private let client: AmodbClient
private var loadedAt: Date?
init(client: AmodbClient) {
self.client = client
}
func load(force: Bool = false) async {
if !force, let last = loadedAt, !movies.isEmpty, Date().timeIntervalSince(last) < 30 * 60 {
return
}
isLoading = true
defer { isLoading = false }
do {
let page: TrendingPage = try await client.get(
"trending/movie/week",
query: [URLQueryItem(name: "language", value: "en-US")]
)
movies = page.results
loadedAt = Date()
errorMessage = nil
} catch {
errorMessage = error.localizedDescription
}
}
}
// MARK: Views
struct MovieRow: View {
let movie: Movie
var body: some View {
HStack(spacing: 12) {
AsyncImage(url: movie.posterURL) { phase in
switch phase {
case .success(let image):
image.resizable().scaledToFill()
case .failure:
Color.gray.opacity(0.2)
default:
ProgressView()
}
}
.frame(width: 60, height: 90)
.clipShape(RoundedRectangle(cornerRadius: 6))
VStack(alignment: .leading, spacing: 4) {
Text(movie.title).font(.headline)
Text(movie.year).font(.subheadline).foregroundStyle(.secondary)
Label(String(format: "%.1f", movie.voteAverage), systemImage: "star.fill")
.font(.caption)
}
}
}
}
struct ContentView: View {
@StateObject private var model: TrendingViewModel
init(client: AmodbClient) {
_model = StateObject(wrappedValue: TrendingViewModel(client: client))
}
var body: some View {
NavigationStack {
List(model.movies) { movie in
MovieRow(movie: movie)
}
.overlay {
if model.isLoading && model.movies.isEmpty {
ProgressView()
} else if let message = model.errorMessage, model.movies.isEmpty {
Text(message).multilineTextAlignment(.center).padding()
}
}
.navigationTitle("Trending")
.refreshable { await model.load(force: true) }
.task { await model.load() }
}
}
}
@main
struct TrendingApp: App {
private let client = AmodbClient(apiKey: ProcessInfo.processInfo.environment["AMODB_KEY"] ?? "")
var body: some Scene {
WindowGroup {
ContentView(client: client)
}
}
}Is the TMDB API free to use in an iOS app?
The TMDB API is free only while your app earns nothing, and an iOS app with ads, in-app purchases or subscriptions needs a paid plan.
TMDB staff said on the TMDB forum (2026-10-15) that an app counts as commercial the moment it earns revenue from ads, in-app purchases, donations or subscriptions. They quoted the commercial plan at $149 a month for companies under $1M revenue, with a custom quote above (2026-03-31), and there is no small tier between free and $149. TMDB's terms of use also require its logo with a not-endorsed notice and limit caching to 6 months.
| Project | TMDB | amodb |
|---|---|---|
| Personal app, earns nothing | Free under TMDB's terms | Paid, from $5.19 a month, no free tier |
| Commercial app (ads, in-app purchases, subscriptions) | $149 a month under $1M revenue, custom quote above | From $5.19 a month. No extra charge; the terms do not prohibit it |
| Logo or attribution | TMDB logo and notice required | No amodb logo; credit JustWatch and licensed texts and images as marked |
amodb plans cost $5.19, $6.19 or $7.19 a month, which is 3.5% to 4.8% of $149, and longer periods save up to 40 percent. Pay by card, Apple Pay or Google Pay, prepaid for 1, 3, 6, 12 or 24 months; those payments do not renew automatically. Patreon is monthly and renews on Patreon until the member cancels there. Do not resell raw API access or share keys. See Is the TMDB API free? for the full comparison.
Next steps
- Add a detail screen that loads
/movie/{id}withappend_, and see the movie details API page for the fields.to_ response= credits, ratings - Switch the
languagequery item to the device language, using the 14 base languages on the language codes page. - Move the key to your server and point
baseURLat it before you publish the app. - Build the same list for the web with the Next.js movie app tutorial, or read the quickstart for a first request in any language.
- Browse every guide in the tutorials hub.