Build a fantasy football lineup optimizer in Python
Quick answer: Pull this week's projections for QB, RB, WR and TE, keep your roster, drop anyone who can't play, sort by projected points, and fill each slot with the best player left, leaving FLEX for last. The script below does that in about 50 lines with requests. It takes 4 API calls a run and works on a free GridIron Data key for the current week. Basic adds the snap share, news and matchups that settle the close calls.
- Language
- Python 3
- Library
- requests
- Calls per run
- 4
- Plan
- Free
What does the optimizer look like?
Get a free key, then run pip install requests, set GRIDIRON_API_KEY and NFL_WEEK, and replace ROSTER with your players. Ids look like First Last#POS; /players/search?name= finds them.
import os
import requests
API = "https://api.gridirondata.com/api/v1"
WEEK = int(os.environ["NFL_WEEK"]) # a free key answers the current week
SLOTS = ["QB", "RB", "RB", "WR", "WR", "TE", "FLEX"]
FLEX = {"RB", "WR", "TE"}
ROSTER = {
"Josh Allen#QB", "Saquon Barkley#RB", "Bijan Robinson#RB", "James Cook#RB",
"Justin Jefferson#WR", "Puka Nacua#WR", "CeeDee Lamb#WR", "Jaylen Waddle#WR",
"Brock Bowers#TE", "Michael Mayer#TE",
}
session = requests.Session()
session.headers["x-api-key"] = os.environ["GRIDIRON_API_KEY"]
def projections(position):
r = session.get(f"{API}/projections/{WEEK}",
params={"position": position, "scoring": "ppr"}, timeout=10)
r.raise_for_status()
return r.json()["projections"]
rows = [p for pos in ("QB", "RB", "WR", "TE") for p in projections(pos)
if p["player_id"] in ROSTER and p.get("available", True)]
rows.sort(key=lambda p: p["projected_points"], reverse=True)
used, total = set(), 0
for slot in SLOTS: # FLEX is last, so it gets the best player left over
allowed = FLEX if slot == "FLEX" else {slot}
pick = next((p for p in rows if p["position"] in allowed
and p["player_id"] not in used), None)
if pick is None:
print(f"{slot:<5} EMPTY")
continue
used.add(pick["player_id"])
total += pick["projected_points"]
flag = "" if pick["injury_status"] == "ACTIVE" else f' ({pick["injury_status"]})'
print(f'{slot:<5} {pick["player_name"]:<22} {pick["projected_points"]:>5.1f}{flag}')
print(f"{'TOTAL':<28} {total:>5.1f}")
print("Bench:", ", ".join(p["player_name"] for p in rows if p["player_id"] not in used))
Why does filling FLEX last work?
In a standard lineup each position slot takes that position's best players, and FLEX can only take what's left. Filling the fixed slots first and FLEX last gives the highest projected total, so you don't need a solver. Use a linear program only for salary-cap DFS, where one expensive player changes who else you can afford.
How are injuries and byes handled?
Players who can't play (Out, IR or on bye) come back with available: false and 0 projected points, and the script drops them. Questionable players stay in with a flag so you can decide. Run it again on Sunday morning, since injury status is checked every 2 minutes during the day and pregame projections refresh after inactives.
How do I make it better?
| Upgrade | Endpoint | Plan |
|---|---|---|
| Pull your roster from Sleeper | Join on ESPN id | Free |
| Compare with last week's real output | /stats/{player_id}/{season} | Free (last week) |
| Prefer players with a rising role | /snaps/{player_id} | Basic |
| Penalize boom/bust players | /deviations/{player_id} | Basic |
| React to game-day changes | /injuries/changes | Pro |
The start/sit model guide goes further. Running this for your own league is fine on any plan; a public or paid product has license rules.
Frequently asked questions
What is the best API for a fantasy football lineup optimizer?
You need weekly projections and injury status in one call. GridIron Data returns both per player in PPR, half-PPR or standard, and a free key covers the current week.
Do I need PuLP or a linear solver?
Not for a season-long lineup. Sorting by projection and filling FLEX last gives the best total. A solver helps with salary-cap DFS.
How many API calls does it use?
Four per run, one per position.
Does it work with half-PPR?
Yes. Change scoring to half or standard in the projections call.