
How to Build a Real-Time Sports Score API with Scraping
Building a sports score API is a classic scraping project. Here's how to scrape live scores and serve them through a clean FastAPI endpoint. Architecture Three components: a scraper fetching live scores, a Redis cache for fast reads, and a FastAPI endpoint serving structured data. Setting Up import requests from bs4 import BeautifulSoup import redis import json from datetime import datetime from fastapi import FastAPI from contextlib import asynccontextmanager import threading import time SCRAPER_KEY = " YOUR_SCRAPERAPI_KEY " r = redis . Redis ( host = " localhost " , port = 6379 , db = 0 , decode_responses = True ) def fetch ( url ): resp = requests . get ( " http://api.scraperapi.com " , params = { " api_key " : SCRAPER_KEY , " url " : url , " render " : " true " }, timeout = 15 ) return BeautifulSoup ( resp . text , " html.parser " ) Scraping Live Scores def scrape_nba_scores (): url = " https://www.espn.com/nba/scoreboard " soup = fetch ( url ) games = [] scoreboard = soup . find_a
Continue reading on Dev.to Python
Opens in a new tab


