Trakt API Guide - JohanDevl/Export_Trakt_4_Letterboxd GitHub Wiki

Trakt.tv API Integration Guide

This document explains how Export Trakt for Letterboxd interacts with the Trakt.tv API, providing details on authentication, endpoints used, rate limiting, and best practices.

API Overview

The Export Trakt for Letterboxd application interacts with the Trakt.tv API to retrieve user watch history, ratings, and other data. Trakt.tv provides a RESTful API that allows access to various resources related to movies, TV shows, and user activities.

Key features of the Trakt.tv API integration:

  • OAuth 2.0 authentication for secure API access
  • Retrieval of watched movies with dates and ratings
  • Access to watchlist, ratings, and collection data
  • Support for TV shows data
  • Pagination support for handling large datasets
  • Rate limiting to comply with Trakt.tv API policies
  • Extended info parameters for detailed metadata

Authentication

The application uses OAuth 2.0 for authentication with the Trakt.tv API with automatic token management.

📘 Note: For detailed OAuth setup and usage instructions, see the OAuth Authentication Guide.

Authentication Overview

  1. Modern OAuth 2.0 Flow

    • Interactive authentication with automatic token renewal
    • Secure token storage using system keyring
    • Transparent token refresh on expiration
    • Comprehensive error handling and user guidance
  2. Automatic Token Management

    • Access tokens are valid for 3 months
    • Refresh tokens enable automatic renewal
    • Background token refresh prevents service interruption
    • Backward compatibility with legacy tokens
  3. Secure Storage

    • Tokens stored in system keyring (macOS Keychain, Windows Credential Store)
    • Encrypted file storage as fallback
    • Environment variables for containerized deployments

Configuration

Authentication settings are configured in the config.toml file:

[trakt]
client_id = "your_client_id"
client_secret = "your_client_secret"
api_base_url = "https://api.trakt.tv"
extended_info = "full"

[auth]
use_oauth = true
auto_refresh = true
redirect_uri = "http://localhost:8080/callback"
callback_port = 8080

Endpoints Used

The application uses the following Trakt.tv API endpoints:

Movies Endpoints

  • GET /sync/watched/movies: Retrieve watched movies history
  • GET /sync/ratings/movies: Retrieve movie ratings
  • GET /sync/watchlist/movies: Retrieve movie watchlist
  • GET /sync/collection/movies: Retrieve movie collection

TV Shows Endpoints

  • GET /sync/watched/shows: Retrieve watched TV shows
  • GET /sync/ratings/shows: Retrieve TV show ratings
  • GET /sync/watchlist/shows: Retrieve TV show watchlist

User Endpoints

  • GET /users/{username}/watched/movies: Alternative method to get watched movies
  • GET /users/{username}/ratings/movies: Alternative method to get movie ratings

Search Endpoints

  • GET /search/movie: Search for movies (used for verification and enrichment)
  • GET /search/show: Search for TV shows

Additional Endpoints

  • GET /movies/{id}: Get detailed information about a specific movie
  • GET /shows/{id}: Get detailed information about a specific TV show

Extended API Endpoints

The application supports extended API information using the extended parameter:

GET /sync/watched/movies?extended=full

Extended Information Fields

The extended=full parameter adds the following fields to movie responses:

  • Movie: tagline, overview, runtime, genres, certification
  • Collection: collected_at date, media type
  • Rating: rated_at date, comment
  • Watch: watched_at date, action

Implementation

The extended information is configured in the config.toml file:

[trakt]
extended_info = "full"  # Options: "min", "full", "metadata"

Rate Limiting

The Trakt.tv API has rate limits that must be respected:

  • 1,000 requests per 5 minutes (average of 3.33 requests per second)
  • 5 requests per second for personal websites
  • 50 requests per second for Trakt.tv clients

How Rate Limiting is Implemented

The application implements rate limiting through:

  1. Client-side Throttling

    • Limiting request frequency to stay below limits
    • Configurable rate limit in the application settings
  2. Response Header Monitoring

    • Monitoring X-Ratelimit-Remaining and X-Ratelimit-Reset headers
    • Adjusting request timing based on remaining limits
  3. Exponential Backoff

    • Implementing backoff strategy for rate limit errors
    • Starting with a short delay and progressively increasing

Data Models

The application uses Go structs to represent Trakt.tv data:

Movie Structure

type Movie struct {
    Title string    `json:"title"`
    Year  int       `json:"year"`
    IDs   MovieIDs  `json:"ids"`
}

type MovieIDs struct {
    Trakt  int     `json:"trakt"`
    TMDB   int     `json:"tmdb"`
    IMDB   string  `json:"imdb"`
}

WatchedMovie Structure

type WatchedMovie struct {
    Movie      Movie  `json:"movie"`
    WatchedAt  string `json:"watched_at"`
}

RatedMovie Structure

type RatedMovie struct {
    Movie    Movie   `json:"movie"`
    Rating   float64 `json:"rating"`
    RatedAt  string  `json:"rated_at"`
}

TV Show Structure

type Show struct {
    Title string   `json:"title"`
    Year  int      `json:"year"`
    IDs   ShowIDs  `json:"ids"`
}

type ShowIDs struct {
    Trakt  int     `json:"trakt"`
    TVDB   int     `json:"tvdb"`
    TMDB   int     `json:"tmdb"`
    IMDB   string  `json:"imdb"`
}

Error Handling

The API client implements robust error handling for various error scenarios:

Error Types

  • Authentication Errors: Issues with API keys or tokens
  • Rate Limiting Errors: When API limits are exceeded
  • Network Errors: Connectivity issues to the Trakt.tv API
  • Server Errors: 5xx responses from the Trakt.tv API
  • Client Errors: Invalid requests (4xx responses)
  • Parsing Errors: Issues with parsing API responses

Retry Strategy

The application implements an intelligent retry strategy:

  • Automatic retry for transient errors (5xx, network issues)
  • Exponential backoff with jitter for rate limit errors
  • Configurable maximum retry attempts
  • Different strategies based on error type

Troubleshooting

Common issues and solutions:

Authentication Failed

Problem: Unable to authenticate with the Trakt.tv API. Solution:

  • Verify your Client ID and Client Secret are correct
  • Check that your token file exists and is not corrupted
  • Delete the token file and re-authenticate

Rate Limit Exceeded

Problem: API requests are being rate limited. Solution:

  • Decrease the rate limit in your configuration
  • Implement caching to reduce API calls
  • Spread requests over a longer period

Unexpected API Responses

Problem: API responses don't match expected format. Solution:

  • Check for Trakt.tv API changes in their documentation
  • Update your API client implementation if needed
  • Log detailed error responses for debugging

Best Practices

When working with the Trakt.tv API:

  1. Respect Rate Limits: Always implement proper rate limiting
  2. Handle Pagination: Most endpoints return paginated results
  3. Implement Caching: Minimize API calls with appropriate caching
  4. Secure Tokens: Store access and refresh tokens securely
  5. Use Extended Info: Use extended parameters when needed
  6. Keep Authentication Up-to-Date: Implement token refresh logic