IP2GeoAPI Documentation
Welcome to IP2GeoAPI - the most comprehensive IP geolocation and intelligence API. Get detailed information about any IP address including location, timezone, network details, and security data.
Quick Start
Get started with IP2GeoAPI in minutes. Simply obtain your free API key and start making requests.
Base URL
https://api.ip2geoapi.com/
Endpoint
GET /ip/{IP}?key=YOUR_API_KEY
Features
Geolocation Data
Accurate city, country, region, and coordinate information.
Network Information
ASN, ISP, organization, and connection type details.
Security Intelligence
VPN, proxy, Tor detection with trust scores.
Timezone Data
Complete timezone information with UTC offsets.
API Endpoints
Know our endpoints and use them efficiently for a faster lookup.
Important
All endpoints must be appended with your own API key:
?key=YOUR_API_KEY
Base URL
https://api.ip2geoapi.com/
Available Endpoints
| METHOD | ENDPOINT | DESCRIPTION |
|---|---|---|
| GET | /ip/{ip} | Lookup a specific IP address |
| GET | /ip/check | Lookup your own IP address |
| GET | /health | Check the API uptime status |
Parameters
| PARAMETER | TYPE | REQUIRED | DESCRIPTION |
|---|---|---|---|
| key | string | Required | Your API key for authentication |
| ip | string | Required | The IP address to lookup (IPv4 or IPv6) |
| format | string | Optional | Response format: json (default), xml, yaml, jsonp |
| callback | string | Optional | JSONP callback function name (max 64 chars). allowed: alphabets, numbers and underscore) |
Authentication
All API requests require authentication using an API key.
Getting Your API Key
Sign up at ip2geoapi.com to get your free API key instantly.
Using Your API Key
Include your API key as a query parameter in every request:
https://api.ip2geoapi.com/ip/8.8.8.8?key=YOUR_API_KEY
Keep Your API Key Secret
Never expose your API key in client-side code or public repositories.
Rate Limits
Rate limits depend on your subscription plan:
- Free Plan: 100,000 requests per month
No daily rate limits
We do not enforce any daily limits. You can use your quota at your own pace.
API Response
The API returns comprehensive data in JSON format.
Sample Response
{
"success": true,
"ip": "8.8.8.8",
"version": "ipv4",
"geo": {
"city": "Chicago",
"country": "United States",
"countryCode": "US",
"region": null,
"regionCode": null,
"latitude": 37.751,
"longitude": -97.822,
"postalCode": null,
"geonameId": 6252001,
"accuracyRadius": 1000,
"metroCode": null,
"continentName": "North America",
"continentCode": "NA",
"isEuMember": false
},
"countryInfo": {
"name": "United States of America",
"alpha2Code": "US",
"alpha3Code": "USA",
"flag": "https://api.ip2geoapi.com/assets/flags/us.svg",
"callingCodes": ["1"],
"currencies": [
{
"code": "USD",
"name": "United States dollar",
"symbol": "$"
}
],
"languages": [
{
"iso639_1": "en",
"iso639_2": "eng",
"name": "English",
"nativeName": "English"
}
]
},
"timezoneInfo": {
"timezone": "America/Chicago",
"utcOffsetSeconds": -21600,
"utcOffsetText": "-06:00",
"utcOffsetHours": -6,
"isDst": false,
"abbreviation": "CST",
"localTime": "2025-12-07T23:29:45.000Z"
},
"network": {
"cidr": "8.8.8.8/32",
"prefixLen": 32,
"asn": 15169,
"asFormatted": "AS15169",
"asName": "GOOGLE",
"isp": "Google",
"organization": "Google",
"connectionType": "Corporate",
"mobile": {
"mcc": null,
"mnc": null
}
},
"asDetails": {
"asn": 15169,
"abuser_score": "0.001 (Low)",
"descr": "GOOGLE, US",
"country": "us",
"active": true,
"org": "Google LLC",
"domain": "google.com",
"abuse": "[email protected]",
"type": "hosting",
"created": "2000-03-30",
"updated": "2012-02-24",
"rir": "ARIN"
},
"security": {
"isHosting": true,
"isProxy": false,
"proxyType": null,
"isVpn": false,
"vpnProvider": null,
"vpnProviderUrl": null,
"isTor": false,
"isAnonymous": true,
"trustScore": 65,
"riskLevel": "medium"
}
}
Response Fields
| Field | Type | Description |
|---|---|---|
| success | boolean | Indicates if the request was successful |
| ip | string | The queried IP address |
| geo | object | Geolocation information |
| countryInfo | object | Country details including flag, currencies, languages |
| timezoneInfo | object | Timezone and time-related information |
| network | object | Network and ISP information |
| asDetails | object | Autonomous System details |
| security | object | Security and threat intelligence |
Complete API Fields
| Field | Description |
|---|---|
| Basic Info | |
| success | Request status |
| ip | IP address |
| version | IP version (IPv4/IPv6) |
| Country Details | |
| countryInfo.name | Country name |
| countryInfo.alpha2Code | ISO 3166-1 alpha-2 |
| countryInfo.alpha3Code | ISO 3166-1 alpha-3 |
| countryInfo.flag | Flag SVG URL |
| countryInfo.callingCodes | Phone calling codes |
| countryInfo.currencies | Currency info |
| countryInfo.languages | Languages |
| Geolocation | |
| geo.city | City name |
| geo.country | Country name |
| geo.countryCode | ISO country code |
| geo.region | Region/state name |
| geo.regionCode | Region code |
| geo.latitude | Latitude |
| geo.longitude | Longitude |
| geo.postalCode | Postal/ZIP code |
| geo.geonameId | GeoNames ID |
| geo.accuracyRadius | Location accuracy radius |
| geo.metroCode | Metro code |
| geo.continentName | Continent name |
| geo.continentCode | Continent code |
| geo.isEuMember | EU membership |
| Timezone | |
| timezoneInfo.timezone | Timezone name |
| timezoneInfo.utcOffsetSeconds | UTC offset (seconds) |
| timezoneInfo.utcOffsetText | UTC offset (text) |
| timezoneInfo.utcOffsetHours | UTC offset (hours) |
| timezoneInfo.isDst | Daylight Saving Time active |
| timezoneInfo.abbreviation | Timezone abbreviation |
| timezoneInfo.localTime | Local time |
| Network | |
| network.cidr | Network CIDR |
| network.prefixLen | Prefix length |
| network.asn | ASN number |
| network.asFormatted | Formatted ASN (e.g., AS15169) |
| network.asName | AS name |
| network.isp | ISP name |
| network.organization | Organization |
| network.connectionType | Connection type |
| network.mobile.mcc | Mobile Country Code (MCC) |
| network.mobile.mnc | Mobile Network Code (MNC) |
| ASN Details | |
| asDetails.asn | ASN number |
| asDetails.abuser_score | Abuse score |
| asDetails.descr | AS description |
| asDetails.country | AS country |
| asDetails.active | Active status |
| asDetails.org | Organization |
| asDetails.domain | Domain |
| asDetails.abuse | Abuse contact |
| asDetails.type | AS type |
| asDetails.updated | Last updated |
| asDetails.rir | Regional Internet Registry (RIR) |
| Security | |
| security.isHosting | Hosting detection |
| security.isProxy | Proxy detection |
| security.proxyType | Proxy type |
| security.isVpn | VPN detection |
| security.vpnProvider | VPN provider |
| security.vpnProviderUrl | VPN provider website URL |
| security.isTor | Tor detection |
| security.isAnonymous | Anonymous IP |
| security.trustScore | Trust score (0–100) |
| security.riskLevel | Risk level |
Error Handling
The API returns detailed error messages to help you troubleshoot issues.
Error Response Format
All errors follow this format:
{
"success": false,
"error": "Error message here"
}
Common Errors
Invalid API Key
{
"success": false,
"error": "Invalid API key. Please get one at https://ip2geoapi.com/ for free."
}
Missing API Key
{
"success": false,
"error": "Missing API key. Please get one at https://ip2geoapi.com/ for free."
}
Monthly Limit Reached
{
"success": false,
"error": "Monthly limit reached. Please upgrade plan at https://ip2geoapi.com/plans"
}
Invalid IP Address
{
"success": false,
"error": "Invalid IP address."
}
Lookup Failed
{
"success": false,
"error": "Lookup failed"
}
JSON Response (Default)
Query string:
https://api.ip2geoapi.com/ip/8.8.8.8?format=json&key=YOUR_API_KEY
If no format parameter is supplied, it will default to JSON:
https://api.ip2geoapi.com/ip/8.8.8.8?key=YOUR_API_KEY
Response:
{
"success": true,
"ip": "8.8.8.8",
"version": "ipv4",
"geo": {
"city": "Chicago",
"country": "United States",
"countryCode": "US",
"region": null,
"regionCode": null,
"latitude": 37.751,
"longitude": -97.822,
"postalCode": null,
"geonameId": 6252001,
"accuracyRadius": 1000,
"metroCode": null,
"continentName": "North America",
"continentCode": "NA",
"isEuMember": false
},
"countryInfo": {
"name": "United States of America",
"alpha2Code": "US",
"alpha3Code": "USA",
"flag": "https://api.ip2geoapi.com/assets/flags/us.svg",
"callingCodes": ["1"],
"currencies": [
{
"code": "USD",
"name": "United States dollar",
"symbol": "$"
}
],
"languages": [
{
"iso639_1": "en",
"iso639_2": "eng",
"name": "English",
"nativeName": "English"
}
]
},
"timezoneInfo": {
"timezone": "America/Chicago",
"utcOffsetSeconds": -21600,
"utcOffsetText": "-06:00",
"utcOffsetHours": -6,
"isDst": false,
"abbreviation": "CST",
"localTime": "2025-12-07T23:29:45.000Z"
},
"network": {
"cidr": "8.8.8.8/32",
"prefixLen": 32,
"asn": 15169,
"asFormatted": "AS15169",
"asName": "GOOGLE",
"isp": "Google",
"organization": "Google",
"connectionType": "Corporate",
"mobile": {
"mcc": null,
"mnc": null
}
},
"asDetails": {
"asn": 15169,
"abuser_score": "0.001 (Low)",
"descr": "GOOGLE, US",
"country": "us",
"active": true,
"org": "Google LLC",
"domain": "google.com",
"abuse": "[email protected]",
"type": "hosting",
"created": "2000-03-30",
"updated": "2012-02-24",
"rir": "ARIN"
},
"security": {
"isHosting": true,
"isProxy": false,
"proxyType": null,
"isVpn": false,
"vpnProvider": null,
"vpnProviderUrl": null,
"isTor": false,
"isAnonymous": true,
"trustScore": 65,
"riskLevel": "medium"
}
}
XML Response
Query string:
https://api.ip2geoapi.com/ip/8.8.8.8?format=xml&key=YOUR_API_KEY
Response:
<response>
<success>true</success>
<ip>8.8.8.8</ip>
<version>ipv4</version>
<geo>
<city>Chicago</city>
<country>United States</country>
<countryCode>US</countryCode>
<region/>
<regionCode/>
<latitude>37.751</latitude>
<longitude>-97.822</longitude>
<postalCode/>
<geonameId>6252001</geonameId>
<accuracyRadius>1000</accuracyRadius>
<metroCode/>
<continentName>North America</continentName>
<continentCode>NA</continentCode>
<isEuMember>false</isEuMember>
</geo>
<countryInfo>
<name>United States of America</name>
<alpha2Code>US</alpha2Code>
<alpha3Code>USA</alpha3Code>
<flag>https://api.ip2geoapi.com/assets/flags/us.svg</flag>
<callingCodes>1</callingCodes>
<currencies>
<code>USD</code>
<name>United States dollar</name>
<symbol>$</symbol>
</currencies>
<languages>
<iso639_1>en</iso639_1>
<iso639_2>eng</iso639_2>
<name>English</name>
<nativeName>English</nativeName>
</languages>
</countryInfo>
<timezoneInfo>
<timezone>America/Chicago</timezone>
<utcOffsetSeconds>-21600</utcOffsetSeconds>
<utcOffsetText>-06:00</utcOffsetText>
<utcOffsetHours>-6</utcOffsetHours>
<isDst>false</isDst>
<abbreviation>CST</abbreviation>
<localTime>2025-12-09T06:23:46.000Z</localTime>
</timezoneInfo>
<network>
<cidr>8.8.8.8/32</cidr>
<prefixLen>32</prefixLen>
<asn>15169</asn>
<asFormatted>AS15169</asFormatted>
<asName>GOOGLE</asName>
<isp>Google</isp>
<organization>Google</organization>
<connectionType>Corporate</connectionType>
<mobile>
<mcc/>
<mnc/>
</mobile>
</network>
<asDetails>
<asn>15169</asn>
<abuser_score>0.001 (Low)</abuser_score>
<descr>GOOGLE, US</descr>
<country>us</country>
<active>true</active>
<org>Google LLC</org>
<domain>google.com</domain>
<abuse>[email protected]</abuse>
<type>hosting</type>
<created>2000-03-30</created>
<updated>2012-02-24</updated>
<rir>ARIN</rir>
</asDetails>
<security>
<isHosting>true</isHosting>
<isProxy>false</isProxy>
<proxyType/>
<isVpn>false</isVpn>
<vpnProvider/>
<vpnProviderUrl/>
<isTor>false</isTor>
<isAnonymous>true</isAnonymous>
<trustScore>65</trustScore>
<riskLevel>medium</riskLevel>
</security>
</response>
YML Response
Query string:
https://api.ip2geoapi.com/ip/8.8.8.8?format=yml&key=YOUR_API_KEY
OR
https://api.ip2geoapi.com/ip/8.8.8.8?format=yaml&key=YOUR_API_KEY
Response:
success: true
ip: 8.8.8.8
version: ipv4
geo:
city: Chicago
country: United States
countryCode: US
region: null
regionCode: null
latitude: 37.751
longitude: -97.822
postalCode: null
geonameId: 6252001
accuracyRadius: 1000
metroCode: null
continentName: North America
continentCode: NA
isEuMember: false
countryInfo:
name: United States of America
alpha2Code: US
alpha3Code: USA
flag: https://api.ip2geoapi.com/assets/flags/us.svg
callingCodes:
- '1'
currencies:
- code: USD
name: United States dollar
symbol: $
languages:
- iso639_1: en
iso639_2: eng
name: English
nativeName: English
timezoneInfo:
timezone: America/Chicago
utcOffsetSeconds: -21600
utcOffsetText: '-06:00'
utcOffsetHours: -6
isDst: false
abbreviation: CST
localTime: '2025-12-09T06:14:54.000Z'
network:
cidr: 8.8.8.8/32
prefixLen: 32
asn: 15169
asFormatted: AS15169
asName: GOOGLE
isp: Google
organization: Google
connectionType: Corporate
mobile:
mcc: null
mnc: null
asDetails:
asn: 15169
abuser_score: 0.001 (Low)
descr: GOOGLE, US
country: us
active: true
org: Google LLC
domain: google.com
abuse: [email protected]
type: hosting
created: '2000-03-30'
updated: '2012-02-24'
rir: ARIN
security:
isHosting: true
isProxy: false
proxyType: null
isVpn: false
vpnProvider: null
vpnProviderUrl: null
isTor: false
isAnonymous: true
trustScore: 65
riskLevel: medium
JSONP Response (Callbacks)
Query string:
https://api.ip2geoapi.com/ip/8.8.8.8?format=jsonp&callback=cbFunction&key=YOUR_API_KEY
Important
Replace cbFunction with your own JS function name
Content inside cbFunction will always be a JSON object
Response:
cbFunction(
{
"success": true,
"ip": "8.8.8.8",
"version": "ipv4",
"geo": {
"city": "Chicago",
"country": "United States",
"countryCode": "US",
"region": null,
"regionCode": null,
"latitude": 37.751,
"longitude": -97.822,
"postalCode": null,
"geonameId": 6252001,
"accuracyRadius": 1000,
"metroCode": null,
"continentName": "North America",
"continentCode": "NA",
"isEuMember": false
},
"countryInfo": {
"name": "United States of America",
"alpha2Code": "US",
"alpha3Code": "USA",
"flag": "https://api.ip2geoapi.com/assets/flags/us.svg",
"callingCodes": ["1"],
"currencies": [
{
"code": "USD",
"name": "United States dollar",
"symbol": "$"
}
],
"languages": [
{
"iso639_1": "en",
"iso639_2": "eng",
"name": "English",
"nativeName": "English"
}
]
},
"timezoneInfo": {
"timezone": "America/Chicago",
"utcOffsetSeconds": -21600,
"utcOffsetText": "-06:00",
"utcOffsetHours": -6,
"isDst": false,
"abbreviation": "CST",
"localTime": "2025-12-07T23:29:45.000Z"
},
"network": {
"cidr": "8.8.8.8/32",
"prefixLen": 32,
"asn": 15169,
"asFormatted": "AS15169",
"asName": "GOOGLE",
"isp": "Google",
"organization": "Google",
"connectionType": "Corporate",
"mobile": {
"mcc": null,
"mnc": null
}
},
"asDetails": {
"asn": 15169,
"abuser_score": "0.001 (Low)",
"descr": "GOOGLE, US",
"country": "us",
"active": true,
"org": "Google LLC",
"domain": "google.com",
"abuse": "[email protected]",
"type": "hosting",
"created": "2000-03-30",
"updated": "2012-02-24",
"rir": "ARIN"
},
"security": {
"isHosting": true,
"isProxy": false,
"proxyType": null,
"isVpn": false,
"vpnProvider": null,
"vpnProviderUrl": null,
"isTor": false,
"isAnonymous": true,
"trustScore": 65,
"riskLevel": "medium"
}
}
)
Hint: Use check to test your own IP
https://api.ip2geoapi.com/ip/
Testing API...
cURL Examples
Make API requests using cURL from the command line.
Basic Request
curl "https://api.ip2geoapi.com/ip/8.8.8.8?key=YOUR_API_KEY"
Pretty Print Response
curl "https://api.ip2geoapi.com/ip/8.8.8.8?key=YOUR_API_KEY" | python3 -m json.tool
Save to File
curl "https://api.ip2geoapi.com/ip/8.8.8.8?key=YOUR_API_KEY" -o response.json
With Headers
curl -X GET "https://api.ip2geoapi.com/ip/8.8.8.8?key=YOUR_API_KEY" \
-H "Accept: application/json"
Python Examples
Integrate IP2GeoAPI into your Python applications.
Using Python SDK
pip install ip2geoapi
Quick Start
from ip2geo import Ip2Geo
client = Ip2Geo("YOUR_API_KEY")
data = client.lookup("8.8.8.8") # json default
# data = client.lookup("8.8.8.8", format="yml")
# data = client.lookup("8.8.8.8", format="xml")
# data = client.lookup("8.8.8.8", format="jsonp", callback="cbFunction")
print(data)
Using Requests Library
import requests
api_key = "YOUR_API_KEY"
ip_address = "8.8.8.8"
response_format = "json" # change to json | yml | jsonp
params = {
"key": api_key,
"format": response_format
}
# Required only for JSONP
if response_format == "jsonp":
params["callback"] = "cbFunction"
url = f"https://api.ip2geoapi.com/ip/{ip_address}"
try:
response = requests.get(
url,
params=params,
timeout=60
)
print(response.text)
except requests.exceptions.RequestException as e:
print({
"transport_error": True,
"message": str(e)
})
Async with aiohttp
import aiohttp
import asyncio
async def get_ip_info(ip_address, api_key, response_format="json"):
url = f"https://api.ip2geoapi.com/ip/{ip_address}"
params = {
"key": api_key,
"format": response_format
}
# Required only for JSONP
if response_format == "jsonp":
params["callback"] = "cbFunction"
timeout = aiohttp.ClientTimeout(total=60)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
async with session.get(url, params=params) as response:
body = await response.text()
print(body)
except asyncio.TimeoutError:
print({
"transport_error": True,
"message": "Request timed out"
})
except aiohttp.ClientError as e:
print({
"transport_error": True,
"message": str(e)
})
async def main():
API_KEY = "YOUR_API_KEY"
IP_ADDRESS = "8.8.8.8"
# Allowed: json (default), xml, yml, jsonp
RESPONSE_FORMAT = "json"
await get_ip_info(IP_ADDRESS, API_KEY, RESPONSE_FORMAT)
asyncio.run(main())
Node.js Examples
Integrate IP2GeoAPI into your Node.js applications.
Using Node.js SDK
npm install ip2geoapiQuick Start
const Ip2Geo = require("ip2geoapi");
(async () => {
const client = new Ip2Geo("API_KEY");
const data = await client.lookup("8.8.8.8"); //json default
// const data = await client.lookup("8.8.8.8", { format: "yml" });
// const data = await client.lookup("8.8.8.8", { format: "xml" });
// const data = await client.lookup("8.8.8.8", { format: "jsonp", callback: "cbFunction" });
console.log(data);
})();Using Axios
const axios = require("axios");
const apiKey = "YOUR_API_KEY";
const ipAddress = "8.8.8.8";
const url = `https://api.ip2geoapi.com/ip/${ipAddress}`;
axios.get(url, {
params: {
key: apiKey,
format: "json" // change to xml | yml | jsonp if needed
},
timeout: 60000,
validateStatus: () => true
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error({
transport_error: true,
message: error.message
});
});
Using Fetch API
const API_KEY = "YOUR_API_KEY";
const IP_ADDRESS = "8.8.8.8";
const format = "json"; // change to xml | yml | jsonp if needed
let url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}?key=${API_KEY}&format=${format}`;
if (format === "jsonp") {
url += "&callback=cbFunction";
}
fetch(url)
.then(response => response.text())
.then(body => {
console.log(body);
})
.catch(error => {
console.error({
transport_error: true,
message: error.message
});
});
Using Native HTTPS Module
const https = require("https");
const API_KEY = "YOUR_API_KEY";
const IP_ADDRESS = "8.8.8.8";
const format = "json"; // change to xml | yml | jsonp if needed
let url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}?key=${API_KEY}&format=${format}`;
if (format === "jsonp") {
url += "&callback=cbFunction";
}
const req = https.get(url, res => {
let body = "";
res.on("data", chunk => {
body += chunk;
});
res.on("end", () => {
console.log(body);
});
});
req.setTimeout(60000, () => {
req.destroy(new Error("Request timed out"));
});
req.on("error", err => {
console.error({
transport_error: true,
message: err.message
});
});
Typescript Examples
Integrate IP2GeoAPI into your Typescript applications.
Using Axios
import axios from "axios";
const API_KEY = "YOUR_API_KEY";
const IP_ADDRESS = "8.8.8.8";
const format = "json"; // change to xml | yml | jsonp if needed
let url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}`;
const params: Record = {
key: API_KEY,
format
};
if (format === "jsonp") {
params.callback = "cbFunction";
}
axios.get(url, {
params,
timeout: 60000,
validateStatus: () => true
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error({
transport_error: true,
message: error.message
});
});
Javascript Examples
Integrate IP2GeoAPI into your Javascript applications.
Using Fetch API
const API_KEY = "YOUR_API_KEY";
const IP_ADDRESS = "8.8.8.8";
const format = "json"; // change to xml | yml | jsonp if needed
let url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}?key=${API_KEY}&format=${format}`;
if (format === "jsonp") {
url += "&callback=cbFunction";
}
fetch(url)
.then(res => res.text())
.then(body => {
console.log(body);
})
.catch(err => {
console.error({
transport_error: true,
message: err.message
});
});
Using jQuery AJAX
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const API_KEY = "YOUR_API_KEY";
const IP_ADDRESS = "8.8.8.8";
const format = "json"; // change to xml | yml | jsonp if needed
let url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}?key=${API_KEY}&format=${format}`;
if (format === "jsonp") {
url += "&callback=cbFunction";
}
$.ajax({
url: url,
method: "GET",
dataType: "text",
timeout: 60000,
complete: function(xhr) {
console.log(xhr.responseText);
},
error: function(xhr, status, err) {
console.error({
transport_error: true,
message: err
});
}
});
</script>
PHP Examples
Integrate IP2GeoAPI into your PHP applications.
Using PHP SDK
composer require ip2geo/ip2geo-phpQuick Start
<?php
require __DIR__ . '/vendor/autoload.php';
use Ip2Geo\Ip2Geo;
$client = new Ip2Geo("API_KEY"); // replace with real key
$data = $client->lookup("8.8.8.8"); // json default
/*
$data = $client->lookup("8.8.8.8", [
"format" => "yml"
]);
$data = $client->lookup("8.8.8.8", [
"format" => "xml"
]);
$data = $client->lookup("8.8.8.8", [
"format" => "jsonp",
"callback" => "cbFunction"
]);
*/
print_r($data);
?>Using cURL
<?php
$apiKey = "YOUR_API_KEY";
$ipAddress = "8.8.8.8";
$format = "json"; // change to xml | yml | jsonp if needed
$url = "https://api.ip2geoapi.com/ip/{$ipAddress}?key={$apiKey}&format={$format}";
if ($format === "jsonp") {
$url .= "&callback=cbFunction";
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Using file_get_contents
<?php
$apiKey = "YOUR_API_KEY";
$ipAddress = "8.8.8.8";
$format = "json"; // change to xml | yml | jsonp if needed
$url = "https://api.ip2geoapi.com/ip/{$ipAddress}?key={$apiKey}&format={$format}";
if ($format === "jsonp") {
$url .= "&callback=cbFunction";
}
$context = stream_context_create([
"http" => [
"method" => "GET",
"timeout" => 60,
"ignore_errors" => true
]
]);
$response = file_get_contents($url, false, $context);
echo $response;
?>
Using Guzzle HTTP Client
<?php
require "vendor/autoload.php";
use GuzzleHttp\Client;
$apiKey = "YOUR_API_KEY";
$ipAddress = "8.8.8.8";
$format = "json"; // change to xml | yml | jsonp if needed
$params = [
"key" => $apiKey,
"format" => $format
];
if ($format === "jsonp") {
$params["callback"] = "cbFunction";
}
$client = new Client([
"timeout" => 60,
"http_errors" => false
]);
$response = $client->get(
"https://api.ip2geoapi.com/ip/{$ipAddress}",
["query" => $params]
);
echo $response->getBody()->getContents();
?>
Java Examples
Integrate IP2GeoAPI into your Java applications.
Using Java SDK
<dependency>
<groupId>com.ip2geoapi</groupId>
<artifactId>ip2geo-java</artifactId>
<version>1.0.0</version>
</dependency>Quick Start
import com.ip2geo.Ip2GeoClient;
Ip2GeoClient client = new Ip2GeoClient("API_KEY");
Object response = client.lookup("check", null, null); // json default
// String response = (String) client.lookup("8.8.8.8", "yml", null);
// String response = (String) client.lookup("8.8.8.8", "xml", null);
// String response = (String) client.lookup("8.8.8.8", "jsonp", "cbFunction");
System.out.println(response);Using HttpURLConnection
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class IP2GeoAPI {
public static void main(String[] args) throws Exception {
String apiKey = "YOUR_API_KEY";
String ipAddress = "8.8.8.8";
String format = "json"; // change to xml | yml | jsonp if needed
String url = "https://api.ip2geoapi.com/ip/" + ipAddress +
"?key=" + apiKey +
"&format=" + format;
if ("jsonp".equals(format)) {
url += "&callback=cbFunction";
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
Using OkHttp
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class IP2GeoAPI {
public static void main(String[] args) throws Exception {
String apiKey = "YOUR_API_KEY";
String ipAddress = "8.8.8.8";
String format = "json"; // change to xml | yml | jsonp if needed
String url = "https://api.ip2geoapi.com/ip/" + ipAddress +
"?key=" + apiKey +
"&format=" + format;
if ("jsonp".equals(format)) {
url += "&callback=cbFunction";
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.print(response.body().string());
}
}
}
Ruby Examples
Integrate IP2GeoAPI into your Ruby applications.
Using Net::HTTP
require "net/http"
require "uri"
api_key = "YOUR_API_KEY"
ip_address = "8.8.8.8"
format = "json" # change to xml | yml | jsonp if needed
url = "https://api.ip2geoapi.com/ip/#{ip_address}?key=#{api_key}&format=#{format}"
if format == "jsonp"
url += "&callback=cbFunction"
end
uri = URI(url)
response = Net::HTTP.get_response(uri)
puts response.body
Using HTTParty
require "httparty"
api_key = "YOUR_API_KEY"
ip_address = "8.8.8.8"
format = "json" # change to xml | yml | jsonp if needed
url = "https://api.ip2geoapi.com/ip/#{ip_address}"
query = {
key: api_key,
format: format
}
if format == "jsonp"
query[:callback] = "cbFunction"
end
response = HTTParty.get(url, query: query)
puts response.body
Go Examples
Integrate IP2GeoAPI into your Go applications.
Using Go SDK
go get github.com/vijaykrpp/ip2geo-goQuick Start
package main
import (
"fmt"
"log"
"github.com/vijaykrpp/ip2geo-go/ip2geo"
)
func main() {
client := ip2geo.NewClient("API_KEY")
data, err := client.Lookup("8.8.8.8", "", "") // json default
// data, err := client.Lookup("8.8.8.8", "yml", "")
// data, err := client.Lookup("8.8.8.8", "xml", "")
// data, err := client.Lookup("8.8.8.8", "jsonp", "cbFunction")
if err != nil {
log.Fatal(err)
}
fmt.Println(data)
}Using net/http Package
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
apiKey := "YOUR_API_KEY"
ipAddress := "8.8.8.8"
format := "json" // change to xml | yml | jsonp if needed
url := fmt.Sprintf(
"https://api.ip2geoapi.com/ip/%s?key=%s&format=%s",
ipAddress, apiKey, format,
)
if format == "jsonp" {
url += "&callback=cbFunction"
}
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Print(string(body))
}
.NET Examples
Integrate IP2GeoAPI into your .NET applications.
Using HttpClient
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string ipAddress = "8.8.8.8";
string format = "json"; // change to xml | yml | jsonp if needed
string url = $"https://api.ip2geoapi.com/ip/{ipAddress}?key={apiKey}&format={format}";
if (format == "jsonp")
{
url += "&callback=cbFunction";
}
using HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
string body = await response.Content.ReadAsStringAsync();
Console.Write(body);
}
}
Rust Examples
Integrate IP2GeoAPI into your Rust applications.
Using reqwest
use reqwest;
#[tokio::main]
async fn main() -> Result<(), Box> {
let api_key = "YOUR_API_KEY";
let ip_address = "8.8.8.8";
let format = "json"; // change to xml | yml | jsonp if needed
let mut url = format!(
"https://api.ip2geoapi.com/ip/{}?key={}&format={}",
ip_address, api_key, format
);
if format == "jsonp" {
url.push_str("&callback=cbFunction");
}
let client = reqwest::Client::new();
let response = client.get(url).send().await?;
let body = response.text().await?;
print!("{}", body);
Ok(())
}
Swift Examples
Integrate IP2GeoAPI into your Swift/iOS applications.
Using URLSession
import Foundation
let apiKey = "YOUR_API_KEY"
let ipAddress = "8.8.8.8"
let format = "json" // change to xml | yml | jsonp if needed
var urlString = "https://api.ip2geoapi.com/ip/\(ipAddress)?key=\(apiKey)&format=\(format)"
if format == "jsonp" {
urlString += "&callback=cbFunction"
}
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
print(String(decoding: data, as: UTF8.self))
}
}
task.resume()
RunLoop.main.run()
Kotlin Examples
Integrate IP2GeoAPI into your Kotlin/Android applications.
Using OkHttp
import okhttp3.OkHttpClient
import okhttp3.Request
fun main() {
val apiKey = "YOUR_API_KEY"
val ipAddress = "8.8.8.8"
val format = "json" // change to xml | yml | jsonp if needed
var url = "https://api.ip2geoapi.com/ip/$ipAddress?key=$apiKey&format=$format"
if (format == "jsonp") {
url += "&callback=cbFunction"
}
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).execute().use { response ->
print(response.body!!.string())
}
}
C++ Examples
Integrate IP2GeoAPI into your C++ applications.
Using libcurl
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <iostream>
using tcp = boost::asio::ip::tcp;
namespace http = boost::beast::http;
int main() {
std::string apiKey = "YOUR_API_KEY";
std::string ipAddress = "8.8.8.8";
std::string format = "json"; // change to xml | yml | jsonp if needed
std::string host = "api.ip2geoapi.com";
std::string target = "/ip/" + ipAddress +
"?key=" + apiKey +
"&format=" + format;
if (format == "jsonp") {
target += "&callback=cbFunction";
}
boost::asio::io_context ioc;
boost::asio::ssl::context ctx(boost::asio::ssl::context::tlsv12_client);
ctx.set_default_verify_paths();
boost::asio::ssl::stream stream(ioc, ctx);
SSL_set_tlsext_host_name(stream.native_handle(), host.c_str());
tcp::resolver resolver(ioc);
auto results = resolver.resolve(host, "443");
boost::asio::connect(stream.next_layer(), results.begin(), results.end());
stream.handshake(boost::asio::ssl::stream_base::client);
http::request req{http::verb::get, target, 11};
req.set(http::field::host, host);
req.set(http::field::user_agent, "Boost.Beast");
http::write(stream, req);
boost::beast::flat_buffer buffer;
http::response res;
http::read(stream, buffer, res);
boost::system::error_code ec;
stream.shutdown(ec);
std::cout << res.body();
return 0;
}
Bash Script Examples
Integrate IP2GeoAPI into your Bash scripts.
Basic Script with jq
#!/bin/bash
API_KEY="YOUR_API_KEY"
IP_ADDRESS="8.8.8.8"
FORMAT="json" # change to xml | yml | jsonp if needed
URL="https://api.ip2geoapi.com/ip/$IP_ADDRESS?key=$API_KEY&format=$FORMAT"
if [ "$FORMAT" = "jsonp" ]; then
URL="$URL&callback=cbFunction"
fi
curl -s "$URL"
library(httr)
api_key <- "YOUR_API_KEY"
ip_address <- "8.8.8.8"
format <- "json" # change to xml | yml | jsonp if needed
url <- paste0(
"https://api.ip2geoapi.com/ip/",
ip_address,
"?key=",
api_key,
"&format=",
format
)
if (format == "jsonp") {
url <- paste0(url, "&callback=cbFunction")
}
response <- GET(url)
cat(content(response, "text", encoding = "UTF-8"))
R Examples
Integrate IP2GeoAPI into your R data analysis projects.
Using httr Package
library(httr)
library(jsonlite)
api_key <- "YOUR_API_KEY"
ip_address <- "8.8.8.8"
url <- paste0("https://api.ip2geoapi.com/ip/", ip_address)
response <- GET(url, query = list(key = api_key))
data <- fromJSON(content(response, "text"))
if (data$success) {
cat("Country:", data$geo$country, "\n")
cat("City:", data$geo$city, "\n")
cat("ISP:", data$network$isp, "\n")
} else {
cat("Error:", data$error, "\n")
}
Dart/Flutter Examples
Integrate IP2GeoAPI into your Flutter mobile applications.
Using http Package
import 'package:http/http.dart' as http;
void main() async {
final apiKey = "YOUR_API_KEY";
final ipAddress = "8.8.8.8";
final format = "json"; // change to xml | yml | jsonp if needed
var url = Uri.parse(
"https://api.ip2geoapi.com/ip/$ipAddress?key=$apiKey&format=$format"
);
if (format == "jsonp") {
url = Uri.parse("${url.toString()}&callback=cbFunction");
}
final response = await http.get(url);
print(response.body);
}
Perl Examples
Integrate IP2GeoAPI into your Perl applications.
Using LWP::UserAgent
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
my $api_key = "YOUR_API_KEY";
my $ip_address = "8.8.8.8";
my $format = "json"; # change to xml | yml | jsonp if needed
my $url = "https://api.ip2geoapi.com/ip/$ip_address?key=$api_key&format=$format";
if ($format eq "jsonp") {
$url .= "&callback=cbFunction";
}
my $ua = LWP::UserAgent->new;
$ua->timeout(60);
my $response = $ua->get($url);
print $response->decoded_content;