A Python wrapper for the Sleeper Fantasy API
Project description
sleeper_fantasy_api
An object-oriented Python wrapper for the Sleeper Fantasy Football API, designed to simplify working with data on users, leagues, transactions, and more.
The Sleeper API is currently read-only.
H/T to other repos who created similar functions before me:
Table of Contents
Overview
This project simplifies accessing the Sleeper API, allowing users to easily fetch player stats, league data, transactions, and more in an object-oriented manner. The wrapper supports complex queries using AND and OR logic, with a focus on easy integration and flexibility.
Features
Core Features
- Fetching player stats, leagues, and transactions
- Supports advanced player search logic (e.g.,
AND/ORconditions) - Object-oriented design for ease of use and integration
- Comprehensive error handling with specific exception types
Advanced Features (New!)
- Player Projections: Access weekly player projections (undocumented Sleeper API endpoint)
- Persistent Caching: File-based caching system for expensive API calls
- Retry Logic: Exponential backoff for rate limits and network errors
- NFL State: Get current NFL season, week, and game state
- Scoring Type Detection: Automatically detect PPR/Half-PPR/Standard scoring
Planned Features
- Custom setting of CONVERT_RESULT global variable by user
Installation
To install locally, follow these steps:
Prerequisites:
- Python 3.10
Installation:
git clone https://github.com/smallery/sleeper_fantasy_api.git
cd sleeper_fantasy_api
pip install -r requirements.txt
Usage
Basic Usage
Get started with simple user and league queries:
from sleeper_api.client import SleeperClient
from sleeper_api.endpoints.user_endpoint import UserEndpoint
from sleeper_api.endpoints.league_endpoint import LeagueEndpoint
# Initialize client
client = SleeperClient()
user_endpoint = UserEndpoint(client)
league_endpoint = LeagueEndpoint(client)
# Get user
user = user_endpoint.get_user("your_username")
print(f"User: {user.display_name}")
# Get user's leagues for 2024
leagues = user_endpoint.get_leagues(user.user_id, 'nfl', '2024')
# Get league details
league = league_endpoint.get_league_by_id(leagues[0]['league_id'])
print(f"League: {league.name}")
Advanced Usage: Player Projections
Access weekly player projections and calculate team totals:
Important:
- Projections (this endpoint) = Pre-game predictions for ALL players
- Actuals (matchups endpoint) = Post-game results for ROSTERED players only in a specific league
- For league-agnostic actual stats, use external APIs (ESPN, NFL.com, etc.)
from sleeper_api.endpoints.projections_endpoint import ProjectionsEndpoint
from sleeper_api.persistent_cache import PersistentCache
# Initialize projections endpoint with caching
persistent_cache = PersistentCache()
projections_endpoint = ProjectionsEndpoint(client, persistent_cache)
# Get current NFL state
nfl_state = league_endpoint.get_nfl_state(convert_results=True)
print(f"Season: {nfl_state.season}, Week: {nfl_state.week}")
# Option 1: Fetch all player projections for one week (cached for 24 hours)
projections = projections_endpoint.get_projections(
season=int(nfl_state.season),
week=nfl_state.week
)
# Returns ALL projection data from Sleeper API
# Includes: pts_ppr, pts_half_ppr, pts_std, pass_yd, rush_yd, rec, etc.
# NOTE: These are PROJECTIONS (predictions), not actuals
# Option 2: Get projection for a single player (uses cache)
player_proj = projections_endpoint.get_player_projection(
player_id="4018", # Patrick Mahomes
season=int(nfl_state.season),
week=nfl_state.week
)
if player_proj:
print(f"Projected PPR Points: {player_proj.get('pts_ppr')}")
print(f"Projected Passing Yards: {player_proj.get('pass_yd')}")
print(f"Projected Pass TDs: {player_proj.get('pass_td')}")
# Option 3: Bulk fetch projections for multiple weeks
season_projections = projections_endpoint.get_season_projections(
season=2024,
weeks=[1, 2, 3, 4] # Or None for all 18 weeks
)
# Returns: {1: {players...}, 2: {players...}, 3: {players...}, 4: {players...}}
# Option 4: Track one player across multiple weeks
mahomes_season = projections_endpoint.get_player_season_projections(
player_id="4018",
season=2024,
weeks=[1, 2, 3, 4] # Or None for all 18 weeks
)
for week, proj in mahomes_season.items():
if proj:
print(f"Week {week}: {proj.get('pts_ppr')} projected PPR points")
# Get actual points scored (after games are played)
matchups = league_endpoint.get_matchups(league_id, nfl_state.week, convert_results=True)
for matchup in matchups:
print(f"Roster {matchup.roster_id}: {matchup.points:.1f} actual points scored")
# Compare projections vs actuals
scoring_type = projections_endpoint.get_scoring_type(league_id)
for matchup in matchups:
projected = projections_endpoint.calculate_team_projection(
starters=matchup.starters,
projections=projections,
scoring_type=scoring_type
)
actual = matchup.points
diff = actual - projected
print(f"Roster {matchup.roster_id}: {actual:.1f} actual vs {projected:.1f} projected (diff: {diff:+.1f})")
Example Scripts
Run the included example scripts from the command line:
Basic usage - Get user info:
python3 examples/example_basic_usage.py -u [YOUR_USERNAME]
Advanced usage - Gather user, league, draft, and player data:
python3 examples/example_advanced_usage.py -u [YOUR_USERNAME]
Player search - Access the player database with complex queries:
python3 examples/example_player_endpoint_search_queries.py
Projections - Demonstrate player projections and advanced features:
python3 examples/example_projections_usage.py -u [YOUR_USERNAME]
Endpoints
The current endpoints available through the API are the following:
Core Endpoints
-
User Endpoint:
user_endpoint: Retrieve information about a user using their username or user_id- Get user leagues for a specific season
-
League Endpoint:
league_endpoint: Retrieve information on leagues with a given league_id- Get rosters, users, matchups, brackets, transactions, and traded picks
- NEW:
get_nfl_state()- Get current NFL season/week information
-
Player Endpoint:
player_endpoint: Retrieve the database of players from Sleeper along with key attributes- Built-in caching to store player data locally (24-hour cache)
- Search players with complex AND/OR logic
- Get trending players (adds/drops)
-
Draft Endpoint:
draft_endpoint: Retrieve information about a draft (picks, users, trades) with a given draft_id
Advanced Endpoints (New!)
- Projections Endpoint:
projections_endpoint: Access weekly player projections from Sleeper- Methods:
get_projections(season, week)- Fetch all player projections for one weekget_player_projection(player_id, season, week)- Fetch single player projection for one weekget_season_projections(season, weeks=None)- Bulk fetch projections across multiple weeks (or all 18 weeks)get_player_season_projections(player_id, season, weeks=None)- Track one player across multiple weekscalculate_team_projection(starters, projections, scoring_type)- Calculate total team projectionget_scoring_type(league_id)- Auto-detect league scoring format (PPR/Half-PPR/Standard)
- Returns complete projection data: pts_ppr, pts_half_ppr, pts_std, plus individual stats (pass_yd, rush_yd, rec, etc.)
- Uses persistent file caching (24-hour TTL) to minimize API calls
For more details, refer to the full Sleeper API documentation.
Contributing
Contributions are welcome! To contribute:
- Fork the repository
- Create a new branch:
git checkout -b yourname/feature-name - Make your changes and add tests
- Run tests:
pytest - Format code:
flake8 sleeper_api - Submit a pull request
All PRs automatically run tests on Python 3.10, 3.11, and 3.12.
License
This project is licensed under the MIT License. See the LICENSE file for more information.
Contact
If you have any questions or issues, please contact Sam Mallery.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sleeper_fantasy_api-0.2.0.tar.gz.
File metadata
- Download URL: sleeper_fantasy_api-0.2.0.tar.gz
- Upload date:
- Size: 40.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
27487ec1c93da2867274363f6155c74869b99ade3dcd592c54d5d02d78c08313
|
|
| MD5 |
481a411aea900c4f8049cc2f6101a1c3
|
|
| BLAKE2b-256 |
e88b713808b61211b86e249564de02115a5867b448afcf74af6694644c50e9ea
|
File details
Details for the file sleeper_fantasy_api-0.2.0-py3-none-any.whl.
File metadata
- Download URL: sleeper_fantasy_api-0.2.0-py3-none-any.whl
- Upload date:
- Size: 33.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f84f725cf2e334665d76fa1741f124566182fa5f0d730495963bede6618f4ebd
|
|
| MD5 |
bf4aea4c5d57e4c131a99e920dbbdc19
|
|
| BLAKE2b-256 |
3fe71c095ff117ec26517ae46e70eb17eace8776ac040adffa0c792a6244e85d
|