import os import requests import json import dotenv from typing import Dict, Any dotenv.load_dotenv() class BricksetAPI: """Class for interacting with the Brickset API""" def __init__(self, debug: bool = False): self.username = os.getenv("BRICKSET_USERNAME") self.password = os.getenv("BRICKSET_PASS") self.api_key = os.getenv("BRICKSET_API_KEY") self.debug = debug self.headers = {"UserAgent": "Edderkop/0.1"} self.user_hash = None def login(self) -> Dict[str, Any]: """Login to Brickset API and get user hash""" url = "https://brickset.com/api/v3.asmx/login" params = { "username": self.username, "password": self.password, "apiKey": self.api_key, } response = requests.get(url, params=params, headers=self.headers) if self.debug: print(f"[@DEBUG] Login response: {response.status_code}") print(f"[@DEBUG] Response content: {response.text}") try: data = response.json() self.user_hash = data.get("hash") if not self.user_hash: raise ValueError("No hash received in login response") return data except json.JSONDecodeError as e: print(f"[@ERROR] Failed to decode JSON response: {e}") print(f"[@DEBUG] Raw response: {response.text}") raise def get_set(self, set_number: str) -> Dict[str, Any]: """Get LEGO set information by set number""" if not self.user_hash: self.login() url = "https://brickset.com/api/v3.asmx/getSets" params = { "apiKey": self.api_key, "userHash": self.user_hash, "params": json.dumps({"setNumber": f"{set_number}-1"}), } response = requests.get(url, params=params, headers=self.headers) if self.debug: print(f"[@DEBUG] Get set response: {response.status_code}") print(f"[@DEBUG] Response content: {response.text}") if response.status_code == 200: try: data = response.json() if not data.get("sets"): raise ValueError(f"No set data found for {set_number}") set_data = data["sets"][0] our_set = { "set_num": set_data["number"], "set_name": set_data["name"], "set_image": set_data["image"]["thumbnailURL"], "set_barcode": set_data["barcode"]["UPC"], "set_retailprice": round(set_data["LEGOCom"]["US"]["retailPrice"]), } # Calculate adjusted price (10% markup) retail_price = our_set["set_retailprice"] our_set["set_adjustredprice"] = retail_price + ( (10 / 100) * retail_price ) # Set Playwell inventory name if our_set["theme"] == "Duplo": our_set["pw_name"] = ( f"{our_set['set_num']} - DUPLO {our_set['set_name']}" ) else: our_set["pw_name"] = f"{our_set['set_num']} - {our_set['set_name']}" return our_set except json.JSONDecodeError as e: # print(f"[@ERROR] Failed to decode JSON response: {e}") # print(f"[@DEBUG] Raw response: {response.text}") raise except KeyError as e: # print(f"[@ERROR] Missing expected field in response: {e}") # print(f"[@DEBUG] Response data: {data}") raise elif response.status_code == 500: raise Exception( "Internal Server Error: Please check API key and parameters." ) else: raise Exception(f"Unexpected response: {response.status_code}") def example(): client = BricksetAPI(debug=True) try: set_info = client.get_set("10931") print(set_info) except Exception as e: print(f"Error: {e}")