Skip to content

How to use the Sleeper API ​

A tutorial for visualizing your fantasy football season
Written by Kevin Tian

I built ffwrapped with data from the public Sleeper API. For a first project, try a chart your league mates can check: total points scored by each team. The manager who finished second in points and missed the playoffs will know exactly which bar is theirs.

You need a league ID for this. You can leave the passwords and API keys out of it.

1. Setup Your Project ​

We'll fetch two lists: the league's users, who have names, and its rosters, which have point totals. The owner ID lets us match them up. I'm using Vite to start a React project. Its setup guide covers the prerequisites.

Run the following commands in your terminal of choice.

bash
# Create a new Vite project with React
npm create vite@latest fantasy-football-app -- --template react

# Navigate to the project directory
cd fantasy-football-app

# Install dependencies
npm install

# Install additional packages we'll need
npm install apexcharts react-apexcharts

I used Vue and TypeScript for ffwrapped. Here I'm using React. The same two requests work in either.

2. Create Your Visualization Component ​

Create src/PointsGraph.jsx and paste this complete component. It fetches the league's users and rosters, matches owners to names, and sorts teams by total points.

The loading and error checks come before the chart options: chartData starts as null, so the chart cannot read its points until the request finishes.

jsx
import { useState, useEffect } from "react";
import Chart from "react-apexcharts";

export default function PointsGraph({ leagueId }) {
  const [chartData, setChartData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    setIsLoading(true);
    setError(null);
    setChartData(null);

    async function fetchData() {
      try {
        const base = `https://api.sleeper.app/v1/league/${leagueId}`;
        const [users, rosters] = await Promise.all(
          ["users", "rosters"].map(async (endpoint) => {
            const response = await fetch(`${base}/${endpoint}`, {
              signal: controller.signal,
            });
            if (!response.ok) throw new Error("Request failed");
            return response.json();
          })
        );
        if (!Array.isArray(users) || !Array.isArray(rosters)) {
          throw new Error("League data is unavailable");
        }

        const userNames = Object.fromEntries(
          users.map((user) => [user.user_id, user.display_name])
        );
        const teams = rosters.map((roster) => ({
          name: userNames[roster.owner_id] || `Team ${roster.roster_id}`,
          points:
            (roster.settings?.fpts ?? 0) +
            (roster.settings?.fpts_decimal ?? 0) / 100,
        }));
        teams.sort((a, b) => b.points - a.points);

        if (!controller.signal.aborted) {
          setChartData({
            teams: teams.map((team) => team.name),
            points: teams.map((team) => Number(team.points.toFixed(2))),
          });
        }
      } catch (err) {
        if (!controller.signal.aborted) {
          setError("Could not load league data. Check the league ID and try again.");
        }
      } finally {
        if (!controller.signal.aborted) setIsLoading(false);
      }
    }

    fetchData();
    return () => controller.abort();
  }, [leagueId]);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div role="alert">{error}</div>;
  if (!chartData?.teams.length) return <div>No roster data available.</div>;

  const chartOptions = {
    chart: { type: "bar", toolbar: { show: false } },
    plotOptions: { bar: { horizontal: true, distributed: true } },
    xaxis: { categories: chartData.teams },
    title: { text: "Total Fantasy Points by Team", align: "center" },
  };

  return (
    <Chart
      options={chartOptions}
      series={[{ name: "Total Points", data: chartData.points }]}
      type="bar"
      height={500}
    />
  );
}

The effect runs again when leagueId changes; its cleanup cancels the previous request. The roster's fpts and fpts_decimal fields hold the whole and fractional parts of its points total. An ownerless roster uses a team-number label instead of an undefined name.

For chart styling options, see the ApexCharts documentation.

3. Update App Component ​

The last step is to import the PointsGraph component we just made in the App.jsx file. Make sure to update LEAGUE_ID with your own league's id. It can be found in the url of the Sleeper homepage https://sleeper.com/leagues/<LEAGUE_ID>.

jsx
import PointsGraph from "./PointsGraph";
import "./App.css";

function App() {
  // Replace with your actual league ID
  const LEAGUE_ID = "...";

  return (
    <div className="app">
      <header>
        <h1>Fantasy Football Points Visualization</h1>
      </header>
      <main>
        <PointsGraph leagueId={LEAGUE_ID} />
      </main>
    </div>
  );
}

export default App;

Compare the tallest bar with the points-for leader in your league standings. That's the first number I'd check before sending the chart around.

tutorial image

The original example project is on GitHub. Use the component above for this updated walkthrough.

4. Next Steps ​

Now that you know how to retrieve, manipulate, and display data from the Sleeper API, take a look at the other API endpoints. Some project ideas include a draft board with player grades, charts comparing weekly points scored, and tables with all-time win/loss records. For working examples, explore ffwrapped draft grades, power rankings, and league history.

If you want more league analysis resources, start with the Fantasy Football League Tools and API Guide. For another data-focused article, check out Does draft pick really matter? for a fantasy football analysis built from real league results.

Last updated: