Python SDK
Official Python SDK for AltSportsLeagues.ai. Install with pip install altsportsleagues and start integrating sports data into your applications.
π Installation
pip install altsportsleaguesFor development:
pip install altsportsleagues[dev]π¦ Package Overview
from altsportsleagues import (
AltSportsLeagues, # Main client
League, # League data model
Event, # Event data model
Sport, # Sport data model
Odds, # Betting odds model
AltSportsLeaguesError, # Base exception
AuthenticationError, # Auth errors
ValidationError, # Validation errors
RateLimitError # Rate limit errors
)π§ Client Configuration
Basic Setup
from altsportsleagues import AltSportsLeagues
# Initialize with API key
client = AltSportsLeagues(api_key="your_api_key_here")
# Test connection
health = client.ping()
print(f"API Status: {health['status']}")Advanced Configuration
client = AltSportsLeagues(
api_key="your_api_key",
base_url="https://api.altsportsleagues.ai", # Optional
timeout=30 # Request timeout in seconds
)Environment Variables
export ALTSPORTSLEAGUES_API_KEY="your_key_here"
export ALTSPORTSLEAGUES_BASE_URL="https://api.altsportsleagues.ai"
export ALTSPORTSLEAGUES_TIMEOUT="30"import os
from altsportsleagues import AltSportsLeagues
client = AltSportsLeagues(api_key=os.getenv("ALTSPORTSLEAGUES_API_KEY"))π Working with Leagues
Listing Leagues
# Get all leagues
leagues = client.get_leagues()
print(f"Found {len(leagues)} leagues")
# Filter by sport type
basketball_leagues = client.get_leagues(sport_type="basketball")
combat_leagues = client.get_leagues(sport_type="combat")
# Display league info
for league in basketball_leagues[:5]:
print(f"{league.league_name} - Compliance: {league.compliance_score}/100")Getting League Details
# Get specific league
nba = client.get_league("nba")
print(f"Name: {nba.league_name}")
print(f"Sport: {nba.sport_bucket}")
print(f"Teams: {nba.number_of_teams}")
print(f"Founded: {nba.founded_year}")
print(f"Compliance: {nba.compliance_score}/100")
print(f"Status: {nba.get_onboarding_progress()}")Creating Leagues
# Create a new league
new_league = client.create_league({
"league_name": "My Basketball League",
"sport_bucket": "team",
"contact_email": "admin@myleague.com",
"description": "Competitive basketball league",
"website": "https://mybasketball.com",
"location": "San Francisco, CA",
"number_of_teams": 12,
"interested_in_betting": True
})
print(f"Created league: {new_league.league_name}")
print(f"League ID: {new_league.league_id}")π Working with Events
Querying Events
# Get upcoming events
upcoming_events = client.get_events(limit=20)
# Filter by league
nba_events = client.get_events(league_id="nba", limit=10)
# Filter by date range
from datetime import datetime, timedelta
start_date = datetime.now().isoformat()
end_date = (datetime.now() + timedelta(days=7)).isoformat()
week_events = client.get_events(
start_date=start_date,
end_date=end_date,
limit=50
)
# Display events
for event in nba_events:
print(f"{event.home_team} vs {event.away_team}")
print(f"Date: {event.start_time}")
print(f"Venue: {event.venue}")
print(f"Status: {event.status}")
print("---")Creating Events
# Create multiple events
events_batch = [
{
"league_id": "nba",
"home_team": "Los Angeles Lakers",
"away_team": "Boston Celtics",
"start_time": "2024-01-15T20:00:00Z",
"venue": "Crypto.com Arena"
},
{
"league_id": "nba",
"home_team": "Golden State Warriors",
"away_team": "Miami Heat",
"start_time": "2024-01-16T19:30:00Z",
"venue": "Chase Center"
}
]
result = client.create_events_batch(events_batch)
print(f"Created {result['successful']} events")Batch Upload from CSV
# Upload events from CSV file
result = client.create_events_from_csv("my_events.csv", "nba")
print(f"Processed: {result['successful']} successful, {result['failed']} failed")CSV Format:
home_team,away_team,start_time,venue,season
Los Angeles Lakers,Boston Celtics,2024-01-15T20:00:00Z,Crypto.com Arena,2023-2024
Golden State Warriors,Miami Heat,2024-01-16T19:30:00Z,Chase Center,2023-2024π° Working with Odds
Getting Event Odds
# Get odds for a specific event
odds_list = client.get_odds("nba_2024_01_15_lakers_celtics")
for odds in odds_list:
print(f"Bookmaker: {odds.bookmaker}")
print(f"Market: {odds.market}")
print(f"Live: {odds.is_live}")
for selection in odds.selections:
print(f" {selection['name']}: {selection['odds']}")
print("---")Finding Best Odds
# Find best odds across all bookmakers
def find_best_odds(event_id, market_type="moneyline"):
odds_list = client.get_odds(event_id)
market_odds = [o for o in odds_list if o.market == market_type]
if not market_odds:
return None
best_odds = {}
for odds in market_odds:
for selection in odds.selections:
name = selection['name']
odds_value = selection['odds']
if name not in best_odds or odds_value > best_odds[name]['odds']:
best_odds[name] = {
'odds': odds_value,
'bookmaker': odds.bookmaker,
'selection': selection
}
return best_odds
# Example usage
best_moneyline = find_best_odds("nba_game_123", "moneyline")
for team, data in best_moneyline.items():
print(f"{team}: {data['odds']} at {data['bookmaker']}")π Compliance & Onboarding
Submitting League Questionnaire
# Submit questionnaire for compliance assessment
questionnaire = {
"league_name": "My League",
"contact_email": "admin@myleague.com",
"sport_bucket": "team",
"has_official_rules": True,
"has_liability_insurance": True,
"has_player_contracts": True,
"interested_in_betting": True,
"preferred_betting_model": "pool",
"expected_betting_volume": "medium"
}
result = client.submit_league_questionnaire(questionnaire)
print(f"Submission status: {result['status']}")Checking Compliance Status
# Get compliance assessment
compliance = client.get_compliance_status("my_league_id")
print(f"Overall Score: {compliance['overall_score']}/100")
print(f"Level: {compliance['compliance_level']}")
print("Strengths:")
for strength in compliance['strengths']:
print(f" β {strength}")
print("Gaps to address:")
for gap in compliance['gaps']:
print(f" β {gap}")π¨ Error Handling
Exception Types
from altsportsleagues import (
AltSportsLeaguesError,
AuthenticationError,
ValidationError,
RateLimitError,
NotFoundError
)
try:
leagues = client.get_leagues()
except AuthenticationError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
print(f"Invalid request: {e}")
except NotFoundError as e:
print(f"Resource not found: {e.resource_type} {e.resource_id}")
except AltSportsLeaguesError as e:
print(f"API error: {e}")Retry Logic
import time
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10)
)
def resilient_api_call(func, *args, **kwargs):
"""Make API calls with automatic retry"""
return func(*args, **kwargs)
# Usage
try:
leagues = resilient_api_call(client.get_leagues)
except Exception as e:
print(f"Failed after retries: {e}")π Performance Optimization
Caching
from functools import lru_cache
import time
@lru_cache(maxsize=100)
def cached_get_league(league_id):
return client.get_league(league_id)
# Cache with TTL
class TTLCache:
def __init__(self, ttl_seconds=300): # 5 minutes
self.cache = {}
self.ttl = ttl_seconds
def get(self, key, fetch_func):
if key in self.cache:
data, timestamp = self.cache[key]
if time.time() - timestamp < self.ttl:
return data
data = fetch_func()
self.cache[key] = (data, time.time())
return data
# Usage
odds_cache = TTLCache(ttl_seconds=60) # 1 minute TTL
def get_cached_odds(event_id):
return odds_cache.get(f"odds_{event_id}", lambda: client.get_odds(event_id))π§ Data Models
League Model
class League:
league_id: str
league_name: str
sport_bucket: str # "combat", "team", "large_field", "racing", "other"
contact_email: str
description: Optional[str]
website: Optional[str]
location: Optional[str]
founded_year: Optional[int]
number_of_teams: Optional[int]
compliance_score: int # 0-100
onboarding_status: str # "pending", "approved", "onboarded"
created_at: Optional[str]
updated_at: Optional[str]
def is_compliant(self) -> bool:
return self.compliance_score >= 70
def get_onboarding_progress(self) -> str:
# Returns human-readable status
passEvent Model
class Event:
event_id: str
league_id: str
home_team: str
away_team: str
start_time: str # ISO 8601
venue: Optional[str]
status: str # "scheduled", "in_progress", "completed", "cancelled"
home_score: Optional[int]
away_score: Optional[int]
season: Optional[str]
created_at: Optional[str]
updated_at: Optional[str]
def is_upcoming(self) -> bool:
# Check if event is in the future
pass
def get_winner(self) -> Optional[str]:
# Return winning team or None for tie
passOdds Model
class Odds:
odds_id: str
event_id: str
bookmaker: str
market: str # "moneyline", "spread", "over/under", etc.
selections: List[Dict] # [{'name': str, 'odds': float, 'volume': int}]
last_updated: str
is_live: bool
def get_best_odds(self, selection_name: str) -> Optional[float]:
# Get best odds for specific selection
passπ API Reference
Client Methods
| Method | Description |
|---|---|
ping() | Test API connectivity |
get_leagues(**filters) | Get leagues with optional filters |
get_league(league_id) | Get specific league details |
create_league(data) | Create new league |
get_events(**filters) | Get events with optional filters |
create_events_batch(events) | Create multiple events |
create_events_from_csv(file_path, league_id) | Create events from CSV |
get_historical_events(league_id, **filters) | Get historical events |
get_odds(event_id) | Get betting odds for event |
get_markets(**filters) | Get available betting markets |
get_sports() | Get all sports |
get_sport_buckets() | Get sport classifications |
submit_league_questionnaire(data) | Submit compliance questionnaire |
get_compliance_status(league_id) | Get compliance assessment |
get_sportsbook_matches(league_id) | Get sportsbook recommendations |
get_api_info() | Get API information |
π Links
Ready to integrate? pip install altsportsleagues and start building!