Quantcast
Channel: ProgrammableWeb - Location
Viewing all articles
Browse latest Browse all 1090

Introduction to the ipapi Geolocation API

$
0
0
Super Short Hed: 
Introduction to the ipapi Geolocation API
Primary Target Audience: 
Primary Channel: 
Primary category: 
Secondary category: 
Related Companies: 
Related APIs: 
ipapi
Summary: 
This article offers an introduction ipapi, a service that provides information about your website's visitors based on their IP address. Using the service, you can determine the customer's location, timezone, default language and currency and details about their network's organizational identity.

The Importance of IP Geolocation for Web Developers

Today, I'm introducing ipapi, a new service that provides a wealth of information about your website's visitors based on their IP address. Using the service, you can determine the customer's location, timezone, default language and currency and details about their network's organizational identity. And, ipapi servers provide this information with extremely fast response times.

Essentially, ipapi offers free IP to geolocation, IP to language, currency and timezone detection as well as security details and hostname and ASN lookups.

The home page for the ipapi.com website and its ip2location time zone lookup an, language and currency services

The home page for the ipapi.com website and its ip2location time zone lookup an, language and currency services

If you've used FreeGeoIP in the past, you'll be familiar with ipapi. It's the result of FreeGeoIP merging with apilayer, a company we've covered here before:

ipapi provides a faster, higher capacity service to more than 100,000 customers. Cumulatively, they've handled more than 2 billion requests.

ipapi's geolocation API is still free to use for new users up to 10,000 requests per month. For smaller applications, this may be all you need. To access ipapi's complete suite of features, you'll need to choose a plan from $10 monthly up to $100, or request a custom enterprise plan.

Exploring Common Scenarios

The ipapi home page has an excellent interactive visualization that shows how developers can leverage IP data to personalize the experience for visitors. Let's take a look.

Content Personalization

Below you see an example of Content Personalization, presenting content specific to a user's location:

Example of IP indication geolocation in New York to show visitor New York Campaign

Example of IP indication geolocation in New York to show visitor New York Campaign

As a user arrives at your site, you send ipapi the ip address 72.229.28.185. In this example, they respond with the location of your customer New York, United States.

With this information, you can customize the content you provide. For example, this site automatically presents a "New York Campaign" to the visitor. Without geolocation, sites typically have an extra step to request the user's location.

ipapi's average response time is typically 20-50ms, a delay which is not perceptible to site visitors.

Language Redirection

Here's a scenario showing how to customize your website's language using ipapi:

A scenario showing how to customize your website's language using ipapi

When your site visitor arrives, you send the IP address 87.111.168.248 to ipapi. It determines that your prospective customer from Spain. While Spain has five different languages, ipapi determines that this person is visiting from a region that speaks spanish allowing you to personalize your site's translation.

Currency Detection

If you're operating an international e-commerce site, it's important to know which currency to present pricing in. The example below shows how to use ipapi to detect currency:

This example below shows how to use ipapi to detect currency.

When the site visitor arrives, you transmit their IP address 210.138.184.59 to ipapi. The service responds by telling you the customer is in Japan and the Japanese Yen is the currency used. Then, you can switch your website to display currency in JPY without requiring the user manually do so.

Timezone Lookup

If you do any kind of scheduling or calendaring on your website, it's important to identify the user's timezone.

In this example, a visitor arrives with the IP address 46.161.59.106. Our request to ipapi responds that the person is in Sydney, Australia and uses the Australia Eastern Time (AET).

In this example, a visitor arrives with the IP address 46.161.59.106. Our request to ipapi responds that the person is in Sydney, Australia and uses the Australia Eastern Time (AET).

Fraud Prevention

ipapi also provides fraud detection to help screen bots, crawlers, anonymous users and bad actors. Here you see an IP identified as a TOR proxy which gives you the option of preventing registration:

Example of ipapi indicating visitor IP appears in a threat database to disallow signup.

Example of ipapi indicating visitor IP appears in a threat database to disallow signup

One example not shown above is determining the ASN. The ASN is a code associated with the organization that manages a range of IP addresses. For example, mobile Verizon customers would appear as Verizon, whereas an Apple employee would likely appear as from Apple.

All of this demonstrates the powerful intelligence ipapi can add to your web service. The additional information allows you to provide a more personalized and more efficient user experience.

To clarify, you can get all this data and more from a single request to the ipapi service. Here's an example of a detailed ipapi API response (I formatted the results in two columns to fit on one page):

Example of JSON response of an ipapi query for free geolocation, IP to language, timezone lookup, currency, security, et al.

Example of JSON response of an ipapi query for free geolocation, IP to language, timezone lookup, currency, security, et al.

This response is in JSON but you can also request your results in XML format.

By default, ipapi responds in English but you can also choose German, Spanish, French, Japanese, Portuguese (Brazil), Russian, and Chinese.

Getting Started with the ipapi Service

Sign Up for Your Free Account

To get started with ipapi, click the SIGN UP FREE button in the upper right of the navigation bar. Of course, you can also choose a premium plan with higher capacity.

ipapi Pricing

ipapi's pricing page showing Free, Standard $10, Business $50, Business Pro $100 and custom Enterprise plans.

ipapi's pricing page showing Free, Standard $10, Business $50, Business Pro $100 and custom Enterprise plans.

All paid plans gain SSL access via HTTPS, whereas the free plan does not.

For $10 per month, you get 50,000 requests per month, ip2location, currency information, timezone lookup and hostname and ASN organizational details.

Higher level plans provide bulk processing, which allows you to gather data about large numbers of ip addresses you already have, often from your existing customer base.

With the Business Pro plan at $100 per month, you gain access to security details.

You can save 20 percent on any plan by paying annually.

Registration for ipapi

The sign up form is very straightforward:

Blank sign up form at ipapi's website ipapi.com

Blank sign up form at ipapi's website ipapi.com

You'll also be asked to provide your billing information in case you upgrade.

The ipapi API Dashboard

The Quickstart Guide

ipapi's API dashboard provides your API key and a simple 3 step quickstart guide:

3-step quickstart guide at ipapi after sign up.

3-step quickstart guide at ipapi after sign up

Step 1 - Your API Access Key
Your API access key provides access to the ipapi API. It's required to be included as a parameter in every call. You can also reset the key to secure a new one whenever you wish.

Step 2 - Reviewing the Major API Endpoints
Overall, there are three primary methods for making use of ipapi API services:

  • Standard Lookup: Looks up the data behind a specific IP address you provide in the request.
  • Bulk Lookup: Look up the data for multiple IP addresses at once, which you provide in the request.
  • Origin Lookup: Look up the data behind the IP address the current API request is coming from i.e. the requesting API is the specified IP address.

Base URL: Whichever API method you choose to use, all API requests to the ipapi API start out with the following base URL: https://api.ipapi.com/
 

Continued from page 1

ipapi, like all of the apilayer products, provide simple documentation with live examples:

ipapi, like all of the apilayer products, provide simple documentation with live examples

It also shows the request parameters so you can customize the URL and re-run requests with different settings:

It also shows the request parameters so you can customize the URL and re-run requests with different settings

Here's the default response in JSON:

{  
   "ip":"161.185.160.93",
   "type":"ipv4",
   "continent_code":"NA",
   "continent_name":"North America",
   "country_code":"US",
   "country_name":"United States",
   "region_code":"NY",
   "region_name":"New York",
   "city":"New York",
   "zip":"10004",
   "latitude":40.7143,
   "longitude":-74.006,
   "location":{  
      "geoname_id":5128581,
      "capital":"Washington D.C.",
      "languages":[  
         {  
            "code":"en",
            "name":"English",
            "native":"English"
         }
      ],
      "country_flag":"http:\/\/assets.ipapi.com\/flags\/us.svg",
      "country_flag_emoji":"\ud83c\uddfa\ud83c\uddf8",
      "country_flag_emoji_unicode":"U+1F1FA U+1F1F8",
      "calling_code":"1",
      "is_eu":false
   },
   "time_zone":{  
      "id":"America\/New_York",
      "current_time":"2018-11-15T17:41:31-05:00",
      "gmt_offset":-18000,
      "code":"EST",
      "is_daylight_saving":false
   },
   "currency":{  
      "code":"USD",
      "name":"US Dollar",
      "plural":"US dollars",
      "symbol":"$",
      "symbol_native":"$"
   },
   "connection":{  
      "asn":22252,
      "isp":"The City of New York"
   }
}

You can minimize response time and bandwidth with ipapi by customizing the response set to request less information. For example, location may be all that you need or security only.

Before we dive into the ipapi API documentation, let's review how to program requests to the API in JavaScript and PHP.

Querying the Endpoints in Multiple Programming Languages

Here's a JavaScript AJAX query:

screenshot of jQuery ajax example of calling the ipapi API methods. Code is available in their documentation.

screenshot of jQuery ajax example of calling the ipapi API methods. Code is available in their documentation.

This AJAX call transformed the JSON formatted response into an accessible JavaScript object named json.

Or, you can use the JavaScript JSON.parse() method for JavaScript in your browser's developer console:

screenshot of console output after JSON.parse operation on API result

screenshot of console output after JSON.parse operation on API result

Here's a PHP cURL-based example for making requests (from ipapi's documentation):

screenshot of PHP cURL example of calling their API methods. Code is available in their documentation.

screenshot of PHP cURL example of calling their API methods. Code is available in their documentation.

This example uses the json_decode() function to transform the JSON data into a usable multilevel array. You can see how this works below in my interactive shell:

$ php -a
Interactive shell
php >  print_r( json_decode('{"ip":"134.201.250.155","type":"ipv4","continent_code":"NA","continent_name":"North America","country_code":"US","country_name":"United States","region_code":"CA","region_name":"California","city":"Huntington Beach","zip":"92648","latitude":33.6746,"longitude":-118.0086,"location":{"geoname_id":5358705,"capital":"Washington D.C.","languages":[{"code":"en","name":"English","native":"English"}],"country_flag":"http:\/\/assets.ipapi.com\/flags\/us.svg","country_flag_emoji":"\ud83c\uddfa\ud83c\uddf8","country_flag_emoji_unicode":"U+1F1FA U+1F1F8","calling_code":"1","is_eu":false},"time_zone":{"id":"America\/Los_Angeles","current_time":"2018-07-25T17:51:07-07:00","gmt_offset":-25200,"code":"PDT","is_daylight_saving":true},"currency":{"code":"USD","name":"US Dollar","plural":"US dollars","symbol":"$","symbol_native":"$"},"connection":{"asn":25876,"isp":"Los Angeles Department of Water & Power"}}',true));

This returns the following structured array:

Array
(
    [ip] => 134.201.250.155
    [type] => ipv4
    [continent_code] => NA
    [continent_name] => North America
    [country_code] => US
    [country_name] => United States
    [region_code] => CA
    [region_name] => California
    [city] => Huntington Beach
    [zip] => 92648
    [latitude] => 33.6746
    [longitude] => -118.0086
    [location] => Array
        (
            [geoname_id] => 5358705
            [capital] => Washington D.C.
            [languages] => Array
                (
                    [0] => Array
                        (
                            [code] => en
                            [name] => English
                            [native] => English
                        )
...

It's easy to translate the response data from ipapi into usable arrays or objects.

That's basically my standard for assessing good APIs: how quickly can I make my first request and use the data for my application. ipapi delivers on this well.

Using the ipapi API Services

The first ipapi geolocation endpoint is the Standard IP Lookup. Here's a screenshot of their dynamic documentation, which works well throughout all of ipapi and all of apilayer's other services.

screenshot of ipapi geolocation documentation for Standard IP Lookup showing parameters.

screenshot of ipapi geolocation documentation for Standard IP Lookup showing parameters

The parameters give you a number of options. You can customize the response data with fields, turn on or off hostname lookup and security module data and choose the language for the response e.g. English, French, etc. There is also a callback option which allows the response data to be fed to a JavaScript function. I'll demonstrate this further below.

Here's a sample response from the IP Lookup documentation. I've clicked the XML button at the bottom right to switch the response format:

<?xml version="1.0" encoding="UTF-8"?>
<result>
   <ip>161.185.160.93</ip>
   <type>ipv4</type>
   <continent_code>NA</continent_code>
   <continent_name>North America</continent_name>
   <country_code>US</country_code>
   <country_name>United States</country_name>
   <region_code>NY</region_code>
   <region_name>New York</region_name>
   <city>Brooklyn</city>
   <zip>11238</zip>
   <latitude>40.676</latitude>
   <longitude>-73.9629</longitude>
   <location>
      <geoname_id>5110302</geoname_id>
      <capital>Washington D.C.</capital>
      <languages>
         <code>en</code>
         <name>English</name>
         <native>English</native>
      </languages>
      <country_flag>https://assets.ipapi.com/images/assets/flags_svg/us.svg</country_flag>
      <country_flag_emoji>🇺🇸</country_flag_emoji>
      <country_flag_emoji_unicode>U+1F1FA U+1F1F8</country_flag_emoji_unicode>
      <calling_code>1</calling_code>
      <is_eu />
   </location>
   <time_zone>
      <id>America/New_York</id>
      <current_time>2018-09-24T08:27:07-04:00</current_time>
      <gmt_offset>-14400</gmt_offset>
      <code>EDT</code>
      <is_daylight_saving>1</is_daylight_saving>
   </time_zone>
   <currency>
      <code>USD</code>
      <name>US Dollar</name>
      <plural>US dollars</plural>
      <symbol>$</symbol>
      <symbol_native>$</symbol_native>
   </currency>
   <connection>
      <asn>22252</asn>
      <isp>The City of New York</isp>
   </connection>
</result>

What if we'd like to request data for a large number of IP addresses? Let's move on to the Bulk IP Lookup method.

Bulk IP Lookups

The ipapi Bulk IP Lookup endpoint allows you to query multiple IP addresses in a single request.

Continued from page 2. 

The usage is similar to the Standard IP Lookup endpoint but the response includes data for all the requested IP addresses.

Screenshot of ipapi documentation for Bulk IP Lookup showing calling parameters.

Screenshot of ipapi documentation for Bulk IP Lookup showing calling parameters.

You could use this to track IP addresses in your database and gather more information about each of your existing users.

Or, you can gather IP addresses from your logs and analyze your traffic for location, language, et al.

The Bulk request responds with a series of results in sequence:

{
    "ip": "161.185.160.93",
    "type": "ipv4",
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code": "US",
    "country_name": "United States",
    "region_code": "NY",
    "region_name": "New York",
    "city": "Brooklyn",
    "zip": "11238",
    "latitude": 40.676,
    "longitude": -73.9629,
    [...]
},
{
    "ip": "161.185.160.93",
    "type": "ipv4",
    "continent_code": "EU",
    "continent_name": "Europe",
    "country_code": "ES",
    "country_name": "Spain",
    "region_code": "GA",
    "region_name": "Galicia",
    "city": "Santiago de Compostela",
    "zip": "15781",
    "latitude": 42.88,
    "longitude": -8.5448,
    [...]
},
{
    "ip": "210.138.184.59",
    "type": "ipv4",
    "continent_code": "AS",
    "continent_name": "Asia",
    "country_code": "JP",
    "country_name": "Japan",
    "region_code": "13",
    "region_name": "Tokyo",
    "city": "Tokyo",
    "zip": "102-0082",
    "latitude": 35.685,
    "longitude": 139.7514,
    [...]
}

Again, you can customize and minimize the response set of the data request for just the data you're looking for. This is extra useful for bulk lookups.

Here's an example of using the fields parameter to request the data you need:

documentation of specifying response fields to minimize or customize the data the api returns.

documentation of specifying response fields to minimize or customize the data the api returns

Origin IP Lookup

The Origin IP Lookup returns the same response data as the standard IP lookup above, but it provides this data for the requesting IP address e.g. the current server or the current web visitor.

Documentation for Origin IP Lookup with endpoint URL structure and request parameters.

Documentation for Origin IP Lookup with endpoint URL structure and request parameters

Be aware that using the Origin IP Lookup in JavaScript does expose your API key to visiting browsers, so you may choose to send the visitors IP address via AJAX to your own server and make the ipapi request from there.

Documentation for ipapi Parameters

Like all apilayer's services, ipapi's documentation is thorough. You can visit the Response Objects page to learn all about the response data provided by ipapi's geolocation API and other feature areas.

Here is a screenshot of a subset of all the response objects ipapi provides; this image is just a portion of the complete set which scrolls several pages:

Screenshot of Documentation of Response Objects, which describes fields returned by the API.

Screenshot of Documentation of Response Objects, which describes fields returned by the API.

Using Callback Functions with the API

All of ipapi's API methods allow you to specify a JavaScript function to call when they return.

Screenshot of documentation from JSONP callbacks showing the API response when a callback function is defined.

Screenshot of documentation from JSONP callbacks showing the API response when a callback function is defined.

When using JavaScript, in my experimentation, it was easier just to have the AJAX success method call my functions with the response data. But, what happens when you're calling the API from a different language?

Here's an example of using the callback method from PHP, to call a JavaScript function on the page to display the data.

The ipapi API query is made via PHP cURL. My specified callback is the JavaScript function name getRegionName(), which must be defined before the API call:

code<script src="/jquery.js"></script>
<script>
  function getRegionName() {
    $('#results').html(JSON.stringify(arguments[0]['region_name']));
  }
</script>
<br /><br /><br /><br /><br />
<div id="results">
  <!--- data displayed here --->
</div>
<?php
  // set IP address and API access key
  $ip ='67.183.38.149';
  $access_key = 'YOUR ACCESS KEY';
  // Initialize CURL:
  $ch = curl_init('https://api.ipapi.com/'.$ip.'?access_key='.$access_key.'&callback=getRegionName');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Store the data:
  $json = curl_exec($ch);
  echo '<script type="text/javascript">'.
       $json.
       '</script>';
  ;
  curl_close($ch);
?>

The result is that the region name is parsed from the result and displayed on the page.

For the IP address specified, it simply says: "Washington". I use arguments[0] to refer to the data sent in the callback.

ipapi API Security Data

To access ipapi's security module, you must subscribe to its Business Pro or Enterprise plan.

The security response can alert you about the following things about site visitors via their IP address:

  • The address is associated with a proxy e.g. CGI, web or VPN
  • The address is a crawler such as a search engine bot, site monitor, screenshot creator, link checker, wearable computer, web scraper, vulnerability scanner, virus scanner, speed tester, feed fetcher, tool or marketing.
  • The address is associated with the anonymous Tor network
  • The address has low, medium or high level threat with characteristics being from Tor, being a fake crawler or web scraper or an known attack source vector e.g. http, mail or ssh
Screenshot of the documentation for Enabling Security Data on ipapi's API

Screenshot of the documentation for Enabling Security Data on ipapi's API

Note: the usual IP results are compressed above to show the security data.

I hope this provides a sense of the power of ipapi. It's not only free ip2location but also timezone, language and currency detection and fraud prevention!

In Closing

I hope you've enjoyed learning about ipapi, a simple, economical, low latency geolocation service with a wide array of features which builds on the success and popularity of FreeGeoIP.

ipapi is a great resource for startups and small companies as well as great big enterprise level corporations. And, it's part of the simple, straightforward family of apilayer, all of whose services are similarly constructed to simplify adoption and development.

Learn more about their suite of products:

screenshot of portfolio of apilayer companies which offer related web-based data APIs

screenshot of portfolio of apilayer companies which offer related web-based data APIs

apilayer and ipapi appreciate your questions, comments and feedback. You can also follow them on Twitter @apilayernet and the apilayer Facebook page.

About apilayer

ipapi is the most recent solution from apilayer, an established leader in product APIs. apilayer aims to help developers and businesses automate and outsource complex processes by serving them with dedicated and handy programming interfaces.

Two other products by apilayer include streetlayer, an international address validation service, and eversign, an electronic document signing, approval and delivery service. You can find my articles about them at ProgrammableWeb.

Content type group: 
Articles
Top Match Search Text: 
Introduction to the ipapi Geolocation API

Viewing all articles
Browse latest Browse all 1090

Trending Articles