# openboxing_api.py import requests from requests.exceptions import ContentDecodingError BASE_URL = "https://openboxing.org/api" def _get_json(url: str): """ Helper to fetch JSON from URL, working around broken Brotli responses. First try without 'br', then fall back to identity if decoding fails. """ # 1) Prefer gzip/deflate and explicitly *exclude* brotli headers = {"Accept-Encoding": "gzip, deflate, identity"} try: resp = requests.get(url, headers=headers, timeout=15) resp.raise_for_status() return resp.json() except ContentDecodingError: # 2) If decoding still blows up, force no compression resp = requests.get(url, headers={"Accept-Encoding": "identity"}, timeout=15) resp.raise_for_status() return resp.json() def get_all_champions(): """ Fetch all champions/fighters from Open Boxing API. Returns a list of fighter dictionaries. """ url = f"{BASE_URL}/champions/all.json" try: return _get_json(url) except Exception as e: print(f"[get_all_champions] Error fetching champions: {e}") return [] def find_champion_by_name(all_champs, name: str): """ Search for a fighter/champion by name. Returns the first match dict or None if not found. """ name_lower = name.lower().strip() for champ in all_champs: print(champ) first = champ['name'].get('first', '').lower() last = champ['name'].get('last', '').lower() full_name = f"{first} {last}".strip() print(full_name) if name_lower in full_name: print("FOUND CHAMPION: ", champ) return champ return None def get_all_bouts(): """ Fetch all bouts from Open Boxing API. Returns a list of bout dictionaries. """ url = f"{BASE_URL}/bouts/all.json" try: bouts = _get_json(url) return bouts if isinstance(bouts, list) else [] except Exception as e: print(f"[get_all_bouts] Error fetching bouts: {e}") return [] def get_bouts_for_champion(bouts, champion_id: int): """ Fetch all bouts/fights for a given champion ID. Returns a list of bout dictionaries. """ champ_bouts = [] for bout in bouts: boxers = bout.get("boxers", {}) boxerA = boxers.get("boxerA", {}) boxerB = boxers.get("boxerB", {}) if boxerA.get("championId") == champion_id or boxerB.get("championId") == champion_id: print(boxerA, boxerB) champ_bouts.append(bout) print("CHAMP BOUT INFO FROM API: ") print(champ_bouts) return champ_bouts