npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sleeper-api

v1.0.5

Published

Sleeper api from https://sleeper.com/

Downloads

6

Readme

SleeperAPI

License Version Downloads

SleeperAPI is a TypeScript client library for interacting with the Sleeper API. It provides a comprehensive set of methods to fetch and manage data related to users, leagues, rosters, matchups, drafts, players, and more. Whether you're building a fantasy sports application or automating league management tasks, SleeperAPI offers a robust and type-safe way to integrate with Sleeper's platform.

Table of Contents

Features

  • TypeScript Support: Fully typed interfaces and classes for type-safe development.
  • Comprehensive Coverage: Access to users, leagues, rosters, matchups, drafts, players, and more.
  • Customizable Axios Instance: Option to provide a custom Axios instance for advanced configurations.
  • Error Handling: Graceful handling of API errors with meaningful messages.
  • Utility Functions: Helper functions like getAvatarUrl for common tasks.

Installation

You can install SleeperAPI using Bun, npm, or Yarn.

Using Bun

bun add sleeperapi axios

Using npm

npm install sleeperapi axios

Using Yarn

yarn add sleeperapi axios

Note: This package depends on axios. Ensure it's installed in your project.

Usage

Initialization

Import the SleeperAPI class and create an instance. You can optionally provide a custom Axios instance if you need to customize request configurations.

import SleeperAPI from 'sleeperapi';
import axios from 'axios';

// Optional: Create a custom Axios instance
const customAxios = axios.create({
  baseURL: 'https://api.sleeper.app/v1',
  timeout: 15000, // 15 seconds timeout
});

// Initialize SleeperAPI with the custom Axios instance
const sleeper = new SleeperAPI(customAxios);

// Or initialize with default settings
const sleeperDefault = new SleeperAPI();

Examples

Fetch a User by Username

import SleeperAPI from 'sleeperapi';

const sleeper = new SleeperAPI();

async function fetchUser() {
  try {
    const user = await sleeper.getUserByUsername('john_doe');
    console.log(user);
  } catch (error) {
    console.error(error.message);
  }
}

fetchUser();

Get All Leagues for a User

import SleeperAPI from 'sleeperapi';

const sleeper = new SleeperAPI();

async function fetchLeagues() {
  try {
    const leagues = await sleeper.getLeaguesForUser('user_id_123', 'nfl', '2023');
    console.log(leagues);
  } catch (error) {
    console.error(error.message);
  }
}

fetchLeagues();

Retrieve All Players for a Sport

import SleeperAPI from 'sleeperapi';

const sleeper = new SleeperAPI();

async function fetchPlayers() {
  try {
    const players = await sleeper.getAllPlayers('nfl');
    console.log(players);
  } catch (error) {
    console.error(error.message);
  }
}

fetchPlayers();

API Reference

User Methods

  • getUserByUsername(username: string): Promise<User>
    • Fetch a user by their username.
  • getUserById(userId: string): Promise<User>
    • Fetch a user by their user ID.

League Methods

  • getLeaguesForUser(userId: string, sport: string, season: string): Promise<League[]>

    • Retrieve all leagues for a specific user.
  • getLeague(leagueId: string): Promise<League>

    • Get details of a specific league.
  • getRosters(leagueId: string): Promise<Roster[]>

    • Fetch all rosters within a league.
  • getUsersInLeague(leagueId: string): Promise<User[]>

    • Get all users participating in a league.
  • getMatchups(leagueId: string, week: number): Promise<Matchup[]>

    • Retrieve all matchups for a given week in a league.
  • getWinnersBracket(leagueId: string): Promise<BracketMatchup[]>

    • Get the winners bracket of a league.
  • getLosersBracket(leagueId: string): Promise<BracketMatchup[]>

    • Get the losers bracket of a league.
  • getTransactions(leagueId: string, round: number): Promise<Transaction[]>

    • Fetch all transactions for a specific round in a league.
  • getTradedPicks(leagueId: string): Promise<DraftPick[]>

    • Retrieve all traded draft picks in a league.

Roster Methods

(Similar methods related to rosters can be documented here if applicable.)

Matchup Methods

(Similar methods related to matchups can be documented here if applicable.)

Draft Methods

  • getDraftsForUser(userId: string, sport: string, season: string): Promise<Draft[]>

    • Fetch all drafts associated with a user.
  • getDraftsForLeague(leagueId: string): Promise<Draft[]>

    • Retrieve all drafts within a league.
  • getDraft(draftId: string): Promise<Draft>

    • Get details of a specific draft.
  • getPicksInDraft(draftId: string): Promise<Pick[]>

    • Fetch all picks in a draft.
  • getTradedPicksInDraft(draftId: string): Promise<DraftPick[]>

    • Retrieve all traded picks in a draft.

Player Methods

  • getAllPlayers(sport: string): Promise<{ [playerId: string]: Player }>

    • Fetch all players for a specific sport.
  • getTrendingPlayers(sport: string, type: 'add' | 'drop', lookbackHours?: number, limit?: number): Promise<TrendingPlayer[]>

    • Get trending players based on recent activity.

Error Handling

SleeperAPI handles errors gracefully by catching them and throwing meaningful error messages. Ensure to use try-catch blocks when making asynchronous calls to handle potential errors.

try {
  const user = await sleeper.getUserByUsername('invalid_username');
} catch (error) {
  console.error(error.message); // Outputs a user-friendly error message
}

Common error messages include:

  • Bad Request: Invalid request parameters.
  • Not Found: Resource does not exist.
  • Too Many Requests: Rate limiting in effect.
  • Internal Server Error: Server-side issues.
  • Service Unavailable: Service is temporarily offline.
  • No Response: No response received from the server.
  • Unexpected Error: Other unforeseen errors.

Contributing

Contributions are welcome! If you'd like to contribute to SleeperAPI, please follow these steps:

  1. Fork the Repository

  2. Create a Feature Branch

    git checkout -b feature/YourFeature
  3. Commit Your Changes

    git commit -m "Add some feature"
  4. Push to the Branch

    git push origin feature/YourFeature
  5. Open a Pull Request

Please ensure your code follows the project's coding standards and includes relevant tests.

License

This project is licensed under the MIT License.


Note: Replace https://img.shields.io/npm/l/sleeperapi, https://img.shields.io/npm/v/sleeperapi, and https://img.shields.io/npm/dm/sleeperapi with actual badge URLs if you have set up badges for your package. Also, ensure to create a LICENSE file in your repository if you haven't already.

If you encounter any issues or have suggestions for improvements, feel free to open an issue or submit a pull request.