API Integration for EPG Enrichment
Status: Reference
Last Updated: 2025-11-02
Related Docs: EPG Generation Guide, REST API
Code Location: backend/epgoat/clients/api_client.py, backend/epgoat/services/api_enrichment.py
Enhance EPG data with real-time sports event information from TheSportsDB and ESPN
Overview
The EPG Generator includes real-time sports data enrichment from dual API sources, providing:
- Rich descriptions - Detailed event information including venue, teams, and context
- Verified times - Accurate start/end times from official sources
- Team metadata - Team names, logos, badges, and additional information
- Venue data - Stadium/arena names and locations
- Dual API fallback - TheSportsDB primary, ESPN fallback for maximum coverage
- Dynamic logo generation - Split team logos for vs. matchups
- Smart rate limiting - Automatic tier detection and protection
API Status: ENABLED BY DEFAULT ✅
API enrichment is now enabled by default for all EPG generation.
Free Tier (30 req/min):
- ✅ Events by date -
eventsday.php - ✅ All leagues -
all_leagues.php - ✅ Team lookup -
lookup_all_teams.php - ⚠️ Rate limited to ~30 requests/minute
Paid Tier ($4.99/month) - RECOMMENDED:
- ✅ All free tier endpoints
- ✅ Search endpoints (searchteams, searchevents)
- ✅ 100 requests per minute (3x faster)
- ✅ 2-minute livescores (Soccer, NFL, NBA, MLB, NHL)
- ✅ Premium API methods
- ✅ YouTube video highlights
Key Endpoints:
- ✅ eventsday.php - Get events by league and date (PRIMARY)
- ✅ searchevents.php - Search events by team names (PREMIUM)
- ✅ lookup_all_teams.php - Get all teams in a league
- ✅ Event data includes: teams, times, venues, logos, scores
Getting Started
Quick Start (Using Your Paid API Key)
You have a paid TheSportsDB account! Set your API key to unlock 100 req/min:
Method 1: Environment Variable (Recommended)
export THESPORTSDB_API_KEY="your-paid-api-key-here"
Method 2: Command Line Flag
python backend/epgoat/run_provider.py \
--provider tps \
--api-key "your-paid-api-key-here"
Method 3: .env File
# Create .env file in project root
echo "THESPORTSDB_API_KEY=your-paid-api-key-here" > .env
Rate Limiting Protection
The system automatically detects your tier and applies appropriate rate limits:
- Free tier keys (
"3","123","1"): 30 req/min - Paid tier keys (anything else): 100 req/min
Features: - ✅ Token bucket rate limiter - ✅ Automatic backoff for 429 (Too Many Requests) - ✅ Automatic retry for 503 (Server Unavailable) - ✅ Exponential backoff (2s, 4s, 8s) - ✅ Never exceeds your rate limit
Subscribe to TheSportsDB (if you haven't already)
- Subscribe: https://www.patreon.com/thedatadb ($4.99/month)
- Get your API key from your Patreon account
-
Set the key using one of the methods above
-
Test the integration:
cd backend/epgoat
python -c "
from api_client import TheSportsDBClient
client = TheSportsDBClient(api_key='your-key')
teams = client.search_teams('Lakers')
print(f'Found {len(teams)} teams')
"
Alternative Free APIs
If you want API enrichment without paying, here are alternatives:
1. ESPN API (Unofficial, Free)
- Access: No key required
- Endpoints:
site.api.espn.com/apis/site/v2/sports/{sport}/{league}/scoreboard - Coverage: NFL, NBA, MLB, NHL, Soccer
- Limitations: Unofficial, may change
- Reliability: ⭐⭐⭐⭐
2. API-Sports (Limited Free)
- URL: https://api-sports.io/
- Free Tier: 100 requests/day
- Coverage: Football, Basketball, Hockey, American Football
- Reliability: ⭐⭐⭐⭐⭐
- Note: 100 requests/day may not be enough for large playlists
3. The Odds API (Limited Free)
- URL: https://the-odds-api.com/
- Free Tier: 500 requests/month
- Coverage: All major sports
- Best for: Verifying event start times
- Reliability: ⭐⭐⭐⭐
Implementation Status
Completed ✅
- [x] TheSportsDB API client
- [x] EPG enrichment module
- [x] Configuration system
- [x] Rate limiting
- [x] Caching support
- [x] Fallback system
In Progress 🔄
- [ ] Integration with main EPG generator
- [ ] Comprehensive testing
- [ ] Documentation
Future Enhancements 📋
- [ ] ESPN API client (free alternative)
- [ ] API-Sports integration
- [ ] Multi-API fallback strategy
- [ ] Response caching to reduce API calls
- [ ] Batch processing for efficiency
Usage Examples
With API Enabled (Premium Key)
from api_enrichment import EPGEnricher
from datetime import datetime
from zoneinfo import ZoneInfo
enricher = EPGEnricher(api_key="your-premium-key", enable_api=True)
enriched = enricher.enrich_event(
channel_name="NBA 01: Lakers vs Celtics",
family="NBA",
payload="Lakers vs Celtics",
parsed_time=datetime(2025, 10, 24, 19, 30, tzinfo=ZoneInfo("America/Chicago")),
target_date="2025-10-24",
target_timezone=ZoneInfo("America/Chicago")
)
if enriched:
print(f"Title: {enriched['title']}")
print(f"Description: {enriched['description']}")
print(f"Start: {enriched['start_time']}")
print(f"End: {enriched['end_time']}")
Without API (Fallback Mode)
enricher = EPGEnricher(enable_api=False)
# Returns None, falls back to parsed data
enriched = enricher.enrich_event(...) # Returns None
# But you can still use fallback durations
duration = enricher.get_fallback_duration("NBA") # 150 minutes
Configuration
Environment Variables
# API Key
export THESPORTSDB_API_KEY="your-key"
# Enable/disable API
export EPGOAT_API_ENABLED="true"
# Rate limit override
export THESPORTSDB_RATE_LIMIT="2.0"
Config File
Edit backend/config/api_config.yml:
api:
enabled: true
key: "your-key"
rate_limit_seconds: 2.0
timeout_seconds: 10
cache_enabled: true
cache_ttl_seconds: 86400
fallback:
enabled: true
durations:
NBA: 150
NFL: 210
# ... etc
API Endpoints Used
TheSportsDB Endpoints (Premium Required)
| Endpoint | Purpose | Rate Limit |
|---|---|---|
/searchteams.php |
Find teams by name | 1 req/2s |
/searchevents.php |
Find events by name | 1 req/2s |
/eventsday.php |
Events by league & date | 1 req/2s |
/eventsnextleague.php |
Upcoming league events | 1 req/2s |
/eventsnext.php |
Upcoming team events | 1 req/2s |
/lookupevent.php |
Event details by ID | 1 req/2s |
Benefits of API Enrichment
Without API:
<programme start="20251024193000 -0500" stop="20251024223000 -0500" channel="nba-01">
<title>Live Event: Lakers vs Celtics</title>
<category>Sports / Basketball / NBA</category>
</programme>
With API:
<programme start="20251024200000 -0500" stop="20251024230000 -0500" channel="nba-01">
<title>Los Angeles Lakers vs Boston Celtics</title>
<desc>NBA 2024-25 Regular Season at Crypto.com Arena, Los Angeles.
Lakers (5-2) host the Celtics (6-1) in this classic rivalry matchup.</desc>
<category>Sports / Basketball / NBA</category>
<icon src="https://www.thesportsdb.com/images/media/league/badge/nba.png"/>
</programme>
Troubleshooting
403 Forbidden Errors
Problem: Getting 403 errors when calling API Solution: You need a premium API key ($3/month Patreon subscription)
# Check your API key
echo $THESPORTSDB_API_KEY
# Test with premium key
python -c "
from api_client import TheSportsDBClient
client = TheSportsDBClient(api_key='your-premium-key')
teams = client.search_teams('Lakers')
print(f'Success: Found {len(teams)} teams')
"
Rate Limiting
Problem: Too many API requests Solution: Enable caching and batch processing
api:
cache_enabled: true
cache_ttl_seconds: 86400 # Cache for 24 hours
No Events Found
Problem: API returns no events for a date Solution: Try different date formats or use event search
# Try searching by event name instead
events = client.search_events("Lakers Celtics")
Cost Analysis
TheSportsDB Premium
- Cost: $3/month (Patreon)
- Requests: Effectively unlimited with rate limiting
- Coverage: All major sports worldwide
- ROI: Excellent for serious EPG generation
Free Alternatives Comparison
| API | Free Tier | Cost to Upgrade | Coverage |
|---|---|---|---|
| TheSportsDB | Limited (403s) | $3/month | ⭐⭐⭐⭐⭐ |
| API-Sports | 100 req/day | $10/month | ⭐⭐⭐⭐ |
| The Odds API | 500 req/month | $10/month | ⭐⭐⭐ |
| ESPN (unofficial) | Unlimited | N/A | ⭐⭐⭐⭐ |
Recommendation
For now: Use the EPG generator without API enrichment. It works great!
When ready: Subscribe to TheSportsDB ($3/month) for the best enrichment experience.
Alternative: I can implement ESPN API integration (free, unofficial) if you want enrichment without paying.
Next Steps
Want me to: 1. Keep as-is - EPG generator works without API (recommended for now) 2. Add ESPN API - Free alternative for enrichment 3. Wait for premium key - Integrate when you subscribe to TheSportsDB
Let me know which option you prefer!
Note: This documentation was last reviewed on 2025-11-02. API status is ENABLED BY DEFAULT as of 2025-10-24.