Skip to main content

Overview

The getTopAnime() function retrieves the highest-rated anime from MyAnimeList, ranked by user scores. Supports pagination and optional filtering by anime type or status.

Function Signature

getTopAnime(
  page?: number,
  limit?: number,
  filter?: string
): Promise<JikanSearchResponse>

Parameters

page
number
default:"1"
Page number for pagination.
  • Minimum: 1
  • Default: 1
  • Each page contains limit number of results
limit
number
default:"20"
Number of results per page.
  • Minimum: 1
  • Maximum: 25
  • Default: 20
filter
string
Filter results by anime characteristics. Supported values:
  • "airing" - Currently airing anime only
  • "upcoming" - Anime that haven’t aired yet
  • "bypopularity" - Sort by popularity instead of score
  • "favorite" - Sort by number of favorites
Default: No filter (sorted by score)

Return Value

Returns a Promise that resolves to a JikanSearchResponse object.
data
JikanAnime[]
required
Array of top-rated anime objects, sorted by score (or other metric if filtered).Each anime includes:
  • mal_id - MyAnimeList ID
  • title - Anime title
  • score - User rating (0-10)
  • rank - Global ranking position
  • popularity - Popularity ranking
  • Complete metadata (genres, studios, episodes, etc.)
See JikanAnime interface for full structure.
pagination
object
required
Pagination metadata

Examples

Basic Usage

import { getTopAnime } from '@/lib/animeApi';

const topAnime = await getTopAnime();

console.log(`Top ${topAnime.data.length} anime:`);
topAnime.data.forEach((anime, index) => {
  console.log(`${index + 1}. ${anime.title} - Score: ${anime.score}`);
});

// Example output:
// 1. Fullmetal Alchemist: Brotherhood - Score: 9.10
// 2. Steins;Gate - Score: 9.09
// 3. Attack on Titan Season 3 Part 2 - Score: 9.08

Filtered Queries

// Get top currently airing anime
const airing = await getTopAnime(1, 20, 'airing');

console.log('Top currently airing anime:');
airing.data.forEach(anime => {
  console.log(`${anime.title} - ${anime.score}/10`);
  console.log(`  Status: ${anime.status}`);
  console.log(`  Episodes: ${anime.episodes || 'Unknown'}`);
});

Advanced Usage

import { getTopAnime, type JikanAnime } from '@/lib/animeApi';

async function getTop100Anime(): Promise<JikanAnime[]> {
  const allAnime: JikanAnime[] = [];
  
  // Load 4 pages of 25 each = 100 total
  for (let page = 1; page <= 4; page++) {
    const response = await getTopAnime(page, 25);
    allAnime.push(...response.data);
  }
  
  return allAnime;
}

const top100 = await getTop100Anime();
console.log(`Loaded ${top100.length} top anime`);

React Hook Usage

Use the useTopAnime hook for React components:
import { useTopAnime } from '@/hooks/useAnime';

function TopAnimeList() {
  const { data, loading, error } = useTopAnime(1);
  
  if (loading) return <div>Loading top anime...</div>;
  if (error) return <div>Error: {error}</div>;
  
  return (
    <div>
      <h1>Top Anime on MyAnimeList</h1>
      <ol>
        {data.map(anime => (
          <li key={anime.id}>
            <strong>{anime.title}</strong>
            <span> - {anime.score}/10</span>
            <p>{anime.synopsis}</p>
          </li>
        ))}
      </ol>
    </div>
  );
}

Filtering Details

Available Filters

Currently broadcasting anime only.
const airing = await getTopAnime(1, 20, 'airing');

// Returns anime where:
// - status === 'Currently Airing'
// - airing === true
Use case: Show what’s hot right now

Performance & Caching

Automatic Caching

Responses are cached for 5 minutes:
// First call - fetches from API (~500ms)
const first = await getTopAnime(1, 20);

// Second call within 5 minutes - returns cached data (~1ms)
const second = await getTopAnime(1, 20);

// Different parameters - new API call
const filtered = await getTopAnime(1, 20, 'airing');

Rate Limiting

Automatic rate limiting ensures API compliance:
  • 3 requests per second maximum
  • Queued execution when limit reached
  • Exponential backoff on 429 errors
// All requests are automatically queued
const [top, airing, upcoming] = await Promise.all([
  getTopAnime(1, 10),
  getTopAnime(1, 10, 'airing'),
  getTopAnime(1, 10, 'upcoming')
]);

// Executes sequentially with 350ms delays

Common Patterns

Leaderboard Display

const topAnime = await getTopAnime(1, 10);

interface LeaderboardEntry {
  rank: number;
  title: string;
  score: number;
  imageUrl: string;
}

const leaderboard: LeaderboardEntry[] = topAnime.data.map((anime, index) => ({
  rank: index + 1,
  title: anime.title,
  score: anime.score,
  imageUrl: anime.images.jpg.large_image_url
}));

// Use in UI
leaderboard.forEach(entry => {
  console.log(`#${entry.rank}: ${entry.title} (${entry.score}/10)`);
});

Recommendation Engine

async function getSimilarToTop(genres: string[], limit = 5) {
  const topAnime = await getTopAnime(1, 100);
  
  // Find top anime matching user's preferred genres
  const recommendations = topAnime.data.filter(anime => 
    anime.genres.some(g => genres.includes(g.name))
  ).slice(0, limit);
  
  return recommendations;
}

// Get top Action/Fantasy anime
const recs = await getSimilarToTop(['Action', 'Fantasy'], 5);
interface TrendingStats {
  topAiring: JikanAnime[];
  avgScore: number;
  mostCommonGenre: string;
}

async function getTrendingStats(): Promise<TrendingStats> {
  const airing = await getTopAnime(1, 25, 'airing');
  
  const avgScore = airing.data.reduce((sum, a) => sum + a.score, 0) / airing.data.length;
  
  const genreCounts = new Map<string, number>();
  airing.data.forEach(anime => {
    anime.genres.forEach(g => {
      genreCounts.set(g.name, (genreCounts.get(g.name) || 0) + 1);
    });
  });
  
  const mostCommonGenre = Array.from(genreCounts.entries())
    .sort((a, b) => b[1] - a[1])[0][0];
  
  return {
    topAiring: airing.data,
    avgScore: Math.round(avgScore * 100) / 100,
    mostCommonGenre
  };
}

const stats = await getTrendingStats();
console.log(`Trending genre: ${stats.mostCommonGenre}`);
console.log(`Average score: ${stats.avgScore}/10`);

Error Handling

API request failed: 404
Error
Invalid page number (beyond available pages)
try {
  await getTopAnime(999999);
} catch (error) {
  console.error('Page not found');
}
API request failed: 429
Error
Rate limit exceeded (after retries)
try {
  await getTopAnime();
} catch (error) {
  console.error('Too many requests, try again later');
}
Network errors
Error
Connection issues or timeouts
try {
  await getTopAnime();
} catch (error) {
  if (error instanceof TypeError) {
    console.error('Network error - check connection');
  }
}

API Endpoint

Calls the Jikan API endpoint:
GET https://api.jikan.moe/v4/top/anime?page={page}&limit={limit}&filter={filter}
Documentation: Jikan Top Anime API

See Also

searchAnime()

Search anime by query string

Seasonal Anime

Get anime by season and year

Components

React components for anime display

API Overview

Complete API reference and types

Build docs developers (and LLMs) love