'How to reliably get the image used in the Wikipedia Infobox?

How do I (reliably) get the main image(s) used in the Wikipedia Infobox from the API?

This question has been asked before and the accepted answer admits that it is just a guess. Subsequent answers seem like a hack, at best and don't return the correct image.

For instance, the Jimi Hendrix Wikipedia entry uses "File:Jimi Hendrix 1967.png" as the main image in the InfoBox.

The updated answers suggest using this url but for Jimi Hendrix (and other topics) it often returns the wrong image.

If I pull in all the images there is no way to determine which is the image used in the Infobox.



Solution 1:[1]

Each Wikipedia page (e.g. Jimi Hendrix) is associated with an Wikidata item ID (Q5928). The main image for each Wikipedia article (usually this in the Infobox template) is kept by image (P18) property in Wikidata, and you can access it by MediaWiki Wikidata API:

https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&sites=enwiki&props=claims&titles=Jimi Hendrix

With this query you will get the Wikidata ID and the image name:

{
    ...
    "id": "Q5928", // Wikidata ID
    "claims":{
        ...
        "P18":[{
            "mainsnak":{
                "datavalue":{
                    "value":"Jimi Hendrix 1967.png", // The image name
                },
            },
        }],
        ...
    }
}

And here I explain how to get the image URL also by using Wikidata ID.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1