Authentication overview
LocationIQ uses a straightforward API key authentication model to control access to its geospatial services. An API key is a unique token that identifies the calling application or user when interacting with the LocationIQ API endpoints. This method ensures that only authorized requests consume API quotas and access specific services like geocoding, reverse geocoding, and routing. When a request is made to a LocationIQ API endpoint, the provided API key is checked against registered keys on the LocationIQ platform to validate the request's origin and associated permissions.
The API key functions as both an identifier and a secret, therefore secure handling is critical. LocationIQ's approach simplifies integration for developers while providing a measurable way to track API usage per key. This allows for usage monitoring, rate limiting, and the application of different access policies based on the subscription tier of the API key holder. For instance, developers on the LocationIQ free tier receive 5,000 requests per day, which requires an authenticated API key for access.
While API keys offer simplicity, they differ from more complex authentication schemes like OAuth 2.0, which typically involve obtaining temporary access tokens after user consent for delegated authorization (OAuth 2.0 specification details). For LocationIQ's use cases—primarily server-to-server or trusted client-server communication where the application itself is being authorized—API keys are an efficient and common method (AWS API Gateway API key usage). The key needs to be passed with every API request, usually as a query parameter.
Supported authentication methods
LocationIQ primarily supports API key authentication. This method is suitable for most applications requiring direct access to their mapping and geospatial APIs.
API Key Authentication
API key authentication involves including a unique alphanumeric string (the API key) with each request sent to the LocationIQ API. This key acts as a secret token that grants access to the associated account's API services and usage quotas. It is generally passed as a query parameter named key in the URL of the API request.
- How it works: When an API request is made, the LocationIQ server extracts the
keyparameter from the URL. It then validates this key against its database of registered API keys. If the key is valid and active, and the account associated with the key has sufficient permissions and quota, the request is processed, and the requested data is returned. - Use cases: Ideal for server-side applications, backend services, or trusted client-side applications where the API key can be securely stored or managed. It is also suitable for rapid prototyping and development due to its simplicity.
- Security considerations: API keys should be treated as sensitive credentials. Exposure can lead to unauthorized access to your LocationIQ account's API usage, potentially incurring unexpected costs or hitting rate limits. Best practices include restricting keys by IP address or referrer, and avoiding hardcoding them directly into public client-side code without additional safeguards.
Authentication Method Summary
The following table summarizes LocationIQ's primary authentication method:
| Method | When to Use | Security Level (General) |
|---|---|---|
| API Key (Query Parameter) | Server-side applications, backend services, trusted client applications, rapid development. | Moderate (requires secure key management) |
Getting your credentials
To start making authenticated requests to LocationIQ, you need to obtain an API key. This process typically involves registering for an account and generating the key through the LocationIQ dashboard.
Step-by-step guide to obtaining an API key:
- Sign up for a LocationIQ account: Navigate to the LocationIQ homepage and sign up for a new account. A valid email address is typically required for registration.
- Access the dashboard: After successful registration and login, you will be directed to your LocationIQ dashboard.
- Locate API key section: Within the dashboard, there is usually a dedicated section for managing your API keys. This might be labeled 'API Keys', 'Account Settings', or similar. Refer to the LocationIQ documentation for the exact location if you cannot find it immediately.
- Generate or retrieve your key: Most new accounts automatically receive a default API key upon creation. If not, there will be an option to generate a new key. Your API key will be displayed, and it's important to copy it securely.
- (Optional) Configure key restrictions: For enhanced security, LocationIQ allows you to add restrictions to your API key, such as specifying allowed IP addresses or HTTP referrers. This limits where your key can be used, reducing the impact if it is compromised.
Authenticated request example
Once you have your API key, you can integrate it into your API requests. The key is typically included as a query parameter named key in the URL.
Below are examples using cURL, JavaScript, and Python to perform a geocoding request to the LocationIQ API (e.g., searching for "Eiffel Tower, Paris"). Remember to replace YOUR_API_KEY with your actual API key.
cURL Example
This cURL command demonstrates a basic GET request to the LocationIQ Geocoding API:
curl "https://us1.locationiq.com/v1/search.php?key=YOUR_API_KEY&q=Eiffel%20Tower%2C%20Paris&format=json"
JavaScript Example
Using the Fetch API in JavaScript for a browser or Node.js environment:
const apiKey = 'YOUR_API_KEY';
const query = 'Eiffel Tower, Paris';
const url = `https://us1.locationiq.com/v1/search.php?key=${apiKey}&q=${encodeURIComponent(query)}&format=json`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Python Example
Using the requests library in Python:
import requests
api_key = 'YOUR_API_KEY'
query = 'Eiffel Tower, Paris'
url = 'https://us1.locationiq.com/v1/search.php'
params = {
'key': api_key,
'q': query,
'format': 'json'
}
try:
response = requests.get(url, params=params)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
These examples illustrate how the key parameter is consistently included in the URL to authenticate the request, as detailed in the LocationIQ API reference.
Security best practices
Securing your LocationIQ API keys is crucial to prevent unauthorized usage, protect your data, and avoid unexpected charges. Adhere to these best practices:
- Do not embed keys directly in public client-side code: Never hardcode your API key directly into client-side JavaScript, mobile applications, or other publicly accessible code. If exposed, your key can be easily extracted and misused. For client-side applications, consider proxying requests through your own backend server that applies the API key, or use IP-based or referrer-based restrictions.
- Use environment variables or configuration files: Store API keys in environment variables (e.g.,
LOCATIONIQ_API_KEY) or securely managed configuration files on your server. This prevents the key from being committed to version control systems like Git. - Implement IP address restrictions: Configure your API key in the LocationIQ dashboard to only accept requests originating from a specific list of IP addresses. This is highly effective for server-side applications.
- Implement HTTP referrer restrictions: For keys used in web applications, restrict them to a specific list of HTTP referrers (your domain names). This helps prevent unauthorized use from other websites.
- Rotate API keys regularly: Periodically generate new API keys and deprecate old ones. This minimizes the risk associated with a long-lived, potentially compromised key. The LocationIQ documentation will provide guidance on key rotation within your dashboard.
- Monitor API usage: Regularly review your LocationIQ API usage statistics in your dashboard. Unusual spikes in usage might indicate a compromised key or abuse.
- Secure your development environment: Ensure that your local development environment and CI/CD pipelines handle API keys securely, avoiding plain-text storage or exposure in logs.
- Never hardcode into public repositories: Avoid committing API keys to public code repositories (e.g., GitHub). Use
.gitignorefiles to exclude configuration files containing keys.
By following these guidelines, you can significantly enhance the security posture of your applications using LocationIQ APIs.