Free IP2Country API with Self-hosted Matomo Instance
Ever googled for "Ip2Country+API+free"? There are a bunch of results1 but as soon as you get on their website and see the Pricing tab, at least I leave the page. Nothing against paid APIs, but it's either pay as you go or no.
Since this isn't the most difficult service those API providers often have a free tier and I guess most of the time it's enough, but then you rely on someone's else infrastructure, and we don't want that either (and by we, I mean the royal "we").
Anyway, for a project, I needed to resolve an IP address to a country. Since I was already running a self-hosted instance of Matomo on the server I remembered setting up the free MaxMind geolocation database.
Matomo either uses the free external service https://db-ip.com or it downloads the MaxMind Lite database to your server. And since we don't want to depend on someone else's infrastructure, a (self-updating) copy of the geolocation database is perfect.
How-To
In Matomo under Admin > System > Geolocation | Location Provider select DBIP / GeoIP 2 (Php). On the same page, setup automatic updates of geolocation databases. Use db-ip.com for out an of the box solution, or setup MaxMind as described.
Then under Admin > Personal > Security | Auth tokens create a new token. Uncheck the Only allow secure requests since you want to use the token as GET parameter.
Copy the token and use it in the following API call with the parameter auth_token
:
https://your-domain.com/index.php?module=API&method=UserCountry.getLocationFromIP&ip={IPv4|Pv6}&format=JSON&token_auth={TOKEN}
That's it.
Here is the result of the public Matomo demo instance (therefore no token used): https://demo.matomo.cloud/index.php?module=API&method=UserCountry.getLocationFromIP&ip=91.8.207.90&format=json
{
continent_name: "Europe",
continent_code: "EU",
country_code: "DE",
country_name: "Germany",
city_name: "Hamburg",
lat: 53.483,
long: 9.852,
postal_code: "21147",
region_code: "HH",
region_name: "Free and Hanseatic City of Hamburg",
ip: "91.8.207.90"
}