BoardGameGeek (BGG) provides an XML-based REST API known as BGG XML API2. It allows programmatic access to board game metadata, user collections, play logs, rankings, and user ratings.
- Base URL:
https://boardgamegeek.com/xmlapi2/ - Response Format: XML
- Documentation Portal: https://boardgamegeek.com/using_the_xml_api
Important (Authentication Required): BGG now requires an API token for XML API access. Requests without a valid Bearer token return
HTTP 401 Unauthorizedwith the headerWWW-Authenticate: Bearer realm="xml api".To obtain API access:
- Log into your account on BoardGameGeek.
- Visit https://boardgamegeek.com/using_the_xml_api to register your application and generate an API key / Bearer token.
- Pass the token in the HTTP
Authorizationheader:Authorization: Bearer YOUR_API_TOKEN
- Rate Limit: Keep request rates conservative (maximum 1–2 requests per second / 20–30 requests per minute). Aggressive querying triggers
HTTP 429 Too Many Requestsor Cloudflare blocks. - User-Agent: Always provide an explicit, identifying
User-Agentheader (e.g.User-Agent: BoardgameSortingApp/1.0 (contact@example.com)). - Caching: Cache responses locally whenever possible. Game details rarely change, so static information should not be re-requested repeatedly.
Retrieves all games in a user's collection, along with personal ratings, status (e.g. owned), and comments.
- URL:
https://boardgamegeek.com/xmlapi2/collection?username={username}&stats=1&own=1 - Query Parameters:
Parameter Description username(Required) BGG account username. own1to return only games marked as owned (0for not owned).stats1to include rating and statistical data (includingaverageweight).subtypeFilter by item subtype (default: boardgame, options includeboardgameexpansion,boardgameaccessory).excludesubtypeExclude a subtype (e.g., excludesubtype=boardgameexpansion).brief1to return abbreviated results.
When requesting a collection that is not already cached on BGG's servers, BGG returns an HTTP 202 Accepted status code with the message:
<message>Your request for this collection has been accepted and will be processed. Please try again later for this request.</message>Clients must handle this asynchronously:
- Check the HTTP status code.
- If
202, wait for 3 to 5 seconds. - Retry the identical request until
200 OKis returned.
<items totalitems="1" termsofuse="...">
<item objecttype="thing" objectid="13" subtype="boardgame" collid="123456">
<name sortindex="1">Catan</name>
<yearpublished>1995</yearpublished>
<image>https://cf.geekdo-images.com/...</image>
<thumbnail>https://cf.geekdo-images.com/...</thumbnail>
<stats minplayers="3" maxplayers="4" minplaytime="60" maxplaytime="120" playingtime="90" numowned="150000">
<rating value="N/A">
<usersrated value="120000" />
<average value="7.13" />
<bayesaverage value="6.95" />
<stddev value="1.54" />
<median value="0" />
<ranks>
<rank type="subtype" id="1" name="boardgame" friendlyname="Board Game Rank" value="450" bayesaverage="6.95" />
</ranks>
</rating>
</stats>
<status own="1" prevowned="0" fortrade="0" want="0" wanttoplay="0" wanttobuy="0" wishlist="0" preordered="0" lastmodified="2024-01-01 12:00:00" />
<numplays>10</numplays>
<comment>Length: 75.1 Category: Strategy</comment>
</item>
</items>Fetches complete metadata for specific items (games, expansions, accessories).
- URL:
https://boardgamegeek.com/xmlapi2/thing?id={id}&stats=1&versions=1 - Query Parameters:
Parameter Description id(Required) BGG Thing ID. Can be a comma-separated list of IDs for batch querying (e.g. id=13,30549,224517).stats1to include rating stats, rank, and complexity weight (averageweight).versions1to include version information (publishers, languages, box dimensions).videos1to include video links.comments1to include user reviews and comments (paginated).marketplace1to include current marketplace listings.
<items termsofuse="...">
<item type="boardgame" id="13">
<thumbnail>...</thumbnail>
<image>...</image>
<name type="primary" sortindex="1" value="Catan" />
<description>In Catan, players try to be the dominant force...</description>
<yearpublished value="1995" />
<minplayers value="3" />
<maxplayers value="4" />
<statistics page="1">
<ratings>
<usersrated value="120000" />
<average value="7.13" />
<bayesaverage value="6.95" />
<averageweight value="2.3125" />
</ratings>
</statistics>
</item>
</items>Searches games by title.
- URL:
https://boardgamegeek.com/xmlapi2/search?query={query}&type=boardgame&exact=1 - Query Parameters:
Parameter Description querySearch term (URL encoded). typeFilter by type: boardgame,boardgameexpansion,boardgameaccessory,videogame,rpgitem.exact1to restrict matches to exact name matches.
/xmlapi2/plays: Retrieves logged game plays for a user or item (username={user},id={thing_id})./xmlapi2/user: User profiles, buddies, and guilds (name={username})./xmlapi2/hot: Trending games (type=boardgame)./xmlapi2/guild: Guild members and announcements (id={guild_id}).
Below is an example showing how to fetch the collection, poll for HTTP 202 completion, and parse directly into records matching Boardgame-Sorting:
import time
import urllib.request
import xml.etree.ElementTree as ET
BGG_API_TOKEN = "YOUR_BEARER_TOKEN" # Generated at https://boardgamegeek.com/using_the_xml_api
USERNAME = "YourBggUsername"
BASE_URL = "https://boardgamegeek.com/xmlapi2"
HEADERS = {
"Authorization": f"Bearer {BGG_API_TOKEN}",
"User-Agent": "BoardgameSorting/1.0 (https://github.com/Talgarr/Boardgame-Sorting)"
}
def fetch_bgg_collection(username: str, max_retries: int = 10, delay: int = 4) -> ET.Element:
"""
Fetches a user's owned board game collection, handling HTTP 202 polling.
"""
url = f"{BASE_URL}/collection?username={username}&own=1&stats=1&subtype=boardgame"
req = urllib.request.Request(url, headers=HEADERS)
for attempt in range(max_retries):
try:
with urllib.request.urlopen(req) as resp:
status = resp.status
content = resp.read()
if status == 200:
return ET.fromstring(content)
elif status == 202:
print(f"Collection request queued by BGG (HTTP 202). Retrying in {delay}s...")
time.sleep(delay)
else:
raise RuntimeError(f"Unexpected status {status}")
except urllib.error.HTTPError as e:
if e.code == 202:
print(f"Collection request queued by BGG (HTTP 202). Retrying in {delay}s...")
time.sleep(delay)
else:
raise e
raise TimeoutError("Timed out waiting for BGG collection generation.")
def parse_collection_games(root: ET.Element):
"""
Parses items from the collection XML into records matching Boardgame-Sorting.
"""
games = []
for item in root.findall("item"):
name_el = item.find("name")
name = name_el.text if name_el is not None else "Unknown"
# Extract average weight (complexity)
avgweight = 0.0
stats_el = item.find("stats")
if stats_el is not None:
rating_el = stats_el.find("rating")
if rating_el is not None:
weight_el = rating_el.find("averageweight")
if weight_el is not None and weight_el.get("value"):
try:
avgweight = float(weight_el.get("value"))
except ValueError:
pass
# Extract comment containing Length and Category
comment_el = item.find("comment")
comment_text = comment_el.text if (comment_el is not None and comment_el.text) else ""
length = None
category = None
for line in comment_text.splitlines():
line = line.strip()
if line.startswith("Length:"):
raw_len = line.replace("Length:", "").strip().replace(",", ".")
try:
length = float(raw_len)
except ValueError:
pass
elif line.startswith("Category:"):
category = line.replace("Category:", "").strip()
if length is not None:
games.append({
"objectname": name,
"avgweight": avgweight,
"length": length,
"category": category
})
return games