Giter VIP home page Giter VIP logo

mkreiser / espn-fantasy-football-api Goto Github PK

View Code? Open in Web Editor NEW
296.0 21.0 73.0 4.7 MB

Connect to ESPN's fantasy football API via this JS API client for web and NodeJS. Available as an npm package.

Home Page: http://espn-fantasy-football-api.s3-website.us-east-2.amazonaws.com/

License: GNU Lesser General Public License v3.0

JavaScript 100.00%
espn api api-client fantasy-football football football-api npm-package

espn-fantasy-football-api's People

Contributors

carolinaguy89 avatar cmjarrett avatar mkreiser avatar ryantrappy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

espn-fantasy-football-api's Issues

espn_s2 cookie no longer exists?

Followed the docs but I couldn't find an espn_s2 cookie (I was able to find the other one). Has something changed here recently?

Any way to determine league name?

Hey! Thanks so much for making this package, phenomenal stuff. I was wondering, Is there a way, through the boxscore endpoint, to get the name of the league you're in?

Thanks!

Draft Order

This is a great tool and works super well. I was wondering if it was at all possible to add draft order to League Object for DraftSettings and/or Draft information. Thanks!

How to fix: TypeError: Client is not a constructor

Node-beginner here. I can't find a fix for the error message above, when declaring a new myClient variable.

Error message:

file:///Users/christopher.koch/dev/node_test/test.js:3
const myClient = new Client({ leagueId: 432132 });
                 ^

TypeError: Client is not a constructor
    at file:///Users/christopher.koch/dev/node_test/test.js:3:18
    at ModuleJob.run (node:internal/modules/esm/module_job:217:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
    at async loadESM (node:internal/process/esm_loader:34:7)
    at async handleMainPromise (node:internal/modules/run_main:66:12)

Node.js v20.8.0

Can someone tell me what i'm doing wrong?

Make Teams object available in Boxscore query

I'm having issues with multiple calls to several clients in one page.

Some of these calls could be minimized, if you make the teams array/object available in the results you get from a boxscore query. It's already there, you just need to provide it. Most people will want more than the teamid that is in the boxscore and it's the team data is already available in the same results you parse. FYI

Thanks!
Travis

Get Matchup / Scoring Period Dynamically

I wrote a little Discord Bot App that fetches box score data from our league. I'm currently returning scores based on a hard coded matchup/scoring period. Does anybody know how to get the matchup / scoring period dynamically based on the current week? Here is my code:

`const { Client } = require('espn-fantasy-football-api/node');
const { getName } = require('./player-mapping');
require('dotenv').config();

const leagueId = process.env.espn_leagueid;
const espnS2 = process.env.espn_espnS2;
const SWID = process.env.espn_swid;
const seasonId = process.env.espn_seasonid;

const myClient = new Client({ leagueId });

myClient.setCookies({ espnS2, SWID });

async function getEspnData() {
const getScores = await myClient.getBoxscoreForWeek({
seasonId,
matchupPeriodId: 1,
scoringPeriodId: 1
});
const matchupData = createEmbedFields(getScores);
const embedded = embedData(matchupData);
return embedded;
}

function createEmbedFields(boxScore) {
const matchupArrayData = boxScore.map(scores => {
const awayTeamId = getName(scores.awayTeamId.toString());
const homeTeamId = getName(scores.homeTeamId.toString());
const awayPoints = scores.awayScore.toString();
const homePoints = scores.homeScore.toString();
return [
{
name: awayTeamId,
value: awayPoints,
inline: true
},
{
name: homeTeamId,
value: homePoints,
inline: true
},
{
name: '\u200B',
value: '\u200B'
}
]
})
.flat();
return matchupArrayData;
}

function embedData(teamData) {
const fflEmbed = {
color: 0x0099ff,
title: 'Current Scores',
fields: teamData,
timestamp: new Date(),
};
return { embeds: [fflEmbed] }
}

module.exports = {
getEspnData,
embedData
};`

Working Example

Is there a very basic working example you could give me? I have the follow code:

const { Client } = require('espn-fantasy-football-api/node');
const axios = require('axios')

const leagueId = 30031
const seasonId = 2023

// const espnS2 = my espnS2 code
// const SWID = my SWID code

async function getLeagueData() {
  try {

    // const routeBase = `https://site.api.espn.com/${seasonId}/segments/0/leagues/${leagueId}`;
    // const routeParams = `?view=mMatchup&view=mMatchupScore&scoringPeriodId=${3}`;
    // const route = `${routeBase}${routeParams}`;
    // const data = await axios.get(route)
    // console.log('DATA : ', data)
    const client = new Client({ leagueId });

  //   // Fetch league info
    const leagueInfo = await client.getTeamsAtWeek({ seasonId, scoringPeriodId: 1 });
    console.log('League Info:', JSON.stringify(leagueInfo, null, 2));

  //   // Fetch teams (users) in the league
  //   const teams = await client.getTeamsAtWeek({ seasonId, scoringPeriodId: 1 });
  //   console.log('Teams:', JSON.stringify(teams, null, 2));

  //   // Fetch rosters in the league
  //   const rosters = await client.getBoxscoreForWeek({ seasonId, scoringPeriodId: 1 });
  //   console.log('Rosters:', JSON.stringify(rosters, null, 2));
  } catch (error) {
      console.error('Error fetching data:', error);
  }
}

getLeagueData()

The league id is just one I found on Google:

https://fantasy.espn.com/football/league?leagueId=30031

When I run this code, I just get back an empty array. When I try to use the axios version I get an error. When I use the client to put in my own person league, I also get an empty array. I made the league public but I also tried with the two codes and still got nothing.

I'm just looking to be able to get the league settings, rosters, and users based on a league id. Any way you can point me in the right direction? I had GPT look at the repo but still no luck. Thanks

Feature request: basic usage example

This is a documentation/example request that a provides an example (and associated documentation to run it) that displays basic information about the user's ESPN league. Likely Node.js based as to function with both private/public leagues.

This is geared towards either a complete novice programmer (hobbyist) or someone new to Node.js. It'd include every step, including how to start the Node.js server.

Converting from ESPN v2 API to v3

ESPN have updated their fantasy football API from v2 to v3. This project is built for v2 and requires significant work for update to v3. This issue tracks the necessary tasks to complete this conversion. The conversion work will occur on the v3-api-conversion branch (protected).

  • Update README with conversion work notice
  • Investigate new route structure
  • Compare v3 route structure to the class design of this project
  • Design new classes, reusing existing structure where appropriate
  • Prep codebase on v3-api-conversion branch for new design (remove deprecated code, etc)
  • Make changes to base classes (BaseObject, etc)
  • Implement new designs
  • Ensure JSDoc documentation is comprehensive and high-quality
  • Clean up unit tests if needed
  • Write integration tests
  • Write migration notes and update README
  • Merge v3-api-conversion branch to master
  • Publish 0.9.0 for testing
  • Publicize new work
  • Publish 1.0.0 for production
  • ๐ŸŽ‰

Add Typescript Types

Typescript can generate the declared types from JSDOC strings. Can we include the types in the npm package for typescript apps?

Team information has last season's names

Not sure what I'm doing wrong here but I'm calling the API and getting last season's team names. Is there some sort of caching issue? I get updated team abbreviations, but not team names.

I build a teamLookup to use in other areas of the app:

espnClient.getTeamsAtWeek({ seasonId: DEFAULT_SEASON_ID, scoringPeriodId: scoringPeriod }).then( response => {
            const teamLookupMap  = response.reduce((lookup, team) => ({ ...lookup, [team.id]: {
                id: team.id,
                abbreviation: team.abbreviation,
                name: team.name,
                logo: team.logoURL,
                wins: team.wins,
                losses: team.losses,
                divisionId: getTeamDivisionId(team.id)
            }}), {});
            resolve(teamLookupMap);
        }).catch(error => {
            console.log({error});
            reject('ERROR');
        });

DEFAULT_SEASON_ID = 2023
scoringPeriodId = 1

Private League Cookies

Having an issue getting data for a private league. I grabbed the espn_s2 value and the SWID via dev console but it's returning blank data.

Beginner's Help

Hi there,
I'm code informed enough to know that what's been built here is great. However, I don't have the technical skills to understand how to accomplish what I want.

I'm hoping to plug into this data set via a google sheet - all i want to pull in is player data (think biographical information - like DOB, current team, etc...etc...).

However, I don't know if that's possible from what is laid out here and if it is possible, could someone point me to the appropriate documentation so i can see what i need to do.

Points don't reflect live game counts

It seems like after a game is over, your points source is finally updated.

I think you either need to change it, use this other source, or a combination of both if a game is in progress.

The live score for a matchup period is found in the " schedule/(weeknum)/(AwayOrHome)/rosterForMatchupPeriod/appliedStatTotal

FYI

Question: is the maintainer still active?

๐Ÿ‘‹๐Ÿผ I'm checking in to see if the maintainer is still active and would like help getting this repository up-to-date. I am interested in using this API, but there are a lot of dependencies that need to be updated. Thanks!

Scoreboard Data from older years

So I read all about how ESPN deleted box scores from anything older than 1 year old.

The final scores are still available in the scoreboard.

Looking through the history of the codebase, I saw that their use to be a scoreboard class. Curious if that is now broken or if there are plans on bringing this functionality back?

Transactions

Is it possible to get transactions (add / drop) via the API?

League Status should be available

I'm going to code something up right now to get league status, but I wanted to put this out here. Every request has a "status" object that provides great detail about the league and the current week, etc. I think that should be available in every request, but should also be it's own request with no scoring period, etc. I'm using it to get the current week status, but there is alot of great info in there that can be passed along easily.

getTeamsByWeek being called twice?

I'm trying to figure out/debug what's going on inside your code and this is weird. I'm seeing a debug statement twice and I'm hoping I'm incorrect on what's going on here.

getTeamsAtWeek({ seasonId, scoringPeriodId }) {
    const routeBase = `${seasonId}/segments/0/leagues/${this.leagueId}`;
    const routeParams = `?scoringPeriodId=${scoringPeriodId}&view=mRoster&view=mTeam`;
    const route = `${routeBase}${routeParams}`;

    return axios.get(route, this._buildAxiosConfig()).then((response) => {
      const data = _.get(response.data, 'teams');
      console.log("In Client..");
      console.log(data);
      return _.map(data, (team) => (
        Team.buildFromServer(team, { leagueId: this.leagueId, seasonId })
      ));
    });
  }

I put the console.logs in by In Client, etc. and here is what I'm seeing in my console...
https://imgur.com/a/oMVQoa2

My code I'm calling looks like this..

await MyClientNorth.getTeamsAtWeek({ seasonId: this.seasonId, scoringPeriodId: this.scoringPeriodId }).then(async (teams) => {
      console.log(teams);
      
      await MyClientNorth.getBoxscoreForWeek({ seasonId: this.seasonId, scoringPeriodId: this.scoringPeriodId, 
        matchupPeriodId: this.matchupPeriodId }).then((boxscores) => {
          console.log("response received."+ boxscores.length);

....................

So what is going on? Why is In Client written out twice?

ESPN-Fantasy-Football-API --> Magic Mirror Module

Hello,

This isn't an issue with your API.

I think your API is awesome and am trying to use it for a Magic Mirror Module (MMM). I've never created a MMM, and may be taking this on too soon :-) as a newbie, but I am looking for guidance as to how to accomplish this. I was thinking I could just copy it and make necessary url updates, but there are some languages/processes I haven't worked with before.

Any suggestions as to where I could start? Or is there an easier way to copy/package for my purpose.

Any assistance/guidance is greatly appreciated.

Thanks,
Vicelady (Programming node.js newbie, somewhat)

Has anyone been able to pull live projected points out of the response?

I have been able to successfully edit this API for my needs by adding new things to pull out of the response. However, I can not seem to get schedule[i].away/home.totalProjectedPointsLive out of the response even though it is there. I'm curious if there is some issue with this particular field.

image

Refused to set unsafe header "Cookie"

I'm trying to set my cookies to be able to see my private league data on my webpage, but when I call BaseAPIObject.setCookies({espnS2: 'xxxxxx', SWID: '{xxxxx}'}) and then league.read() I get the error "Refused to set unsafe header "Cookie""

any solutions or workarounds for this?

I think it has something to do with axios/axios#319 but i'm not totally sure

Can't get boxscores without refresh

I'm using Ionic and Angular, etc. I have a dropdown for Week number. When I change the week number and call the same code for BoxScores, the boxscores.length is 0. It works the first page load, but then won't work on reloads. If I hardcode the week to any week number, it will load correctly the first time.

Also I know your code is getting the right data the second time on my update as the Network tab in chrome dev tools shows that it returned the right data. I'm assuming something has gone wrong in the getBoxscoresForWeek function on subsequent calls.

Help anyone?

Feat: Add addtional biographical information

I'm attempting to use this to feed a roster-management tool I'm building for a dynasty league. Is there a way in the ESPN api to get additional biographical information such as hieght/weight and draft year/pick number?

getTeamsAtWeek returning error with years before 2018

When using the Client.getTeamsAtWeek() function for league stats prior to 2018, the api fails with a 404.

(node:24828) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404
at createError (C:\scratch\GitHub\GentlemensLeague\node_modules\espn-fantasy-football-api\node-dev.js:1014:15)
at settle (C:\scratch\GitHub\GentlemensLeague\node_modules\espn-fantasy-football-api\node-dev.js:1289:12)
at IncomingMessage.handleStreamEnd (C:\scratch\GitHub\GentlemensLeague\node_modules\espn-fantasy-football-api\node-dev.js:361:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1220:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:24828) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:24828) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I've found that I can get the relevent Teams map by utilizing the same endpoint as the getHistoricalScoreboardForWeek() api, 'https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory/' and then building the Teams array.

--but I thought I would at least let anyone else know that it is possible to get historical information at least to 2011.

This is the hacky temporary workaround I made in node-dev.js if anyone needs it. I'll try to mock up a pull request that isn't my hack, maybe add a getHistoricalTeamsAtWeek() function instead for those years < 2018

 {
    key: "getTeamsAtWeek",
    value: function getTeamsAtWeek(_ref5) {
      var _this4 = this;
      console.log(_ref5.seasonId);
      if(_ref5.seasonId > 2017) {
        var seasonId = _ref5.seasonId,
        scoringPeriodId = _ref5.scoringPeriodId;

        var route = this.constructor._buildRoute({
          base: "".concat(seasonId, "/segments/0/leagues/").concat(this.leagueId),
          params: "?scoringPeriodId=".concat(scoringPeriodId, "&view=mRoster&view=mTeam")
        });
        console.log(route);

        return axios__WEBPACK_IMPORTED_MODULE_4___default.a.get(route, this._buildAxiosConfig()).then(function (response) {
          var data = lodash_get__WEBPACK_IMPORTED_MODULE_3___default()(response.data, 'teams');

          return lodash_map__WEBPACK_IMPORTED_MODULE_1___default()(data, function (team) {
            return _team_team__WEBPACK_IMPORTED_MODULE_9__["default"].buildFromServer(team, {
              leagueId: _this4.leagueId,
              seasonId: seasonId
            });
          });
        });
      } else {
        var _this4 = this;

        var seasonId = _ref5.seasonId,
            matchupPeriodId = _ref5.scoringPeriodId,
            scoringPeriodId = _ref5.scoringPeriodId;
  
        var route = this.constructor._buildRoute({
          base: "".concat(this.leagueId),
          params: "?scoringPeriodId=".concat(scoringPeriodId, "&seasonId=").concat(seasonId) + '&view=mMatchupScore&view=mScoreboard&view=mSettings&view=mTopPerformers&view=mTeam'
        });
  
        var axiosConfig = this._buildAxiosConfig({
          baseURL: 'https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory/'
        });
        console.log(route);
  
        return axios__WEBPACK_IMPORTED_MODULE_4___default.a.get(route, axiosConfig).then(function (response) {
          var data = lodash_get__WEBPACK_IMPORTED_MODULE_3___default()(response.data[0], 'teams');it 
  
          return lodash_map__WEBPACK_IMPORTED_MODULE_1___default()(data, function (team) {
            return _team_team__WEBPACK_IMPORTED_MODULE_9__["default"].buildFromServer(team, {
              leagueId: _this4.leagueId,
              seasonId: seasonId
            });
          });
        });
      }
    }

Can we get the teams avatar?

Any way we can get the URL for the teams avatar, and perhaps the league avatar?

v3 is looking good!

Thanks!
Travis

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.