Libraries
Other Languages & Integrations
Our GeoIP API can be integrated with any programming language that supports HTTP requests. Here are examples for various languages and platforms.
REST API
All SDKs are built on top of our REST API. You can make direct HTTP requests:
# Get current IP
curl "https://api.geoipapi.com/ip"
# Get geolocation data
curl "https://api.geoipapi.com/json"
Response Format
All endpoints return JSON in this format:
{
"ip": "143.244.47.99",
"type": "IPv4",
"country": {
"is_eu_member": false,
"currency_code": "USD",
"continent": "NA",
"name": "United States",
"country_code": "US",
"state": "New York",
"city": "New York",
"zip": "10123",
"timezone": "America/New_York"
},
"location": {
"latitude": 40.71274915752556,
"longitude": -74.00695761274129
},
"asn": {
"number": 212238,
"name": "Datacamp Limited",
"network": "143.244.47.0/24",
"type": "HOSTING"
}
}
Ruby
require 'net/http'
require 'json'
class GeoIPClient
BASE_URL = 'https://api.geoipapi.com'
def initialize
@http = Net::HTTP.new(URI(BASE_URL).host, URI(BASE_URL).port)
@http.use_ssl = true
end
def get_ip
uri = URI("#{BASE_URL}/ip")
request = Net::HTTP::Get.new(uri)
response = @http.request(request)
response.body.strip.gsub('"', '')
end
def get_ip_data
uri = URI("#{BASE_URL}/json")
request = Net::HTTP::Get.new(uri)
response = @http.request(request)
JSON.parse(response.body)
end
end
# Usage
client = GeoIPClient.new
current_ip = client.get_ip
location_data = client.get_ip_data
puts "Current IP: #{current_ip}"
puts "Location: #{location_data['country']['city']}, #{location_data['country']['name']}"
Rust
use reqwest;
use serde::Deserialize;
#[derive(Deserialize)]
struct GeoIPResponse {
ip: String,
#[serde(rename = "type")]
ip_type: String,
country: Country,
location: Location,
asn: ASN,
}
#[derive(Deserialize)]
struct Country {
is_eu_member: bool,
currency_code: String,
continent: String,
name: String,
country_code: String,
state: String,
city: String,
zip: Option<String>,
timezone: String,
}
#[derive(Deserialize)]
struct Location {
latitude: f64,
longitude: f64,
}
#[derive(Deserialize)]
struct ASN {
number: u32,
name: String,
network: String,
#[serde(rename = "type")]
asn_type: String,
}
pub struct GeoIPClient {
client: reqwest::Client,
base_url: String,
}
impl GeoIPClient {
pub fn new() -> Self {
Self {
client: reqwest::Client::new(),
base_url: "https://api.geoipapi.com".to_string(),
}
}
pub async fn get_ip(&self) -> Result<String, Box<dyn std::error::Error>> {
let response = self.client
.get(&format!("{}/ip", self.base_url))
.send()
.await?;
let ip = response.text().await?;
Ok(ip.trim().replace("\"", ""))
}
pub async fn get_ip_data(&self) -> Result<GeoIPResponse, Box<dyn std::error::Error>> {
let response = self.client
.get(&format!("{}/json", self.base_url))
.send()
.await?;
let geo_data: GeoIPResponse = response.json().await?;
Ok(geo_data)
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = GeoIPClient::new();
let current_ip = client.get_ip().await?;
let geo_data = client.get_ip_data().await?;
println!("Current IP: {}", current_ip);
println!("Location: {}, {}", geo_data.country.city, geo_data.country.name);
Ok(())
}
Swift
import Foundation
struct GeoIPResponse: Codable {
let ip: String
let type: String
let country: Country
let location: Location
let asn: ASN
}
struct Country: Codable {
let isEuMember: Bool
let currencyCode: String
let continent: String
let name: String
let countryCode: String
let state: String
let city: String
let zip: String?
let timezone: String
enum CodingKeys: String, CodingKey {
case isEuMember = "is_eu_member"
case currencyCode = "currency_code"
case continent, name
case countryCode = "country_code"
case state, city, zip, timezone
}
}
struct Location: Codable {
let latitude: Double
let longitude: Double
}
struct ASN: Codable {
let number: Int
let name: String
let network: String
let type: String
}
class GeoIPClient {
private let baseURL = "https://api.geoipapi.com"
func getIP(completion: @escaping (String?) -> Void) {
guard let url = URL(string: "\(baseURL)/ip") else {
completion(nil)
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data,
let ip = String(data: data, encoding: .utf8) else {
completion(nil)
return
}
completion(ip.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\"", with: ""))
}.resume()
}
func getIPData(completion: @escaping (GeoIPResponse?) -> Void) {
guard let url = URL(string: "\(baseURL)/json") else {
completion(nil)
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else {
completion(nil)
return
}
let geoData = try? JSONDecoder().decode(GeoIPResponse.self, from: data)
completion(geoData)
}.resume()
}
}
// Usage
let client = GeoIPClient()
client.getIP { ip in
if let ip = ip {
print("Current IP: \(ip)")
}
}
client.getIPData { geoData in
if let data = geoData {
print("Location: \(data.country.city), \(data.country.name)")
}
}
Kotlin
import kotlinx.coroutines.*
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.net.URI
@Serializable
data class GeoIPResponse(
val ip: String,
val type: String,
val country: Country,
val location: Location,
val asn: ASN
)
@Serializable
data class Country(
@SerialName("is_eu_member") val isEuMember: Boolean,
@SerialName("currency_code") val currencyCode: String,
val continent: String,
val name: String,
@SerialName("country_code") val countryCode: String,
val state: String,
val city: String,
val zip: String?,
val timezone: String
)
@Serializable
data class Location(
val latitude: Double,
val longitude: Double
)
@Serializable
data class ASN(
val number: Int,
val name: String,
val network: String,
val type: String
)
class GeoIPClient {
private val client = HttpClient.newHttpClient()
private val baseUrl = "https://api.geoipapi.com"
suspend fun getIP(): String? {
return try {
val request = HttpRequest.newBuilder()
.uri(URI.create("$baseUrl/ip"))
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
response.body().trim().replace("\"", "")
} catch (e: Exception) {
null
}
}
suspend fun getIPData(): GeoIPResponse? {
return try {
val request = HttpRequest.newBuilder()
.uri(URI.create("$baseUrl/json"))
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
Json.decodeFromString<GeoIPResponse>(response.body())
} catch (e: Exception) {
null
}
}
}
fun main() = runBlocking {
val client = GeoIPClient()
val currentIP = client.getIP()
val geoData = client.getIPData()
currentIP?.let { println("Current IP: $it") }
geoData?.let { println("Location: ${it.country.city}, ${it.country.name}") }
}
PowerShell
class GeoIPClient {
[string]$BaseUrl = "https://api.geoipapi.com"
[string] GetIP() {
try {
$response = Invoke-RestMethod -Uri "$($this.BaseUrl)/ip"
return $response.Trim('"')
}
catch {
Write-Error "Failed to get IP: $_"
return $null
}
}
[PSCustomObject] GetIPData() {
try {
$response = Invoke-RestMethod -Uri "$($this.BaseUrl)/json"
return $response
}
catch {
Write-Error "Failed to get IP data: $_"
return $null
}
}
}
# Usage
$client = [GeoIPClient]::new()
$currentIP = $client.GetIP()
$geoData = $client.GetIPData()
Write-Host "Current IP: $currentIP"
Write-Host "Location: $($geoData.country.city), $($geoData.country.name)"
Write-Host "Coordinates: $($geoData.location.latitude), $($geoData.location.longitude)"
Need Another Language?
If you need an SDK for a language not listed here, please contact us and let us know. We're always looking to expand our SDK offerings based on community demand.
You can also contribute by creating your own SDK wrapper around our REST API and sharing it with the community.