Authentication overview

Authentication for the Danish data service Energi API is primarily managed through API keys. These keys serve as unique identifiers and provide the necessary credentials to access Energi's various data endpoints, including electricity spot prices, gas prices, and power grid data. The API key model ensures that only authorized applications and users can retrieve data, maintaining the integrity and security of the energy datasets.

When an application makes a request to the Energi API, the API key must be included in the request, typically within the header or as a query parameter. The Energi system then validates this key against its records to grant or deny access to the requested resources. This process is fundamental for securing data access and managing usage across different service tiers, from the free API key for limited requests to custom enterprise solutions.

Energi's approach to authentication is designed for straightforward integration, supported by comprehensive Energi API documentation and SDKs in languages like Python, JavaScript, PHP, and Ruby. These resources aim to simplify the development process, allowing developers to focus on integrating energy data into their applications rather than complex authentication mechanisms. Understanding the proper handling and management of these API keys is crucial for maintaining the security and functionality of any application built on the Energi API.

Supported authentication methods

The Danish data service Energi API predominantly utilizes API keys for authenticating requests. This method is widely adopted for its simplicity and effectiveness in controlling access to web services. An API key is a token that a client provides when making API calls, which is then verified by the server to determine if the client is authorized to perform the requested operation.

API Key Authentication

API key authentication involves generating a unique alphanumeric string that acts as a secret token. This token is then included with every API request to identify the client making the call. Energi's API expects this key to be passed in a specific manner, which is detailed in their Energi developer documentation. Typically, API keys are sent either as a custom HTTP header (e.g., X-API-Key or Authorization: Bearer <API_KEY>) or as a query parameter in the URL (e.g., ?apiKey=<API_KEY>).

The primary advantages of using API keys for authentication include:

  • Ease of Implementation: Developers can quickly integrate API key authentication into their applications without complex protocols.
  • Statelessness: API keys do not require session management, simplifying server-side implementation.
  • Granular Control: Energi can associate specific permissions and rate limits with individual API keys, allowing for fine-grained control over access to different data endpoints and usage quotas.

However, it is important to manage API keys securely, as their compromise can lead to unauthorized access to data and potential misuse of API resources. Best practices for securing API keys are discussed in a later section.

Other Potential Authentication Methods (Not Currently Supported by Energi)

While Energi focuses on API keys, other authentication methods exist in the broader API landscape. These are mentioned for context but are not currently supported by Energi:

  • OAuth 2.0: A delegated authorization framework that allows third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access with its own credentials. OAuth 2.0 is often used for user-centric APIs where a user grants an application permission to access their data without sharing their credentials directly with the application. For more information, consult the OAuth 2.0 specification.
  • Basic Authentication: A simple authentication scheme built into the HTTP protocol. It involves sending a username and password, base64-encoded, in the Authorization header. While simple, it sends credentials in a reversible format and is generally not recommended for sensitive data without HTTPS.
  • JWT (JSON Web Tokens): A compact, URL-safe means of representing claims to be transferred between two parties. JWTs are often used in conjunction with OAuth 2.0 or as a standalone token-based authentication mechanism, particularly in microservices architectures.

Energi's decision to use API keys simplifies developer integration, particularly for server-to-server communication where user context is not required. Developers should refer to the Energi API documentation for the most up-to-date information on supported authentication methods and specific implementation details.

Authentication Method Comparison

The table below summarizes the primary authentication method supported by Energi and its characteristics:

Method When to Use Security Level Complexity
API Key Server-to-server communication, client-side applications (with care), accessing public or application-specific data. Moderate (depends heavily on key management) Low

Getting your credentials

To begin interacting with the Danish data service Energi API, you will need to obtain an API key. This key serves as your primary credential for authenticating requests and accessing the available energy data. The process for acquiring an API key is designed to be straightforward and is managed through the Energi developer portal.

Steps to Obtain an API Key:

  1. Visit the Energi Developer Portal: Navigate to the official Energi API homepage.
  2. Sign Up or Log In: If you are a new user, you will need to create an account. Existing users can log in with their registered credentials.
  3. Access the Dashboard/API Key Section: Once logged in, locate the section dedicated to API key management. This is typically found within a 'Dashboard', 'My Account', or 'API Keys' area.
  4. Generate a New API Key: Follow the prompts to generate a new API key. Energi may allow you to name your key for easier identification, especially if you plan to use multiple keys for different applications or environments (e.g., development, staging, production).
  5. Copy and Store Your API Key: Once generated, your API key will be displayed. It is critical to copy this key immediately and store it securely. For security reasons, Energi typically only displays the full key once, and you may not be able to retrieve it again if lost. Treat your API key as a sensitive secret.
  6. Understand Usage Limits: Be aware of the usage limits associated with your API key, especially if you are on the free tier. These limits typically include a maximum number of requests per period and restrictions on historical data access (e.g., 24-hour historical data for the free tier).

For detailed, step-by-step instructions with screenshots, always refer to the official Energi API documentation.

Considerations for Multiple API Keys:

Energi's system may allow for the generation of multiple API keys. This practice is recommended for several reasons:

  • Application-Specific Keys: Assign a unique API key to each application or service that interacts with the Energi API. This makes it easier to track usage and revoke access for a specific application without affecting others.
  • Environment-Specific Keys: Use separate keys for development, testing, and production environments. This prevents accidental data manipulation in production from development environments and simplifies credential rotation.
  • Key Rotation: Regularly rotate your API keys. If a key is compromised, revoking it and issuing a new one minimizes the window of vulnerability.

Always ensure that your API keys are managed in accordance with security best practices to prevent unauthorized access to Energi's data.

Authenticated request example

Once you have obtained your API key from the Energi developer portal, you can use it to make authenticated requests to the Energi API. The following examples demonstrate how to include your API key in a request using common programming languages. These examples assume your API key is named YOUR_API_KEY and is passed as a query parameter called apiKey, as is a common pattern for API key authentication, though specific implementation details should always be verified against the official Energi API documentation.

Python Example

Using the requests library, a common choice for HTTP requests in Python:


import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.energi.dk/v1/"
ENDPOINT = "spotprices"

params = {
    "apiKey": API_KEY,
    "area": "DK1", # Example: Danish bidding zone 1
    "date": "2026-05-29" # Example: Today's date
}

try:
    response = requests.get(f"{BASE_URL}{ENDPOINT}", params=params)
    response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
    data = response.json()
    print("Successfully fetched data:")
    print(data)
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
    if response.status_code == 401:
        print("Authentication failed. Check your API key.")
    elif response.status_code == 403:
        print("Access denied. Check permissions or rate limits.")

JavaScript (Node.js with axios) Example

For server-side JavaScript applications, axios is a popular choice:


const axios = require('axios');

const API_KEY = "YOUR_API_KEY";
const BASE_URL = "https://api.energi.dk/v1/";
const ENDPOINT = "gasprices";

async function getGasPrices() {
    try {
        const response = await axios.get(`${BASE_URL}${ENDPOINT}`, {
            params: {
                apiKey: API_KEY,
                date: "2026-05-29", // Example: Today's date
                currency: "EUR" // Example: Currency
            }
        });
        console.log("Successfully fetched data:", response.data);
    } catch (error) {
        console.error("An error occurred:", error.message);
        if (error.response) {
            console.error("Status:", error.response.status);
            console.error("Data:", error.response.data);
            if (error.response.status === 401) {
                console.error("Authentication failed. Check your API key.");
            }
        }
    }
}

getGasPrices();

PHP Example

Using file_get_contents for a simple request, or cURL for more advanced scenarios:


<?php

$apiKey = "YOUR_API_KEY";
$baseUrl = "https://api.energi.dk/v1/";
$endpoint = "powergriddata";

$params = [
    "apiKey" => $apiKey,
    "area" => "DK", // Example: All Denmark
    "from" => "2026-05-28T00:00:00Z",
    "to" => "2026-05-29T00:00:00Z"
];

$url = $baseUrl . $endpoint . '?' . http_build_query($params);

$context = stream_context_create([
    'http' => [
        'ignore_errors' => true, // Allow checking HTTP status codes
    ],
]);

$response = @file_get_contents($url, false, $context);

if ($response === FALSE) {
    echo "Error making request.\n";
} else {
    $http_status = $http_response_header[0];
    if (strpos($http_status, '200 OK') !== false) {
        $data = json_decode($response, true);
        echo "Successfully fetched data:\n";
        print_r($data);
    } else {
        echo "API request failed: " . $http_status . "\n";
        if (strpos($http_status, '401 Unauthorized') !== false) {
            echo "Authentication failed. Check your API key.\n";
        }
    }
}

?>

These examples illustrate the basic structure of an authenticated request. Always replace "YOUR_API_KEY" with your actual API key and consult the Energi API documentation for specific endpoint paths, required parameters, and response formats.

Security best practices

Securing your API keys and ensuring the integrity of your interactions with the Danish data service Energi API is paramount. Adhering to security best practices helps prevent unauthorized access to your account and protects the data you retrieve. While API keys offer simplicity, their security relies heavily on how they are managed and used.

1. Treat API Keys as Sensitive Credentials

Your API key grants access to your Energi account's data and resources. It should be treated with the same level of security as a username and password. Never embed API keys directly into client-side code (e.g., JavaScript in a web browser) where they can be easily exposed. If an API key is compromised, it can lead to unauthorized data access, exceeding rate limits, or incurring costs on your account.

2. Use Environment Variables or Secret Management Services

Instead of hardcoding API keys directly into your application's source code, store them in environment variables or use a dedicated secret management service. This practice ensures that keys are not exposed in version control systems (like Git) and can be easily managed across different deployment environments. For example, in a Node.js application, you might use process.env.ENERGI_API_KEY, or in a Python application, os.environ.get('ENERGI_API_KEY').

  • Environment Variables: Suitable for most applications, especially for smaller deployments.
  • Secret Management Services: For larger, more complex deployments, consider services like AWS Secrets Manager, Google Secret Manager, or Azure Key Vault. These services provide centralized, secure storage and retrieval of secrets, including API keys. Google Cloud Secret Manager documentation provides details on how to use such a service.

3. Implement HTTPS/TLS for All API Communication

Always ensure that all communication with the Energi API occurs over HTTPS (HTTP Secure). HTTPS encrypts the data exchanged between your application and the API server, protecting your API key and the retrieved data from eavesdropping and man-in-the-middle attacks. The Energi API, like most modern APIs, enforces HTTPS for all endpoints, but it's crucial to verify your application's configuration.

4. Restrict API Key Permissions (Least Privilege)

If Energi offers the ability to create API keys with specific permissions (e.g., read-only access to certain endpoints), always generate keys with the minimum necessary privileges for a given application. This principle of least privilege minimizes the impact if a key is compromised.

5. Implement IP Whitelisting (if available)

If Energi's API key management system supports IP whitelisting, configure your API keys to only accept requests originating from a specific set of IP addresses. This adds an extra layer of security, as even if a key is stolen, it cannot be used from an unauthorized IP address.

6. Rotate API Keys Regularly

Periodically rotate your API keys by generating new ones and revoking the old ones. This practice reduces the window of exposure if a key is unknowingly compromised. The frequency of rotation depends on your security policy and the sensitivity of the data accessed.

7. Monitor API Usage for Anomalies

Regularly monitor your API usage patterns. Unusual spikes in requests, requests from unexpected geographical locations, or access to endpoints not typically used by your application could indicate a compromised API key. Implement alerting mechanisms to notify you of such anomalies.

8. Secure Your Development Environment

Ensure that your development machines and environments are secure. Use strong passwords, keep software updated, and employ firewalls and antivirus solutions. A compromised development environment can expose API keys and other sensitive credentials.

9. Error Handling and Logging

Implement robust error handling in your application to gracefully manage authentication failures. Log authentication attempts and failures (without logging the API key itself) to help identify potential security incidents. However, avoid logging the actual API key in plain text as this creates a security risk.

By diligently following these security best practices, you can significantly enhance the protection of your Energi API integrations and safeguard your data.