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" | python -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 Requests Library
import requests
api_key = "YOUR_API_KEY"
ip_address = "8.8.8.8"
url = f"https://api.ip2geoapi.com/ip/{ip_address}"
params = {"key": api_key}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
if data['success']:
geo = data['geo']
country_info = data['countryInfo']
network = data['network']
security = data['security']
print(f"IP: {data['ip']}")
print(f"Country: {geo['country']} ({geo['countryCode']})")
print(f"City: {geo['city']}")
print(f"Latitude: {geo['latitude']}")
print(f"Longitude: {geo['longitude']}")
print(f"ISP: {network['isp']}")
print(f"Organization: {network['organization']}")
print(f"Trust Score: {security['trustScore']}")
print(f"Risk Level: {security['riskLevel']}")
else:
print(f"Error: {response.status_code}")
Async with aiohttp
import aiohttp
import asyncio
async def get_ip_info(ip_address, api_key):
url = f"https://api.ip2geoapi.com/ip/{ip_address}"
params = {"key": api_key}
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
async with session.get(url, params=params) as response:
if response.status != 200:
return {"success": False, "error": f"HTTP {response.status}"}
try:
return await response.json()
except Exception:
return {"success": False, "error": "Invalid JSON response"}
except asyncio.TimeoutError:
return {"success": False, "error": "Request timed out"}
except Exception as e:
return {"success": False, "error": str(e)}
async def main():
API_KEY = "YOUR_API_KEY"
IP_ADDRESS = "8.8.8.8"
data = await get_ip_info(IP_ADDRESS, API_KEY)
if data.get("success"):
print(f"Country: {data['geo']['country']}")
print(f"Security Risk: {data['security']['riskLevel']}")
print(f"Trust Score: {data['security']['trustScore']}")
else:
print(f"Error: {data.get('error')}")
asyncio.run(main())
Node.js Examples
Integrate IP2GeoAPI into your Node.js applications.
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 }
})
.then(response => {
const data = response.data;
if (data.success) {
const { geo, countryInfo, network, security } = data;
console.log(`IP: ${data.ip}`);
console.log(`Country: ${geo.country} (${geo.countryCode})`);
console.log(`City: ${geo.city}`);
console.log(`Latitude: ${geo.latitude}`);
console.log(`Longitude: ${geo.longitude}`);
console.log(`ISP: ${network.isp}`);
console.log(`Organization: ${network.organization}`);
console.log(`Trust Score: ${security.trustScore}`);
console.log(`Risk Level: ${security.riskLevel}`);
}
})
.catch(error => {
console.error('Error:', error.message);
});
Using Fetch API
const API_KEY = 'YOUR_API_KEY';
const IP_ADDRESS = '8.8.8.8';
fetch(`https://api.ip2geoapi.com/ip/${IP_ADDRESS}?key=${API_KEY}`)
.then(async (response) => {
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
if (data.success) {
console.log(`Country: ${data.geo.country}`);
console.log(`Timezone: ${data.timezoneInfo.timezone}`);
console.log(`Trust Score: ${data.security.trustScore}`);
} else {
console.error(`API Error: ${data.error}`);
}
})
.catch((error) => {
console.error('Request failed:', error);
});
Using Native HTTPS Module
const https = require('https');
const API_KEY = 'YOUR_API_KEY';
const IP_ADDRESS = '8.8.8.8';
const url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}?key=${API_KEY}`;
const req = https.get(url, (res) => {
let data = '';
// Check HTTP status
if (res.statusCode !== 200) {
console.error(`HTTP Error: ${res.statusCode}`);
res.resume(); // drain stream
return;
}
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const result = JSON.parse(data);
if (result.success) {
console.log(`Country: ${result.geo.country}`);
console.log(`Organization: ${result.network.organization}`);
console.log(`Risk Level: ${result.security.riskLevel}`);
} else {
console.error(`API Error: ${result.error}`);
}
} catch (err) {
console.error('JSON Parse Error:', err.message);
}
});
});
// Request-level error handler
req.on('error', (err) => {
console.error('Request failed:', err.message);
});
// Optional: timeout
req.setTimeout(10000, () => {
console.error('Request timed out');
req.destroy();
});
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";
// Optional: Define response type for IntelliSense
interface Ip2GeoResponse {
success: boolean;
ip: string;
geo: {
city: string | null;
country: string;
latitude: number;
longitude: number;
};
network: {
isp: string | null;
organization: string | null;
};
security: {
trustScore: number;
riskLevel: string;
};
error?: string;
}
async function lookupIp() {
try {
const url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}`;
const response = await axios.get(url, {
params: { key: API_KEY }
});
const data = response.data;
if (data.success) {
console.log("IP:", data.ip);
console.log("Country:", data.geo.country);
console.log("City:", data.geo.city);
console.log("ISP:", data.network.isp);
console.log("Risk Level:", data.security.riskLevel);
} else {
console.error("API Error:", data.error);
}
} catch (err) {
console.error("Request failed:", err);
}
}
lookupIp();
Javascript Examples
Integrate IP2GeoAPI into your Javascript applications.
Using Fetch API
const API_KEY = "YOUR_API_KEY";
const IP_ADDRESS = "8.8.8.8";
async function lookupIp() {
try {
const url = `https://api.ip2geoapi.com/ip/${IP_ADDRESS}?key=${API_KEY}`;
const res = await fetch(url);
const data = await res.json();
if (data.success) {
console.log("IP:", data.ip);
console.log("Country:", data.geo.country);
console.log("City:", data.geo.city);
console.log("ISP:", data.network.isp);
console.log("Risk Level:", data.security.riskLevel);
} else {
console.error("API Error:", data.error);
}
} catch (err) {
console.error("Request failed:", err);
}
}
lookupIp();
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";
$.ajax({
url: `https://api.ip2geoapi.com/ip/${IP_ADDRESS}`,
method: "GET",
data: {
key: API_KEY
},
success: function(data) {
if (data.success) {
console.log("IP:", data.ip);
console.log("Country:", data.geo.country);
console.log("City:", data.geo.city);
console.log("ISP:", data.network.isp);
console.log("Risk Level:", data.security.riskLevel);
} else {
console.error("API Error:", data.error);
}
},
error: function(xhr, status, err) {
console.error("Request failed:", err);
}
});
</script>
PHP Examples
Integrate IP2GeoAPI into your PHP applications.
Using cURL
<?php
$apiKey = "YOUR_API_KEY";
$ipAddress = "8.8.8.8";
$url = "https://api.ip2geoapi.com/ip/{$ipAddress}?key={$apiKey}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$data = json_decode($response, true);
if ($data['success']) {
$geo = $data['geo'];
$countryInfo = $data['countryInfo'];
$network = $data['network'];
$security = $data['security'];
echo "IP: " . $data['ip'] . "\n";
echo "Country: " . $geo['country'] . " (" . $geo['countryCode'] . ")\n";
echo "City: " . $geo['city'] . "\n";
echo "Latitude: " . $geo['latitude'] . "\n";
echo "Longitude: " . $geo['longitude'] . "\n";
echo "ISP: " . $network['isp'] . "\n";
echo "Organization: " . $network['organization'] . "\n";
echo "Trust Score: " . $security['trustScore'] . "\n";
echo "Risk Level: " . $security['riskLevel'] . "\n";
}
} else {
echo "Error: HTTP {$httpCode}\n";
}
?>
Using file_get_contents
<?php
$apiKey = 'YOUR_API_KEY';
$ipAddress = '8.8.8.8';
$url = "https://api.ip2geoapi.com/ip/{$ipAddress}?key={$apiKey}";
$response = file_get_contents($url);
$data = json_decode($response, true);
if ($data['success']) {
echo "Country: " . $data['geo']['country'] . "\n";
echo "Timezone: " . $data['timezoneInfo']['timezone'] . "\n";
echo "Risk Level: " . $data['security']['riskLevel'] . "\n";
} else {
echo "Error: " . $data['error'] . "\n";
}
?>
Using Guzzle HTTP Client
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$apiKey = 'YOUR_API_KEY';
$ipAddress = '8.8.8.8';
$client = new Client();
$response = $client->get("https://api.ip2geoapi.com/ip/{$ipAddress}", [
'query' => ['key' => $apiKey]
]);
$data = json_decode($response->getBody(), true);
if ($data['success']) {
echo "Country: " . $data['geo']['country'] . "\n";
echo "Organization: " . $data['network']['organization'] . "\n";
} else {
echo "Error: " . $data['error'] . "\n";
}
?>
Java Examples
Integrate IP2GeoAPI into your Java applications.
Using HttpURLConnection
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.JSONObject;
public class IP2GeoAPI {
public static void main(String[] args) {
String apiKey = "YOUR_API_KEY";
String ipAddress = "8.8.8.8";
String url = String.format(
"https://api.ip2geoapi.com/ip/%s?key=%s",
ipAddress, apiKey
);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Accept", "application/json")
.GET()
.build();
try {
HttpResponse response = client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
if (response.statusCode() == 200) {
JSONObject data = new JSONObject(response.body());
if (data.getBoolean("success")) {
JSONObject geo = data.getJSONObject("geo");
JSONObject network = data.getJSONObject("network");
JSONObject security = data.getJSONObject("security");
System.out.println("IP: " + data.getString("ip"));
System.out.println("Country: " + geo.getString("country")
+ " (" + geo.getString("countryCode") + ")");
System.out.println("City: " + geo.getString("city"));
System.out.println("Latitude: " + geo.getDouble("latitude"));
System.out.println("Longitude: " + geo.getDouble("longitude"));
System.out.println("ISP: " + network.getString("isp"));
System.out.println("Organization: " + network.getString("organization"));
System.out.println("Trust Score: " + security.getInt("trustScore"));
System.out.println("Risk Level: " + security.getString("riskLevel"));
} else {
System.out.println("API returned success=false");
}
} else {
System.out.println("HTTP Error: " + response.statusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Using OkHttp
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;
public class IP2GeoAPI {
public static void main(String[] args) {
String apiKey = "YOUR_API_KEY";
String ipAddress = "8.8.8.8";
String url = "https://api.ip2geoapi.com/ip/" + ipAddress + "?key=" + apiKey;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.out.println("HTTP Error: " + response.code());
return;
}
String responseBody = response.body() != null ? response.body().string() : "";
JSONObject data = new JSONObject(responseBody);
if (data.getBoolean("success")) {
System.out.println("Country: " +
data.getJSONObject("geo").getString("country"));
System.out.println("Timezone: " +
data.getJSONObject("timezoneInfo").getString("timezone"));
System.out.println("Risk Level: " +
data.getJSONObject("security").getInt("riskLevel"));
} else {
System.out.println("API Error: " + data.getString("error"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Ruby Examples
Integrate IP2GeoAPI into your Ruby applications.
Using Net::HTTP
require 'net/http'
require 'json'
require 'uri'
api_key = "YOUR_API_KEY"
ip_address = "8.8.8.8"
url = "https://api.ip2geoapi.com/ip/#{ip_address}?key=#{api_key}"
uri = URI(url)
response = Net::HTTP.get_response(uri)
if response.code.to_i == 200
data = JSON.parse(response.body)
if data['success']
geo = data['geo']
network = data['network']
security = data['security']
puts "IP: #{data['ip']}"
puts "Country: #{geo['country']} (#{geo['countryCode']})"
puts "City: #{geo['city']}"
puts "Latitude: #{geo['latitude']}"
puts "Longitude: #{geo['longitude']}"
puts "ISP: #{network['isp']}"
puts "Organization: #{network['organization']}"
puts "Trust Score: #{security['trustScore']}"
puts "Risk Level: #{security['riskLevel']}"
end
else
puts "Error: HTTP #{response.code}"
end
Using HTTParty
require 'httparty'
api_key = 'YOUR_API_KEY'
ip_address = '8.8.8.8'
response = HTTParty.get(
"https://api.ip2geoapi.com/ip/#{ip_address}",
query: { key: api_key }
)
if response.success?
data = response.parsed_response
if data['success']
puts "Country: #{data['geo']['country']}"
puts "Timezone: #{data['timezoneInfo']['timezone']}"
puts "Risk Level: #{data['security']['riskLevel']}"
else
puts "API Error: #{data['error']}"
end
else
puts "HTTP Error: #{response.code}"
end
Go Examples
Integrate IP2GeoAPI into your Go applications.
Using net/http Package
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Response struct {
Success bool `json:"success"`
IP string `json:"ip"`
Geo struct {
Country string `json:"country"`
CountryCode string `json:"countryCode"`
City string `json:"city"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
} `json:"geo"`
Network struct {
ISP string `json:"isp"`
Organization string `json:"organization"`
} `json:"network"`
Security struct {
TrustScore int `json:"trustScore"`
RiskLevel string `json:"riskLevel"`
} `json:"security"`
}
func main() {
apiKey := "YOUR_API_KEY"
ipAddress := "8.8.8.8"
url := fmt.Sprintf(
"https://api.ip2geoapi.com/ip/%s?key=%s",
ipAddress, apiKey
)
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var data Response
json.Unmarshal(body, &data)
if data.Success {
fmt.Printf("IP: %s\n", data.IP)
fmt.Printf("Country: %s (%s)\n", data.Geo.Country, data.Geo.CountryCode)
fmt.Printf("City: %s\n", data.Geo.City)
fmt.Printf("ISP: %s\n", data.Network.ISP)
fmt.Printf("Trust Score: %d\n", data.Security.TrustScore)
}
}
.NET Examples
Integrate IP2GeoAPI into your .NET applications.
Using HttpClient
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
static async Task Main(string[] args)
{
string apiKey = "YOUR_API_KEY";
string ipAddress = "8.8.8.8";
string url = $"https://api.ip2geoapi.com/ip/{ipAddress}?key={apiKey}";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Accept", "application/json");
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
JObject data = JObject.Parse(content);
if ((bool)data["success"])
{
var geo = data["geo"];
var network = data["network"];
var security = data["security"];
Console.WriteLine($"IP: {data["ip"]}");
Console.WriteLine($"Country: {geo["country"]} ({geo["countryCode"]})");
Console.WriteLine($"City: {geo["city"]}");
Console.WriteLine($"ISP: {network["isp"]}");
Console.WriteLine($"Trust Score: {security["trustScore"]}");
Console.WriteLine($"Risk Level: {security["riskLevel"]}");
}
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
}
}
Rust Examples
Integrate IP2GeoAPI into your Rust applications.
Using reqwest
use reqwest;
use serde_json::Value;
#[tokio::main]
async fn main() -> Result<(), Box> {
let api_key = "YOUR_API_KEY";
let ip_address = "8.8.8.8";
let url = format!(
"https://api.ip2geoapi.com/ip/{}?key={}",
ip_address, api_key
);
let client = reqwest::Client::new();
let response = client
.get(&url)
.header("Accept", "application/json")
.send()
.await?;
if response.status().is_success() {
let data: Value = response.json().await?;
if data["success"].as_bool().unwrap_or(false) {
let geo = &data["geo"];
let network = &data["network"];
let security = &data["security"];
println!("IP: {}", data["ip"]);
println!("Country: {} ({})", geo["country"], geo["countryCode"]);
println!("City: {}", geo["city"]);
println!("Latitude: {}", geo["latitude"]);
println!("Longitude: {}", geo["longitude"]);
println!("ISP: {}", network["isp"]);
println!("Organization: {}", network["organization"]);
println!("Trust Score: {}", security["trustScore"]);
println!("Risk Level: {}", security["riskLevel"]);
} else {
println!("API returned success=false");
}
} else {
println!("HTTP error: {}", response.status());
}
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 urlString = "https://api.ip2geoapi.com/ip/\(ipAddress)?key=\(apiKey)"
guard let url = URL(string: urlString) else {
print("Invalid URL")
exit(1)
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let data = data else {
print("No data received")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
if let success = json["success"] as? Bool, success == true {
let ip = json["ip"] as? String ?? ""
let geo = json["geo"] as? [String: Any] ?? [:]
let network = json["network"] as? [String: Any] ?? [:]
let security = json["security"] as? [String: Any] ?? [:]
print("IP: \(ip)")
print("Country: \(geo["country"] ?? "") (\(geo["countryCode"] ?? ""))")
print("City: \(geo["city"] ?? "")")
print("Latitude: \(geo["latitude"] ?? 0)")
print("Longitude: \(geo["longitude"] ?? 0)")
print("ISP: \(network["isp"] ?? "")")
print("Organization: \(network["organization"] ?? "")")
print("Trust Score: \(security["trustScore"] ?? "")")
print("Risk Level: \(security["riskLevel"] ?? "")")
} else {
print("API error or invalid response")
}
}
} catch {
print("JSON parse error: \(error)")
}
}
task.resume()
Kotlin Examples
Integrate IP2GeoAPI into your Kotlin/Android applications.
Using OkHttp
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
fun main() {
val apiKey = "YOUR_API_KEY"
val ipAddress = "8.8.8.8"
val url = "https://api.ip2geoapi.com/ip/$ipAddress?key=$apiKey"
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
println("Error: HTTP ${response.code}")
return
}
val body = response.body?.string() ?: return
val json = JSONObject(body)
if (json.optBoolean("success")) {
val geo = json.optJSONObject("geo") ?: JSONObject()
val network = json.optJSONObject("network") ?: JSONObject()
val security = json.optJSONObject("security") ?: JSONObject()
println("IP: ${json.optString("ip")}")
println("Country: ${geo.optString("country")} (${geo.optString("countryCode")})")
println("City: ${geo.optString("city")}")
println("Latitude: ${geo.optDouble("latitude")}")
println("Longitude: ${geo.optDouble("longitude")}")
println("ISP: ${network.optString("isp")}")
println("Organization: ${network.optString("organization")}")
println("Trust Score: ${security.optInt("trustScore")}")
println("Risk Level: ${security.optString("riskLevel")}")
} else {
println("API returned success=false")
}
}
}
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 <nlohmann/json.hpp>
#include <iostream>
using tcp = boost::asio::ip::tcp;
namespace http = boost::beast::http;
using json = nlohmann::json;
int main() {
std::string apiKey = "YOUR_API_KEY";
std::string ipAddress = "8.8.8.8";
std::string host = "api.ip2geoapi.com";
std::string target = "/ip/" + ipAddress + "?key=" + apiKey;
int port = 443;
boost::asio::io_context ioc;
boost::asio::ssl::context ctx(boost::asio::ssl::context::tlsv12_client);
// Load system default root certificates
ctx.set_default_verify_paths();
boost::asio::ssl::stream stream(ioc, ctx);
// Set SNI hostname
if(!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) {
std::cerr << "SNI error\n";
return 1;
}
tcp::resolver resolver(ioc);
auto const results = resolver.resolve(host, "443");
boost::asio::connect(stream.next_layer(), results.begin(), results.end());
stream.handshake(boost::asio::ssl::stream_base::client);
// Build HTTP GET request
http::request req{http::verb::get, target, 11};
req.set(http::field::host, host);
req.set(http::field::user_agent, "C++17 Boost.Beast Client");
http::write(stream, req);
boost::beast::flat_buffer buffer;
http::response res;
http::read(stream, buffer, res);
// Close connection
boost::system::error_code ec;
stream.shutdown(ec);
if(ec == boost::asio::error::eof) {
ec = {};
}
if(ec) {
std::cerr << "Shutdown failed: " << ec.message() << "\n";
}
// Parse JSON
auto data = json::parse(res.body());
if (data["success"].get()) {
auto geo = data["geo"];
auto network = data["network"];
auto security = data["security"];
std::cout << "IP: " << data["ip"] << "\n";
std::cout << "Country: " << geo["country"] << " (" << geo["countryCode"] << ")\n";
std::cout << "City: " << geo["city"] << "\n";
std::cout << "Latitude: " << geo["latitude"] << "\n";
std::cout << "Longitude: " << geo["longitude"] << "\n";
std::cout << "ISP: " << network["isp"] << "\n";
std::cout << "Organization: " << network["organization"] << "\n";
std::cout << "Trust Score: " << security["trustScore"] << "\n";
std::cout << "Risk Level: " << security["riskLevel"] << "\n";
}
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"
URL="https://api.ip2geoapi.com/ip/$IP_ADDRESS?key=$API_KEY"
response=$(curl -s "$URL")
success=$(echo "$response" | jq -r '.success')
if [ "$success" != "true" ]; then
echo "API returned success=false or error"
exit 1
fi
ip=$(echo "$response" | jq -r '.ip')
country=$(echo "$response" | jq -r '.geo.country')
country_code=$(echo "$response" | jq -r '.geo.countryCode')
city=$(echo "$response" | jq -r '.geo.city')
lat=$(echo "$response" | jq -r '.geo.latitude')
lon=$(echo "$response" | jq -r '.geo.longitude')
isp=$(echo "$response" | jq -r '.network.isp')
org=$(echo "$response" | jq -r '.network.organization')
trust=$(echo "$response" | jq -r '.security.trustScore')
risk=$(echo "$response" | jq -r '.security.riskLevel')
echo "IP: $ip"
echo "Country: $country ($country_code)"
echo "City: $city"
echo "Latitude: $lat"
echo "Longitude: $lon"
echo "ISP: $isp"
echo "Organization: $org"
echo "Trust Score: $trust"
echo "Risk Level: $risk"
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))
if (response$status_code != 200) {
print(paste("HTTP error:", response$status_code))
quit()
}
data <- fromJSON(content(response, "text", encoding = "UTF-8"))
if (data$success) {
geo <- data$geo
network <- data$network
security <- data$security
cat("IP:", data$ip, "\n")
cat("Country:", geo$country, "(", geo$countryCode, ")\n")
cat("City:", geo$city, "\n")
cat("Latitude:", geo$latitude, "\n")
cat("Longitude:", geo$longitude, "\n")
cat("ISP:", network$isp, "\n")
cat("Organization:", network$organization, "\n")
cat("Trust Score:", security$trustScore, "\n")
cat("Risk Level:", security$riskLevel, "\n")
} else {
print("API returned success = FALSE")
}
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 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
final apiKey = "YOUR_API_KEY";
final ipAddress = "8.8.8.8";
final url = Uri.parse("https://api.ip2geoapi.com/ip/$ipAddress?key=$apiKey");
try {
final response = await http.get(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
if (data['success'] == true) {
final geo = data['geo'];
final network = data['network'];
final security = data['security'];
print("IP: ${data['ip']}");
print("Country: ${geo['country']} (${geo['countryCode']})");
print("City: ${geo['city']}");
print("Latitude: ${geo['latitude']}");
print("Longitude: ${geo['longitude']}");
print("ISP: ${network['isp']}");
print("Organization: ${network['organization']}");
print("Trust Score: ${security['trustScore']}");
print("Risk Level: ${security['riskLevel']}");
} else {
print("API returned success = false");
}
} else {
print("HTTP Error: ${response.statusCode}");
}
} catch (e) {
print("Error: $e");
}
}
Perl Examples
Integrate IP2GeoAPI into your Perl applications.
Using LWP::UserAgent
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use JSON;
my $api_key = 'YOUR_API_KEY';
my $ip_address = '8.8.8.8';
my $url = "https://api.ip2geoapi.com/ip/$ip_address?key=$api_key";
# Create UserAgent
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
# Make GET request
my $response = $ua->get($url);
if ($response->is_success) {
# Decode JSON
my $json = decode_json($response->decoded_content);
if ($json->{success}) {
print "IP: $json->{ip}\n";
print "Country: $json->{geo}->{country}\n";
print "City: $json->{geo}->{city}\n";
print "ISP: $json->{network}->{isp}\n";
print "Organization: $json->{network}->{organization}\n";
print "Continent: $json->{geo}->{continentName}\n";
print "Timezone: $json->{timezoneInfo}->{timezone}\n";
print "Local Time: $json->{timezoneInfo}->{localTime}\n";
print "Trust Score: $json->{security}->{trustScore}\n";
print "Risk Level: $json->{security}->{riskLevel}\n";
}
else {
print "API Error: $json->{error}\n";
}
} else {
die "HTTP Request failed: " . $response->status_line . "\n";
}