This is the first phase in my project to analyse my anime watch history. Here, I outline my approach to collecting metadata for each anime title I’ve watched and all its related franchise entries from MyAnimeList’s public database using the Jikan API. This code takes my personal watched anime list as input and outputs a CSV file containing detailed metadata for every related anime entry, grouped by franchise.
*MyAnimeList (MAL) is one of the world’s largest anime and manga cataloguing platforms, with over 26,000 anime entries and 68,000 manga as of 2024.*
*Jikan (時間) is an unofficial, open-source API that provides structured access to MAL’s data, since MyAnimeList itself does not have a full public API.*
You can find the full code on my GitHub here.
Python libraries:
requests (API calls), pandas (dataframes), json (data handling), difflib & re (fuzzy string matching), unicodedata (unicode normalisation).
Custom module:
anime_list module which contains my personal watch history list (all_watched_anime) as input.
First, I define a global constant for the API endpoint:
URL = "https://api.jikan.moe/v4"
The get_data function is a helper used for almost all API requests in this project. By calling it wherever needed (instead of copy-pasting network logic), it ensures consistent, readable, and robust data fetching.
None if all retries fail, allowing the rest of the code to gracefully handle missing data.Centralising all API calls in a single function keeps the script clean, avoids duplication, and ensures consistent error handling and retry logic. This pattern increases both reliability and maintainability in the data collection workflow.
def get_data(url, params=None, max_retries=5, wait=1):
"""Performs a GET request with basic retry logic and
error handling for robust data collection.
"""
retries = 0
while retries < max_retries:
time.sleep(wait)
try:
resp = requests.get(url, params=params)
if resp.status_code == 429:
print(f"⚠️ Rate limited at {url}, retrying ({retries+1}/{max_retries})…")
time.sleep(10)
retries += 1
continue
resp.raise_for_status()
return resp
except requests.exceptions.HTTPError as e:
print(f"❌ Request failed for {url} due to {e}")
return None
except Exception as e:
print(f"❌ Unexpected error on attempt {retries+1} for {url}: {e}")
return None
print(f"❌ Max retries exceeded for {url}")
return None
The next step is to clean and normalise the anime title strings so they can be matched with entries in the MAL database as efficiently as possible. This process handles differences in punctuation, spacing, spelling, and capitalisation. Here, each title is normalised (cleaned up), split into word tokens, and compared using fuzzy matching - so that even titles that aren’t identical (due to minor differences) can still be recognised as matches.
norm(s: str) -> str :
Normalises a string for robust text matching and tokenisation: Applies Unicode normalisation, lowercases, removes apostrophes, replaces non-alphanumeric characters with spaces, and trims whitespace.
title_variants(anime: dict) -> list[str]:
Returns all available title variants for a given anime entry by extracting the primary, English, Japanese, and any additional titles present in the 'titles' field.
tokenise(s: str) -> list[str] :
Splits a normalised string into lowercase word tokens.
token_similarity(qtok: str, ttok: str) -> float :
Computes a similarity score between two tokens for fuzzy matching. It returns 1.0 for exact matches. If one token contains the other (e.g., 'summer' vs. 'summertime'), it returns a boosted similarity score based on their overlap and position. Otherwise, it falls back to the standard fuzzy ratio.
tokens_cover(query_tokens: list[str], title_tokens: list[str], thresh: float) -> tuple[bool, float]:
Checks if every query token is strongly matched by a title token. For each query token, it requires at least one title token with similarity greater than or equal to the threshold set(’thresh’). Then returns whether all are covered (True or False), and the sum of the best similarities for each token.