Authentication overview
positionstack relies on a simple, token-based authentication mechanism using API keys. This approach is common for web services providing public data access with usage tracking. When a client makes a request to a positionstack endpoint, an API key must be included to authorize the call and associate it with a specific user account. This key serves as both an identifier and a secret, granting access to the specified API services.
The primary function of an API key in this context is to:
- Identify the caller: Distinguishes legitimate users from unauthorized access attempts.
- Track usage: Enables positionstack to monitor request volume against account quotas, particularly relevant for its free and paid tiers.
- Enforce policies: Allows for the application of rate limits and access restrictions based on the subscription level associated with the key.
Unlike more complex protocols such as OAuth 2.0, API key authentication is generally simpler to implement, making it suitable for applications where the primary concern is controlled access to data rather than delegated authorization to third-party services. Developers should treat their positionstack API keys as sensitive credentials due to their direct access capabilities.
Supported authentication methods
positionstack exclusively supports API key authentication. This method involves generating a unique secret string, often referred to as an access_key, from the user's dashboard. This key is then appended to every API request as a query parameter. The API key acts as a secret token, identifying the client application making the request.
The following table outlines the specifics of positionstack's authentication method:
| Method | Description | When to Use | Security Level |
|---|---|---|---|
API Key (access_key) |
A unique alphanumeric string sent as a query parameter with each request. | All API interactions with positionstack, for both forward and reverse geocoding. | Moderate (relies on key secrecy; vulnerable if exposed client-side without restrictions). |
This approach simplifies client integration, as it avoids complex token exchange flows. However, developers must implement appropriate security measures to protect the API key from unauthorized exposure, especially in client-side applications. For server-side integrations, environmental variables or secret management systems are recommended.
Getting your credentials
To obtain your positionstack API key (access_key), follow these steps:
- Sign Up/Log In: Navigate to the positionstack website and either sign up for a new account or log in to your existing one. A free tier is available, offering 10,000 requests per month.
- Access Dashboard: Once logged in, you will typically be redirected to your personal dashboard or account overview page.
- Locate API Key: Your unique
access_keyis usually prominently displayed on this dashboard. It may be labeled explicitly as "Your Access Key," "API Key," or similar. The official positionstack documentation provides visual guidance for locating this key. - Copy the Key: Copy the entire string. This is the credential you will use in all your API requests.
It is crucial to treat this key as a sensitive password. Avoid hardcoding it directly into client-side code that can be inspected (e.g., JavaScript in public web pages). For server-side applications, retrieve the key from secure environment variables or a secret management service.
Authenticated request example
Authenticating with positionstack involves appending your access_key as a query parameter to the request URL. The following examples demonstrate how to make an authenticated request using common programming languages and cURL.
cURL Example
This cURL command demonstrates a basic forward geocoding request for "1600 Amphitheatre Parkway, Mountain View, CA" using a placeholder API key:
curl "http://api.positionstack.com/v1/forward?access_key=YOUR_ACCESS_KEY&query=1600%20Amphitheatre%20Parkway,%20Mountain%20View,%20CA"
Replace YOUR_ACCESS_KEY with your actual API key retrieved from your positionstack dashboard.
Python Example
This Python example uses the requests library to perform a similar authenticated request:
import requests
import os
# It's best practice to load your API key from environment variables
access_key = os.environ.get("POSITIONSTACK_ACCESS_KEY")
if not access_key:
print("Error: POSITIONSTACK_ACCESS_KEY environment variable not set.")
exit()
base_url = "http://api.positionstack.com/v1/forward"
params = {
"access_key": access_key,
"query": "1600 Amphitheatre Parkway, Mountain View, CA"
}
try:
response = requests.get(base_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"Request failed: {e}")
To run this Python code, set an environment variable named POSITIONSTACK_ACCESS_KEY with your actual key.
JavaScript (Browser) Example
For client-side JavaScript, direct embedding of the API key is generally discouraged due to security risks. If absolutely necessary, consider domain restrictions on your API key or proxying requests through a backend server. This example is for demonstration purposes and assumes the key is safely managed (e.g., restricted by domain):
const accessKey = "YOUR_ACCESS_KEY"; // In a real app, load this securely
const query = "1600 Amphitheatre Parkway, Mountain View, CA";
const url = `http://api.positionstack.com/v1/forward?access_key=${accessKey}&query=${encodeURIComponent(query)}`;
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("Fetch error:", error);
});
For production client-side applications, it is highly recommended to proxy requests through your own backend server, which can then add the API key securely. This prevents direct exposure of the key in the browser's developer tools.
Security best practices
Securing your positionstack API key is essential to prevent unauthorized usage, protect your account from exceeding rate limits, and maintain the integrity of your application. Adhering to these best practices will help mitigate common security risks:
-
Never Expose API Keys in Client-Side Code: Avoid embedding your
access_keydirectly into JavaScript code that runs in a user's browser or any other publicly accessible client-side application. Exposed keys can be easily stolen and misused. If client-side access is required, consider:- Proxying Requests: Route all client-side API calls through your own backend server. The server can then securely add the API key before forwarding the request to positionstack. This isolates the key from the client.
- Domain Restrictions: Check if positionstack offers IP address or HTTP referrer restrictions for API keys in your dashboard. This can limit where your key can be used, even if exposed.
-
Use Environment Variables for Server-Side Applications: When deploying server-side applications, store your
access_keyin environment variables rather than hardcoding it directly into your source code. This practice is widely adopted for sensitive credentials and is supported by most cloud platforms (e.g., AWS Lambda environment variables, Google Cloud authentication). -
Utilize Secret Management Services: For complex or enterprise-level applications, integrate with a dedicated secret management service. Examples include AWS Secrets Manager, Google Secret Manager, or HashiCorp Vault. These services provide secure storage, versioning, and access control for API keys and other sensitive data.
-
Rotate API Keys Periodically: Regularly generate new API keys and deactivate old ones. This practice, known as key rotation, limits the impact if an old key is compromised without your knowledge. Refer to your positionstack dashboard for key management options.
-
Implement Rate Limiting on Your End: Even though positionstack has its own rate limits, implementing additional rate limiting within your application can prevent abusive or erroneous calls from exhausting your quota and potentially exposing your key to excessive use if compromised.
-
Monitor Usage and Logs: Regularly check your positionstack account's usage statistics and any associated logs. Unusual spikes in activity could indicate a compromised key or an unintended application behavior.
-
Secure Development Practices: Apply general secure coding principles, such as input validation and error handling, to prevent vulnerabilities that could lead to API key exposure.
By following these guidelines, developers can significantly enhance the security posture of applications integrating with positionstack's geocoding API, protecting both their accounts and their users' data.