Files
fpl_api_examples/team.py
T

85 lines
3.1 KiB
Python

"""Show an FPL team's summary and published gameweek squad (no login needed)."""
import argparse
import json
import sys
from urllib.error import URLError
from urllib.request import Request, urlopen
BASE_URL = "https://fantasy.premierleague.com/api/"
def get_json(path):
"""Send an HTTP GET request and turn the JSON response into a Python dict."""
request = Request(
BASE_URL + path,
headers={"User-Agent": "FPL-API-Demo/1.0", "Accept": "application/json"},
)
with urlopen(request, timeout=20) as response:
return json.load(response)
def positive_int(value):
number = int(value)
if number < 1:
raise argparse.ArgumentTypeError("must be a positive integer")
return number
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--team-id", type=positive_int, default=2134)
parser.add_argument("--gameweek", type=positive_int, choices=range(1, 39))
args = parser.parse_args()
# An entry is a manager's fantasy team, rather than a Premier League club.
team = get_json(f"entry/{args.team_id}/")
print(f"Team: {team['name']} (entry {args.team_id})")
print(f"Manager: {team['player_first_name']} {team['player_last_name']}")
print(f"Overall points: {team['summary_overall_points']}")
print(f"Overall rank: {team['summary_overall_rank']}")
gameweek = args.gameweek or team.get("current_event")
if not gameweek:
print("No gameweek squad is available yet.")
return
# Picks contain player IDs. Join them to bootstrap data to get readable names.
picks = get_json(f"entry/{args.team_id}/event/{gameweek}/picks/")
bootstrap = get_json("bootstrap-static/")
players = {player["id"]: player for player in bootstrap["elements"]}
clubs = {club["id"]: club["short_name"] for club in bootstrap["teams"]}
positions = {
position["id"]: position["singular_name_short"]
for position in bootstrap["element_types"]
}
print(f"\nGameweek {gameweek} squad (published at the deadline):")
print(f"{'Slot':<6} {'Player':<24} {'Club':<6} {'Pos':<5} Role")
for pick in sorted(picks["picks"], key=lambda item: item["position"]):
player = players[pick["element"]]
role = "Starter" if pick["position"] <= 11 else "Bench"
if pick["is_captain"]:
role += " (captain)"
elif pick["is_vice_captain"]:
role += " (vice captain)"
print(
f"{pick['position']:<6} {player['web_name']:<24} "
f"{clubs[player['team']]:<6} {positions[player['element_type']]:<5} {role}"
)
if picks.get("active_chip"):
print(f"Active chip: {picks['active_chip']}")
if __name__ == "__main__":
try:
main()
except (URLError, TimeoutError, OSError, ValueError, KeyError) as exc:
print(f"Unable to load team data: {exc}", file=sys.stderr)
print(
"Check the team ID and connection. Gameweek picks are available only "
"after that gameweek's deadline. The API may also be unavailable.",
file=sys.stderr,
)
sys.exit(1)