SDKs overview

GeoJS provides an API for IP geolocation and related services, designed for straightforward integration into web and application development projects. Accessing the GeoJS API (api.geojs.io) can be achieved through direct HTTP requests or by utilizing Software Development Kits (SDKs) and community libraries. These tools abstract the underlying HTTP communication, offering language-specific methods and objects that simplify common tasks such as fetching location data for a given IP address or the client's current IP address.

The SDKs and libraries listed here are designed to streamline the process of making requests to the GeoJS API endpoints, which include functionalities like /v1/ip for an IP address lookup, /v1/ip/country for country code retrieval, and /v1/ip/geo for detailed geographic information. By using these SDKs, developers can reduce the boilerplate code required for API calls, error handling, and response parsing, enabling quicker development cycles.

While GeoJS's direct API interaction is fairly simple, using an SDK can enhance developer experience by providing idiomatic ways to interact with the service within a specific programming language environment. This page details the official SDKs and notable community-contributed libraries, their installation methods, and provides a quickstart example to demonstrate basic usage.

Official SDKs by language

GeoJS emphasizes direct API interaction via standard HTTP methods, making it accessible from any language capable of making web requests. However, it also provides specific examples of how to integrate with various popular programming languages, which serve as de facto official SDKs or highly recommended integration patterns. These examples are detailed in the GeoJS documentation.

The following table outlines common integration methods and their typical installation commands for GeoJS:

Language Package/Method Installation Command (Example) Maturity
JavaScript (Browser/Node.js) fetch or axios (external) npm install axios First-party recommended pattern
Python requests (external) pip install requests First-party recommended pattern
PHP cURL or Guzzle (external) composer require guzzlehttp/guzzle First-party recommended pattern
Ruby Net::HTTP (built-in) (No installation for Net::HTTP) First-party recommended pattern
Go net/http (built-in) (No installation for net/http) First-party recommended pattern

GeoJS does not distribute dedicated SDKs as separate package manager entries (e.g., geojs-js-sdk). Instead, it provides comprehensive examples using widely adopted, robust HTTP client libraries available in each language. This approach ensures compatibility, leverages existing community knowledge, and avoids dependency on a GeoJS-specific library for core HTTP operations.

Installation

Installation for GeoJS integration typically involves installing a standard HTTP client library for your chosen programming language rather than a dedicated GeoJS SDK. The following sections detail common installation procedures for the most frequently used languages according to the GeoJS documentation.

JavaScript (Browser & Node.js)

For JavaScript environments, the fetch API (native in modern browsers and Node.js v18+) or the axios library are commonly used. If using axios, install it via npm:

npm install axios

The fetch API does not require installation as it is a built-in browser and Node.js feature. For environments requiring polyfills for fetch, consider libraries like node-fetch for older Node.js versions.

Python

The Python requests library is the recommended method for making HTTP requests. Install it using pip:

pip install requests

This library simplifies HTTP request handling, including GET and POST requests, headers, and URL parameters, making it suitable for interacting with the GeoJS API.

PHP

PHP can interact with the GeoJS API using its native cURL functions or through a more object-oriented HTTP client like Guzzle. To install Guzzle via Composer:

composer require guzzlehttp/guzzle

Ensure Composer is installed on your system. Guzzle provides a flexible interface for making HTTP requests and is widely used in PHP projects.

Ruby

Ruby includes the Net::HTTP library in its standard library, which can be used to perform HTTP requests without additional installation. For more advanced features or a more declarative syntax, external gems like HTTParty or Faraday could be installed via Bundler:

gem install httparty
bundle install

Go

Go's standard library provides the net/http package for making HTTP requests, requiring no external dependencies for basic API interaction:

import (
    "net/http"
    "io/ioutil"
    "encoding/json"
    "fmt"
)

func main() {
    // ... code to make request ...
}

For more complex scenarios, external libraries might be used, but net/http is sufficient for GeoJS API calls.

Quickstart example

This quickstart example demonstrates how to retrieve the geolocation details for the client's current IP address using JavaScript (browser-side) and Python, showcasing the simplicity of GeoJS API integration. Both examples make a GET request to the /v1/ip/geo endpoint, which returns a JSON object containing detailed information such as country, city, and coordinates.

JavaScript (Browser)

This snippet uses the browser's native fetch API to retrieve geolocation data and log it to the console. This can be placed directly within an HTML script tag.

async function getGeolocation() {
  try {
    const response = await fetch('https://get.geojs.io/v1/ip/geo.json');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Geolocation Data:', data);
    // Example: Display country name
    document.getElementById('countryName').textContent = data.country;
  } catch (error) {
    console.error('Error fetching geolocation:', error);
  }
}

// Call the function when the page loads or on a specific event
getGeolocation();

To display data on a webpage, ensure you have an HTML element with the ID countryName:

<p>Your Country: <span id="countryName">Loading...</span></p>

Python

This Python example uses the requests library to perform the same query and print the structured JSON response. This script can be run directly from your terminal.

import requests
import json

def get_geolocation():
    try:
        response = requests.get('https://get.geojs.io/v1/ip/geo.json')
        response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)
        data = response.json()
        print("Geolocation Data:")
        print(json.dumps(data, indent=4))
        # Example: Access specific fields
        print(f"Country: {data.get('country')}")
        print(f"City: {data.get('city')}")
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Connection error occurred: {conn_err}")
    except requests.exceptions.Timeout as timeout_err:
        print(f"Timeout error occurred: {timeout_err}")
    except requests.exceptions.RequestException as req_err:
        print(f"An unexpected error occurred: {req_err}")

if __name__ == "__main__":
    get_geolocation()

Running this Python script will output the detailed geolocation information to your console, formatted for readability.

Community libraries

While GeoJS primarily encourages direct HTTP client usage, the simplicity and widespread applicability of IP geolocation services have led to the development of various community-contributed wrappers and utility functions. These libraries generally build upon the principles demonstrated in the official examples, often adding convenience features, stricter typing, or integration with specific frameworks.

Community libraries are not officially maintained by GeoJS and their continued support, security, and compatibility with future API changes may vary. Developers should verify the project's activity, documentation, and licensing before incorporating them into production systems. Searching package repositories like npm for JavaScript, PyPI for Python, or Packagist for PHP with terms like "geojs" or "ip geolocation" can reveal active community projects. For example, the W3C Geolocation API is a browser-native alternative for client-side location, though it relies on user consent and different data sources than IP-based services.

Developers are encouraged to review the source code of any third-party library to understand its implementation and ensure it meets project requirements. For most applications, the direct integration methods outlined in the official GeoJS documentation using standard HTTP clients like fetch, requests, or Guzzle are sufficient and often preferred for their minimal dependency footprint and direct control over API interaction.