SDKs overview
IP 2 Country provides an API for converting IP addresses to country information. Unlike some services that offer pre-built Software Development Kits (SDKs) to streamline integration, IP 2 Country's approach requires direct interaction with its RESTful API. This means developers use standard HTTP client libraries available in their chosen programming language to send requests and parse responses. This method offers flexibility, enabling fine-grained control over network requests and data handling, but it also places the responsibility for API interaction logic directly on the developer.
The absence of official SDKs implies that developers are responsible for managing API keys, constructing request URLs, handling HTTP headers, and parsing the JSON response payload. This direct integration model is common among APIs that prioritize simplicity and broad compatibility across diverse technology stacks, as it avoids locking developers into specific language versions or framework dependencies. For detailed API specifications, including endpoints, parameters, and response formats, developers should consult the IP 2 Country developer documentation.
Official SDKs by language
As noted in the developer experience documentation, IP 2 Country does not currently offer official SDKs for any programming language. Developers integrate with the service by making direct HTTP requests to the API endpoint. This requires implementing the request and response handling logic using standard HTTP libraries or frameworks specific to the programming language being used. The table below illustrates this direct integration model:
| Language | Package/Method | Installation/Integration | Maturity |
|---|---|---|---|
| Python | requests library |
pip install requests |
Stable (via 3rd party HTTP client) |
| JavaScript (Node.js) | node-fetch or axios |
npm install node-fetch or npm install axios |
Stable (via 3rd party HTTP client) |
| PHP | Guzzle HTTP client | composer require guzzlehttp/guzzle |
Stable (via 3rd party HTTP client) |
| Java | java.net.HttpClient or Apache HttpClient |
Built-in or Maven/Gradle dependency | Stable (via built-in or 3rd party HTTP client) |
| Ruby | Net::HTTP (built-in) or httparty gem |
Built-in or gem install httparty |
Stable (via built-in or 3rd party HTTP client) |
Each of these methods involves constructing the API request URL, adding any necessary authentication (such as an API key), and then parsing the JSON response. The IP 2 Country API reference provides details on the expected request parameters and the structure of the JSON response for successful lookups and error conditions.
Installation
Since official SDKs are not provided, installation typically involves adding an HTTP client library to your project. The specific installation method depends on your programming language and package manager. Below are common examples for popular languages:
Python
For Python, the requests library is a common choice for making HTTP requests due to its user-friendly API. To install:
pip install requests
JavaScript (Node.js)
In Node.js environments, node-fetch or axios are frequently used. node-fetch brings the browser's Fetch API to Node.js, while axios is a promise-based HTTP client for the browser and Node.js.
npm install node-fetch
# or
npm install axios
PHP
For PHP projects, the Guzzle HTTP client is a robust option, often managed via Composer.
composer require guzzlehttp/guzzle
Java
Java 11 and later include a built-in java.net.HttpClient. For earlier versions or more advanced features, Apache HttpClient is a common external library.
Using built-in Java 11+ HttpClient: No installation required.
Using Apache HttpClient (Maven): Add to your pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
Using Apache HttpClient (Gradle): Add to your build.gradle:
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
Ruby
Ruby has a built-in Net::HTTP library. For a more convenient API, the httparty gem is popular.
gem install httparty
Quickstart example
The following examples demonstrate how to make a basic IP 2 Country API request using common HTTP client libraries. Replace YOUR_API_KEY with your actual API key obtained from the IP 2 Country developer portal.
Python Example (using requests)
import requests
api_key = "YOUR_API_KEY"
ip_address = "8.8.8.8" # Example IP address (Google DNS)
url = f"https://api.ip2country.com?ip={ip_address}&key={api_key}"
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
data = response.json()
if data and data.get("countryCode"):
print(f"IP: {ip_address}")
print(f"Country Code: {data['countryCode']}")
print(f"Country Name: {data['countryName']}")
else:
print(f"Could not retrieve country for IP {ip_address}: {data.get('error', 'Unknown error')}")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An error occurred: {req_err}")
JavaScript (Node.js) Example (using node-fetch)
const fetch = require('node-fetch');
const apiKey = "YOUR_API_KEY";
const ipAddress = "8.8.8.8"; // Example IP address (Google DNS)
async function getCountryFromIp(ip) {
const url = `https://api.ip2country.com?ip=${ip}&key=${apiKey}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data && data.countryCode) {
console.log(`IP: ${ip}`);
console.log(`Country Code: ${data.countryCode}`);
console.log(`Country Name: ${data.countryName}`);
} else {
console.log(`Could not retrieve country for IP ${ip}: ${data.error || 'Unknown error'}`);
}
} catch (error) {
console.error("Error fetching IP country:", error);
}
}
getCountryFromIp(ipAddress);
PHP Example (using Guzzle HTTP client)
<?php
require 'vendor/autoload.php'; // Composer autoloader
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
$apiKey = "YOUR_API_KEY";
$ipAddress = "8.8.8.8"; // Example IP address (Google DNS)
$client = new Client();
try {
$response = $client->request('GET', 'https://api.ip2country.com', [
'query' => [
'ip' => $ipAddress,
'key' => $apiKey
]
]);
$data = json_decode($response->getBody(), true);
if (isset($data['countryCode'])) {
echo "IP: " . $ipAddress . "\n";
echo "Country Code: " . $data['countryCode'] . "\n";
echo "Country Name: " . $data['countryName'] . "\n";
} else {
echo "Could not retrieve country for IP " . $ipAddress . ": " . ($data['error'] ?? 'Unknown error') . "\n";
}
} catch (ClientException $e) {
echo "Client error: " . $e->getMessage() . "\n";
} catch (ServerException $e) {
echo "Server error: " . $e->getMessage() . "\n";
} catch (\Exception $e) {
echo "An unexpected error occurred: " . $e->getMessage() . "\n";
}
?>
Community libraries
Because IP 2 Country does not provide official SDKs, the community primarily focuses on direct HTTP client integrations rather than dedicated wrappers. However, developers often share utility functions or classes that encapsulate the API call logic within larger projects. These are not typically standalone, published libraries but rather code snippets or modules designed for specific application contexts.
For example, a developer might create a IpCountryService class in Java or a ip_lookup.py module in Python that handles the API key management, request construction, error handling, and response parsing for IP 2 Country. Such components are usually tailored to the needs of individual projects and might be found in open-source repositories as part of broader applications.
When searching for community-contributed code, it is advisable to look for examples that utilize common HTTP client libraries for your language, such as Python's Requests library, JavaScript's Axios, or PHP's Guzzle. These examples typically demonstrate the fundamental patterns for interacting with any RESTful API, including IP 2 Country. Always review the source code of any community contribution for security and maintainability before integrating it into a production environment, as they are not officially supported or maintained by IP 2 Country.