Authentication overview
The Tankerkoenig API provides access to real-time fuel prices for gas stations across Germany, sourced from official government data. To ensure controlled access and manage usage, the API employs a direct API key authentication model. This method requires developers to register and obtain a unique API key, which acts as a credential to authorize their requests. Each API call made to the Tankerkoenig endpoints must include this key for successful data retrieval.
API key authentication is a common practice for public APIs due to its simplicity and ease of implementation. It allows the API provider to identify the consuming application, enforce rate limits, and distinguish between free-tier usage and paid subscriptions. For Tankerkoenig, this system supports their free tier of up to 50 requests per day and scales with their paid service levels. Adherence to best practices for API key management is crucial to maintain the security and integrity of applications integrating with Tankerkoenig.
Supported authentication methods
Tankerkoenig exclusively supports API key authentication. This method involves embedding a generated key directly into API requests, typically as a query parameter. Other authentication schemes, such as OAuth 2.0 or mutual TLS (mTLS), are not offered for the Tankerkoenig public API. The choice of API key authentication aligns with the API's primary use case of providing read-only access to publicly available fuel price data rather than managing user-specific data or requiring complex authorization flows.
The following table outlines the key characteristics of Tankerkoenig's supported authentication method:
| Method | When to Use | Security Level |
|---|---|---|
| API Key | Accessing public, read-only fuel price data from Tankerkoenig. Suitable for server-side applications and mobile apps where the key can be securely stored or proxied. | Moderate. Provides identification and rate limiting. Requires careful key management to prevent unauthorized usage if exposed. |
While API keys are straightforward, they differ from more robust token-based authentication systems like OAuth 2.0, which are designed for delegated authorization and often provide short-lived, refreshable tokens. For Tankerkoenig, the API key serves as a persistent credential.
Getting your credentials
To obtain your Tankerkoenig API key, you must register on the official Tankerkoenig website. The process typically involves creating an account and then requesting an API key through their developer portal. This key is unique to your account and should be treated as a confidential credential.
- Visit the Tankerkoenig API Website: Navigate to the Tankerkoenig API documentation page.
- Registration: Look for a registration or sign-up link. You will likely need to provide an email address and create a password.
- API Key Request: Once registered and logged in, there should be a section or button to generate a new API key. This key will be displayed to you and should be copied immediately.
- Store Your Key Securely: After generation, store your API key in a secure location. It is generally not retrievable through the portal after initial display for security reasons. If lost, you may need to generate a new key.
The Tankerkoenig API key is a string of alphanumeric characters. It authenticates your application against the API, allowing you to consume the data according to your account's rate limits (e.g., 50 requests per day for the free tier or higher limits for paid subscriptions).
Authenticated request example
Once you have obtained your API key, you can include it in your API requests. The Tankerkoenig API expects the key to be passed as a query parameter named apikey. Below are examples demonstrating how to make an authenticated request using common programming languages.
Python example
This Python example uses the requests library to query the list endpoint, which provides a list of all fuel stations.
import requests
API_KEY = "YOUR_TANKERKOENIG_API_KEY"
BASE_URL = "https://creativecommons.tankerkoenig.de/json/list.php"
params = {
"lat": 52.5200,
"lng": 13.4050,
"rad": 5,
"sort": "price",
"type": "e5",
"apikey": API_KEY
}
try:
response = requests.get(BASE_URL, params=params)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
Node.js example
This Node.js example uses the built-in fetch API to make a similar request.
const API_KEY = "YOUR_TANKERKOENIG_API_KEY";
const BASE_URL = "https://creativecommons.tankerkoenig.de/json/list.php";
const lat = 52.5200;
const lng = 13.4050;
const rad = 5;
const sort = "price";
const type = "e5";
const url = `${BASE_URL}?lat=${lat}&lng=${lng}&rad=${rad}&sort=${sort}&type=${type}&apikey=${API_KEY}`;
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("An error occurred:", error);
});
In both examples, replace "YOUR_TANKERKOENIG_API_KEY" with your actual API key. The parameters lat, lng, rad, sort, and type are specific to the list endpoint for filtering fuel stations by location and fuel type.
Security best practices
Securing your API key is critical to prevent unauthorized access to your Tankerkoenig API quota and potential misuse. Adhering to established security practices helps protect your credentials and ensures the reliability of your integration.
- Do Not Expose API Keys in Client-Side Code: Never embed your API key directly into client-side code (e.g., JavaScript in a web browser or mobile app binaries without obfuscation). If an API key is exposed on the client side, it can be easily extracted and used by unauthorized parties, leading to exceeded rate limits or charges if you are on a paid plan. Instead, use a backend proxy server to make API calls, passing the API key securely from your server.
- Store API Keys Securely: On server-side applications, API keys should not be hardcoded directly into source files. Instead, store them in environment variables, secure configuration files, or a dedicated secret management service. This practice prevents keys from being committed to version control systems (like Git) and makes them easier to manage across different deployment environments (development, staging, production).
- Implement Rate Limiting and Monitoring: Even with a securely stored key, it's prudent to implement your own rate limiting on your application's calls to the Tankerkoenig API. Monitor your API usage to detect unusual spikes that might indicate a compromised key or an application error.
- Rotate API Keys Regularly: Periodically generating a new API key and revoking the old one reduces the risk associated with a single key being compromised for an extended period. The Tankerkoenig developer portal should provide functionality for key rotation.
- Restrict API Key Privileges (If Applicable): While the Tankerkoenig API keys generally grant access to all available data endpoints, for other APIs that offer granular permissions, always assign the minimum necessary privileges to an API key.
- Use HTTPS: Always ensure that all communication with the Tankerkoenig API occurs over HTTPS. This encrypts the data in transit, protecting your API key and the retrieved fuel price information from interception. Modern HTTP client libraries typically enforce HTTPS by default, but it's important to verify. The Cloudflare explanation of HTTPS provides further details on its importance.
- Error Handling: Implement robust error handling in your application to gracefully manage failed API requests, including those due to invalid or missing API keys. This prevents application crashes and can help diagnose authentication issues.
By following these best practices, developers can build secure and reliable applications that integrate with the Tankerkoenig API, protecting both their own resources and the integrity of the API service.