Authentication overview

Geocode.xyz utilizes API keys as its primary method for authenticating requests to its geocoding services. This system allows the API to identify the requesting application or user, manage access permissions, and track usage against account limits, including the free tier of 2,500 requests per day or paid subscription plans. API keys are unique identifiers that should be treated as sensitive credentials.

When making a request to the Geocode.xyz API, the API key is typically passed as a query parameter. This approach ensures that each request is associated with a specific account, enabling the service to enforce rate limits and provide accurate billing. Understanding the proper handling and security of these keys is crucial for maintaining the integrity and availability of your applications that rely on Geocode.xyz.

Supported authentication methods

Geocode.xyz primarily supports API key authentication. This method is straightforward to implement and widely used for accessing web services. While other authentication methods like OAuth 2.0 or mutual TLS might offer more complex security features, API keys are sufficient for the typical use cases of a geocoding service, balancing ease of use with necessary access control.

API Key

An API key is a token that a client provides when making API calls. It serves as a unique identifier and secret token for authentication. For Geocode.xyz, the API key is included directly in the request URL as a query parameter.

Table: Geocode.xyz Authentication Methods

Method When to Use Security Level
API Key (Query Parameter) All standard API requests to Geocode.xyz. Suitable for server-side applications, and client-side applications where keys are restricted to public data or proxying through a backend. Moderate. Relies on key secrecy and secure transmission (HTTPS). Vulnerable if exposed in public code or insecure channels.

Getting your credentials

To obtain your Geocode.xyz API key, you need to register for an account on their website. The process typically involves creating an account and then navigating to your user dashboard where the API key is generated and displayed. Geocode.xyz provides a dedicated API documentation page that outlines the steps for obtaining and using your key.

  1. Sign Up/Log In: Visit the Geocode.xyz homepage and either sign up for a new account or log in to an existing one.
  2. Access Dashboard: After logging in, navigate to your account dashboard or a section typically labeled "API Key" or "Credentials."
  3. Generate Key: If a key is not automatically provided, there will usually be an option to generate a new API key.
  4. Copy Key: Once generated, carefully copy your API key. This key is a sensitive credential and should be stored securely.

It is important to note that Geocode.xyz offers a free tier that includes a certain number of requests per day without requiring a credit card, though an API key is still needed for access and usage tracking.

Authenticated request example

Once you have your API key, you can include it in your API requests. The key is typically passed as a query parameter named auth or key. The following examples demonstrate how to make an authenticated request using common programming languages. All requests should be made over HTTPS to ensure the API key is encrypted during transmission, as recommended by general web security practices for HTTPS protocol usage.

Python Example

This Python example uses the requests library to perform a forward geocoding query with an API key.


import requests

API_KEY = "YOUR_API_KEY"
ADDRESS = "1600 Amphitheatre Parkway, Mountain View, CA"

url = f"https://geocode.xyz/{ADDRESS}?json=1&auth={API_KEY}"

try:
    response = requests.get(url)
    response.raise_for_status()  # Raise an exception for HTTP errors
    data = response.json()
    print("Latitude:", data.get("latt"))
    print("Longitude:", data.get("longt"))
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

PHP Example

This PHP example uses file_get_contents for a simple GET request with the API key.


<?php
$apiKey = "YOUR_API_KEY";
$address = urlencode("Eiffel Tower, Paris");

$url = "https://geocode.xyz/{$address}?json=1&auth={$apiKey}";

$response = @file_get_contents($url);

if ($response === FALSE) {
    echo "Error making request.";
} else {
    $data = json_decode($response, true);
    if (isset($data['error'])) {
        echo "API Error: " . $data['error']['message'];
    } else {
        echo "Latitude: " . $data['latt'] . "<br>";
        echo "Longitude: " . $data['longt'] . "<br>";
    }
}
?>

JavaScript (Browser/Node.js) Example

This JavaScript example uses the fetch API to make an authenticated request.


const API_KEY = "YOUR_API_KEY";
const ADDRESS = "Times Square, New York";

const url = `https://geocode.xyz/${encodeURIComponent(ADDRESS)}?json=1&auth=${API_KEY}`;

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log("Latitude:", data.latt);
    console.log("Longitude:", data.longt);
  })
  .catch(error => {
    console.error("Error fetching geocode data:", error);
  });

Security best practices

Properly securing your Geocode.xyz API key is essential to prevent unauthorized access to your account and potential service disruptions or unexpected charges. Adhering to these best practices helps maintain the integrity and security of your integrations:

  • Keep API Keys Confidential: Treat your API key as a password. Never embed it directly into client-side code (e.g., JavaScript in a public web page) or commit it to public version control systems like GitHub. If a key is exposed, it can be used by unauthorized parties, leading to usage beyond your allocated limits.
  • Use Environment Variables: For server-side applications, store API keys in environment variables rather than hardcoding them into your application's source code. This practice isolates sensitive information from the main codebase and makes it easier to manage credentials across different deployment environments.
  • Implement Server-Side Proxy: For client-side applications (e.g., single-page applications), consider routing all API requests through a secure backend proxy. Your client-side application requests your server, which then makes the authenticated call to Geocode.xyz using the securely stored API key. This prevents the API key from ever being exposed in the user's browser or network traffic.
  • Restrict API Key Usage (if applicable): While Geocode.xyz's API keys are generally broad, if the service offered IP restrictions or domain restrictions, these would be valuable to configure. Always check the Geocode.xyz API documentation for any available mechanisms to limit the scope of your API key.
  • Monitor Usage: Regularly monitor your API usage through your Geocode.xyz account dashboard. Unexpected spikes in usage could indicate a compromised API key or an issue with your application.
  • Rotate API Keys: Periodically rotate your API keys. If a key is compromised, rotating it ensures that the old key becomes invalid, mitigating potential damage. Check your Geocode.xyz account for options to regenerate or revoke API keys.
  • Use HTTPS: Always ensure that all API requests to Geocode.xyz are made over HTTPS. This encrypts the communication channel, protecting your API key and other data from interception by malicious actors during transit. The IETF RFC 2818 on HTTP Over TLS provides foundational guidance on secure communication.
  • Error Handling: Implement robust error handling in your application to gracefully manage authentication failures. This can include logging errors for review and notifying administrators, without exposing sensitive details to end-users.