IP Location Query API
Get detailed location information for any IP address
Overview
The IP Location Query API provides comprehensive geolocation information for any IPv4 or IPv6 address. Get detailed location data including country, region, city, ISP, timezone, and coordinates.
Endpoint
POST https://ipconfig.com/api/ip-query
Authentication
This API requires authentication using an API key. Include your API key in the request headers:
Authorization: Bearer YOUR_API_KEY
Request Format
Headers
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY
Body Parameters
Parameter | Type | Required | Description |
---|---|---|---|
ip | string | Yes | The IP address to query (IPv4 or IPv6) |
lang | string | No | Response language (en or zh ). Default: en |
Example Request
{
"ip": "8.8.8.8",
"lang": "en"
}
Usage Examples
# Set your API key
export IPCONFIG_API_KEY='your-api-key-here'
# Basic IP query
curl -H "Content-Type: application/json" \
-H "Authorization: Bearer $IPCONFIG_API_KEY" \
-X POST "https://ipconfig.com/api/ip-query" \
-d '{
"ip": "8.8.8.8",
"lang": "en"
}'
# Query IPv6 address
curl -H "Content-Type: application/json" \
-H "Authorization: Bearer $IPCONFIG_API_KEY" \
-X POST "https://ipconfig.com/api/ip-query" \
-d '{
"ip": "2001:4860:4860::8888",
"lang": "en"
}'
async function queryIPLocation(ip, lang = 'en') {
const apiKey = process.env.IPCONFIG_API_KEY;
if (!apiKey) {
throw new Error('API key not configured');
}
try {
const response = await fetch('https://ipconfig.com/api/ip-query', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ ip, lang })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.success) {
return data.data;
} else {
throw new Error(data.error || 'Unknown API error');
}
} catch (error) {
console.error('IP query failed:', error);
throw error;
}
}
// Usage example
queryIPLocation('8.8.8.8', 'en')
.then(result => {
console.log('IP Location Info:', result);
console.log(`Location: ${result.city}, ${result.country}`);
console.log(`ISP: ${result.isp}`);
console.log(`Coordinates: ${result.latitude}, ${result.longitude}`);
})
.catch(error => {
console.error('Error:', error.message);
});
import requests
import os
import json
def query_ip_location(ip_address, lang='en'):
"""Query IP location information"""
# Get API key from environment variable
api_key = os.getenv("IPCONFIG_API_KEY")
if not api_key:
raise ValueError("Please set IPCONFIG_API_KEY environment variable")
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"ip": ip_address,
"lang": lang
}
try:
response = requests.post(
"https://ipconfig.com/api/ip-query",
headers=headers,
json=payload,
timeout=10
)
response.raise_for_status()
data = response.json()
if data.get("success"):
return data["data"]
else:
raise Exception(f"API Error: {data.get('error', 'Unknown error')}")
except requests.exceptions.RequestException as e:
raise Exception(f"Request failed: {e}")
# Usage example
if __name__ == "__main__":
try:
# Query Google DNS
result = query_ip_location("8.8.8.8", "en")
print(f"IP: {result['ip']}")
print(f"Country: {result.get('country', 'Unknown')}")
print(f"Province: {result.get('province', 'Unknown')}")
print(f"City: {result.get('city', 'Unknown')}")
print(f"ISP: {result.get('isp', 'Unknown')}")
print(f"ASN: {result.get('asn', 'Unknown')}")
print(f"Location: {result.get('latitude', 0)}, {result.get('longitude', 0)}")
print(f"Timezone: {result.get('time_zone', 'Unknown')}")
except Exception as e:
print(f"Error: {e}")
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
type IPQueryRequest struct {
IP string `json:"ip"`
Lang string `json:"lang"`
}
type APIResponse struct {
Success bool `json:"success"`
Data *IPResult `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
type Meta struct {
IsLoggedIn bool `json:"isLoggedIn"`
IsApiRequest bool `json:"isApiRequest"`
CurrentCredits int `json:"currentCredits"`
}
type IPResult struct {
IP string `json:"ip"`
Continent string `json:"continent,omitempty"`
Country string `json:"country,omitempty"`
Province string `json:"province,omitempty"`
City string `json:"city,omitempty"`
District string `json:"district,omitempty"`
ISP string `json:"isp,omitempty"`
ASN string `json:"asn,omitempty"`
Latitude float64 `json:"latitude,omitempty"`
Longitude float64 `json:"longitude,omitempty"`
TimeZone string `json:"time_zone,omitempty"`
Currency string `json:"currency,omitempty"`
ZipCode string `json:"zip_code,omitempty"`
AreaCode string `json:"area_code,omitempty"`
}
func queryIPLocation(ipAddress, lang string) (*IPResult, error) {
// Get API key from environment variable
apiKey := os.Getenv("IPCONFIG_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("IPCONFIG_API_KEY environment variable not set")
}
// Prepare request payload
payload := IPQueryRequest{
IP: ipAddress,
Lang: lang,
}
jsonData, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal JSON: %v", err)
}
// Create request
req, err := http.NewRequest("POST", "https://ipconfig.com/api/ip-query", bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %v", err)
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %v", err)
}
defer resp.Body.Close()
// Parse response
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %v", err)
}
var apiResp APIResponse
if err := json.Unmarshal(body, &apiResp); err != nil {
return nil, fmt.Errorf("failed to parse JSON: %v", err)
}
if !apiResp.Success {
return nil, fmt.Errorf("API error: %s", apiResp.Error)
}
return apiResp.Data, nil
}
func main() {
result, err := queryIPLocation("8.8.8.8", "en")
if err != nil {
fmt.Printf("Query failed: %v\n", err)
return
}
fmt.Printf("IP: %s\n", result.IP)
fmt.Printf("Country: %s\n", result.Country)
fmt.Printf("Province: %s\n", result.Province)
fmt.Printf("City: %s\n", result.City)
fmt.Printf("ISP: %s\n", result.ISP)
fmt.Printf("ASN: %s\n", result.ASN)
fmt.Printf("Location: %.6f, %.6f\n", result.Latitude, result.Longitude)
fmt.Printf("Timezone: %s\n", result.TimeZone)
}
<?php
function queryIPLocation($ip, $lang = 'en') {
// Get API key from environment variable
$apiKey = getenv('IPCONFIG_API_KEY');
if (!$apiKey) {
throw new Exception('IPCONFIG_API_KEY environment variable not set');
}
$payload = json_encode([
'ip' => $ip,
'lang' => $lang
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
],
'content' => $payload,
'timeout' => 10
]
]);
$response = file_get_contents('https://ipconfig.com/api/ip-query', false, $context);
if ($response === false) {
throw new Exception('Request failed');
}
$data = json_decode($response, true);
if (!$data['success']) {
throw new Exception('API Error: ' . ($data['error'] ?? 'Unknown error'));
}
return $data['data'];
}
// Usage example
try {
$result = queryIPLocation('8.8.8.8', 'en');
echo "IP: " . $result['ip'] . "\n";
echo "Country: " . ($result['country'] ?? 'Unknown') . "\n";
echo "Province: " . ($result['province'] ?? 'Unknown') . "\n";
echo "City: " . ($result['city'] ?? 'Unknown') . "\n";
echo "ISP: " . ($result['isp'] ?? 'Unknown') . "\n";
echo "ASN: " . ($result['asn'] ?? 'Unknown') . "\n";
echo "Location: " . ($result['latitude'] ?? 0) . ", " . ($result['longitude'] ?? 0) . "\n";
echo "Timezone: " . ($result['time_zone'] ?? 'Unknown') . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
Response Format
Success Response
{
"success": true,
"data": {
"ip": "8.8.8.8",
"continent": "North America",
"country": "United States",
"province": "California",
"city": "Mountain View",
"district": "",
"isp": "Google LLC",
"asn": "AS15169",
"latitude": 37.4056,
"longitude": -122.0775,
"time_zone": "America/Los_Angeles",
"currency": "USD",
"zip_code": "94043",
"area_code": "650"
},
"meta": {
"isLoggedIn": true,
"isApiRequest": true,
"currentCredits": 1247
}
}
Error Response
{
"success": false,
"error": "Invalid IP address format",
"meta": {
"isLoggedIn": true,
"isApiRequest": true,
"currentCredits": 1247
}
}
Response Fields
Field | Type | Description |
---|---|---|
ip | string | The queried IP address |
continent | string | Continent name |
country | string | Country name |
province | string | Province/State name |
city | string | City name |
district | string | District/County name |
isp | string | Internet Service Provider |
asn | string | Autonomous System Number |
latitude | number | Latitude coordinate |
longitude | number | Longitude coordinate |
time_zone | string | Timezone identifier |
currency | string | Local currency code |
zip_code | string | Postal/ZIP code |
area_code | string | Phone area code |
Error Codes
Code | Description |
---|---|
InvalidIP | Invalid IP address format |
PrivateIP | Private IP address not supported |
RateLimitExceeded | API rate limit exceeded |
InsufficientCredits | Not enough API credits |
InvalidAPIKey | Invalid or missing API key |
Rate Limits
- Free Tier: 1,000 requests per month
- Pro Tier: 10,000 requests per month
- Enterprise: Custom limits available
Rate limits are enforced per API key. Exceeded limits will return a 429 Too Many Requests
status.
Best Practices
- Cache Results: IP location data doesn't change frequently, cache for 24-48 hours
- Handle Errors Gracefully: Always implement proper error handling
- Validate IP Addresses: Validate IP format before making requests
- Use Appropriate Language: Set the
lang
parameter based on user preference - Monitor Credits: Keep track of your API credit usage
Use Cases
- Geolocation Services: Show location-based content
- Fraud Detection: Identify suspicious IP addresses
- Analytics: Understand user geographic distribution
- Content Personalization: Customize content by location
- Security: Block or allow access based on location
- Compliance: Implement geo-restrictions for legal compliance
Supported IP Types
- IPv4: Standard IPv4 addresses (e.g.,
192.168.1.1
) - Public IPs Only: Private/internal IP addresses are not supported
Related APIs
- Get My IP API - Get your current public IP address
- Ping Test API - Test network connectivity to various locations