无法从IGDB API获取指定游戏封面URL的技术求助
问题:IGDB API返回ID而非实际数据,调用covers端点无法获取目标游戏封面
我刚开始使用IGDB API,通过Python的requests库获取搜索结果的完整数据。目前搜索功能正常,但API仅返回部分元素的ID值(如游戏封面、类型、平台信息),而非实际内容。
尝试提取游戏封面URL时,调用covers端点返回的是看似随机的图片,而非目标游戏的封面。试过指定game_id或image_id,结果依旧不符合预期。
尝试过的代码
代码1:指定game_id
import json import requests token = get_token() client_id = "my id" headers = {"Client-ID":client_id, "Authorization":"Bearer " + token['access_token']} game_id = "84920" params = {"fields":"url", "id":game_id} response = requests.get("https://api.igdb.com/v4/covers", params=params, headers=headers) image = json.loads(response.content.decode('utf-8'))
代码2:指定image_id
image_id = "134616" params = {"fields":"url", "image_id":image_id} response = requests.get("https://api.igdb.com/v4/covers", params=params, headers=headers) image = json.loads(response.content.decode('utf-8'))
问题现象
返回的是随机图片URL列表,并非目标游戏的封面。
解决方案
IGDB API的核心查询逻辑不支持通过GET请求的params传递过滤条件,必须使用POST请求,并在请求体中编写IGDB自定义的查询语句。之前的GET请求无法正确解析过滤规则,导致返回随机数据。
正确获取指定游戏封面的代码
方法1:通过游戏ID关联获取封面
import json import requests token = get_token() client_id = "my id" headers = { "Client-ID": client_id, "Authorization": f"Bearer {token['access_token']}", "Content-Type": "text/plain" # 必须设置该请求头 } game_id = "84920" # IGDB查询语法:先指定返回字段,再用where过滤关联的游戏ID query = f"fields url; where game = {game_id};" response = requests.post("https://api.igdb.com/v4/covers", headers=headers, data=query) image_data = json.loads(response.content.decode('utf-8')) if image_data: print("目标游戏封面URL:", image_data[0]['url']) else: print("未找到对应游戏的封面")
方法2:通过封面ID直接获取
cover_id = "134616" query = f"fields url; where id = {cover_id};" response = requests.post("https://api.igdb.com/v4/covers", headers=headers, data=query) image_data = json.loads(response.content.decode('utf-8')) if image_data: print("指定ID的封面URL:", image_data[0]['url']) else: print("未找到该ID对应的封面")
进阶优化:一次性获取完整游戏数据
如果需要同时获取游戏名称、封面、类型、平台等完整信息,无需单独调用多个端点,直接在games端点使用关联查询即可:
query = "fields name, cover.url, genres.name, platforms.name; where id = 84920;" response = requests.post("https://api.igdb.com/v4/games", headers=headers, data=query) game_full_data = json.loads(response.content.decode('utf-8')) print(json.dumps(game_full_data, indent=2))
该请求会直接返回包含封面URL、类型名称、平台名称的完整游戏数据,省去了手动关联ID的步骤。
内容的提问来源于stack exchange,提问作者TCombu
相关产品推荐
相关产品推荐

