How to get image URL property from Wikidata item by API?

If some Wikidata item (with ID: Qxxx) has image (P18) property, you can access it by MediaWiki API:

https://www.wikidata.org/w/api.php?action=wbgetclaims&property=P18&entity=Qxxx

The response will include:

"claims": {
        "P18": [{ "mainsnak": { "datavalue": { "value": "img_name.ext" }, "hash": ... }}]
}

where img_name.ext is the name of the image you are looking for.

The final image URL will be: https://upload.wikimedia.org/wikipedia/commons/a/ab/img_name.ext, where a and b are the first and the second chars of MD5 hashsum of the img_name.ext (with all whitespaces replaced by _).

Example: For item jaguar (Q35694) the API will returns image name "Junior-Jaguar-Belize-Zoo.jpg", which has MD5 hashsum("Junior-Jaguar-Belize-Zoo.jpg") = 213b31ec141dafebe457e49bcd7f9329, so a=2 and b=1, or the final image URL will be: https://upload.wikimedia.org/wikipedia/commons/2/21/Junior-Jaguar-Belize-Zoo.jpg

Note: The MD5 hashsum is for the name of the image file, not the P18[0].mainsnak.hash property included in the JSON body.


You can build URLs from the image property (Sample.png in the following example):

https://commons.wikimedia.org/w/index.php?title=Special:Redirect/file/Sample.png&width=300

See Wikimedia Commons' "Reusing content outside Wikimedia" documentation for more details.