pythonpython-requeststwitch

Can't get cover URL from IGDB API


I'm just getting started with the IGDB API and I'm trying to get all the data I need for a search result using requests in Python. I have the search function working fine, but the API only returns ID values for some elements of the search result and not the actual data, such as for the image cover, genres, or platforms.

Right now I'm trying to extract the image cover URL from the API, but when I try the covers endpoint it just seems to be returning the same random images and not an image or images for the game I'm looking for. I'm not sure if I need to specify the image id somehow, but I've also tried that and got the same result.

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'))

Also tried:

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'))

Result: a list of seemingly random image urls, not the image(s) for the game I'm looking for.


Solution

  • IGDB's API works off a SQL like query written as a string in the body part of the request.

    You are trying to make the request as parameters instead, and making a GET request, instead of a POST request

    So the following should do the trick

    import json
    import requests
    
    token = get_token()
    
    client_id = "my id"
    
    headers = {"Client-ID":client_id, "Authorization":"Bearer " + token['access_token']}
    
    game_id = "84920"
    
    response = requests.post("https://api.igdb.com/v4/games", headers=headers, data='fields cover.image_id; where id='+game_id+';')
    
    image = json.loads(response.content.decode('utf-8'))
    

    Note: I'm selecting against the /games endpoint and using an expander to join another table. As the covers endpoint the id of the cover is not the game ID, so your original request won't fetch the right cover anyway.

    You would also want to grab the image_id instead and construct a URL as the url returned in the cover is generally not useful for most use cases.

    So drop the image_id into https://images.igdb.com/igdb/image/upload/t_{size}/{image_id}.jpg

    I generally prefer/use cover_big as the size