How to use Wikidata API to get ISO 3166-1 country codes?

Viewed 2000

I have been looking for examples online but can't find any for getting ISO 3166-1 country codes using the Wikidata API.

It's mentioned here that one can do https://query.wikidata.org/sparql or https://query.wikidata.org/bigdata/ldf, but I don't really know the difference. Also, I'm used to using APIs that return JSON, which it seems like neither of these two endpoints are. Is there a way to get JSON?

Overall, just wondering how to do this properly since examples are few and far between (or none at all).

2 Answers

Use this SPARQL query. It get the list of countries that has ISO 36 code value. After entering the previous URL, You can click Download button to download the response to JSON, CSV...etc.

#Find ISO 3166-1 alpha-2 country codes
SELECT ?country ?countryLabel ?code
WHERE
{
    ?country wdt:P297 ?code .
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Wikidata's API is not meant to be used for that kind of queries on the fly. You would need to get all items that have the property P297 (ISO 3166) which will give you the list of countries and then fetch each country with all it's claims just to get the ISO 3166 value.

Instead, why not have a copy of the codes on your server, or even fetch it from a clean source meant for that, like this one: https://restcountries.eu/rest/v2/all?fields=name;alpha2Code

Related