yahoo-fantasy Node.js Client

repository·master·Indexed 42 days ago

https://github.com/whatadewitt/yahoo-fantasy-sports-api

A Node.js client for the Yahoo Fantasy Sports API (v5.3.0) that provides high-level abstractions for managing leagues, teams, players, and transactions. It features automatic OAuth2 authentication and token refreshing, along with specialized resource collections for Games, Leagues, Players, Transactions, and Teams.

Tokens
1.8K
Snippets
7
Records
8
Agent score
52%

What's inside yahoo-fantasy

  1. Access resource collections and singletons

    master

    The YahooFantasy instance acts as a gateway to various resource managers. It provides both single resource instances (e.g., client.league) and collection instances (e.g., client.leagues).

    Available resources include:

    • game / games
    • league / leagues
    • player / players
    • team / teams
    • transaction / transactions
    • roster
    • user
  2. Authenticate using OAuth2 flow

    master

    The YahooFantasy client supports the standard OAuth2 authorization flow. This involves two main steps:

    1. auth(res, state): Initiates the authorization request. If used in a web server context (e.g., Express), pass the response object (res). The method will attempt to redirect the user to Yahoo's login page. You can optionally pass a state parameter for CSRF protection.
    2. authCallback(req, cb): Call this method in your redirect handler once the user has authorized your app. It exchanges the code from the query parameters for access and refresh tokens. It expects a request object (req) containing req.query.code.
    // 1. Redirect user to Yahoo
    app.get('/login', (req, res) => {
      client.auth(res, 'some-state-string');
    });
    
    // 2. Handle the callback
    app.get('/callback', (req, res) => {
      client.authCallback(req, (err, tokens) => {
        if (err) return res.status(500).send(err);
        // tokens contains { access_token, refresh_token, state }
        res.send('Authenticated!');
      });
    });
  3. Make API requests with api()

    master

    The api() method is the low-level interface for all Yahoo Fantasy API calls. It handles URL construction, parameter encoding (defaulting to format=json), and automatic token refreshing.

    Signature: api(method, url, [postData])

    • method: HTTP method ('GET' or 'POST').
    • url: The full Yahoo API URL (e.g., https://fantasysports.yahooapis.com/fantasy/v2/...).
    • postData (optional): The body for POST requests.

    Note on Authentication: If yahooUserToken is set, it uses Bearer token authentication. If not set, it falls back to OAuth 1.0a signature generation using the consumer credentials.

    // Example GET request
    const data = await client.api('GET', 'https://fantasysports.yahooapis.com/fantasy/v2/games/nfl/summaries?format=json');
    
    // Example POST request
    const postData = { key: 'value' };
    const result = await client.api('POST', 'https://fantasysports.yahooapis.com/fantasy/v2/some/endpoint', postData);
  4. Manage user tokens and refreshing

    master

    The client manages authentication state via yahooUserToken and yahooRefreshToken. You can manually update these if you are resuming a session:

    • setUserToken(token): Sets the current access token.
    • setRefreshToken(token): Sets the current refresh token.
    • refreshToken(cb): Manually triggers a token refresh using the stored yahooRefreshToken.

    If an API call fails due to an expired token, the client automatically attempts to call refreshToken and retries the original request once.

    // Manually setting tokens from a database
    client.setUserToken('stored_access_token');
    client.setRefreshToken('stored_refresh_token');
    
    // Manually refreshing
    client.refreshToken((err, newTokens) => {
      if (err) console.error(err);
      else console.log('Refreshed:', newTokens);
    });
  5. Access Yahoo! Fantasy data collections

    master

    The collections entrypoint provides access to various data collections for querying Yahoo! Fantasy Sports data. You can import these collections to interact with specific data sets such as Games, Leagues, Players, Transactions, and Teams. Each exported collection acts as a specialized interface for retrieving that specific type of resource.

    import { Games, Leagues, Players, Transactions, Teams } from './collections/index.mjs';
    
    // Example usage (assuming the collections follow standard query patterns):
    // const games = await Games.get(...);
    // const players = await Players.get(...);
  6. Access Yahoo! Fantasy API resources

    master

    The resources/index.mjs entrypoint provides exported resource classes that serve as the primary interface for interacting with different entities in the Yahoo! Fantasy API. You can import these classes to perform operations related to games, leagues, players, rosters, transactions, teams, and users.

    import { Game, League, Player, Roster, Transaction, Team, User } from './resources/index.mjs';
    
    // Example usage (assuming an initialized client/context):
    // const leagueData = await League.get(leagueId);
    // const playerData = await Player.get(playerId);
  7. Initialize the YahooFantasy client

    master

    The yahoo-fantasy library exports a default class YahooFantasy which serves as the primary entrypoint for interacting with the Yahoo Fantasy Sports API. To use the library, require the module and instantiate the class. Note that the library uses ESM internally via the esm loader.

    const YahooFantasy = require('yahoo-fantasy');
    const yahoo = new YahooFantasy();
  8. Reference the available data collections

    master

    The following collections are exported from the collections module:

    • Games: Access to game-related data.
    • Leagues: Access to league-related data.
    • Players: Access to player-related data.
    • Transactions: Access to transaction-related data.
    • Teams: Access to team-related data.
    export { GamesCollection as Games };
    export { LeagueCollection as Leagues };
    export { PlayerCollection as Players };
    export { TransactionCollection as Transactions };
    export { TeamCollection as Teams };