Getting started overview
Integrating with Danish data service Energi involves a sequence of steps designed to get developers accessing energy data quickly. This guide focuses on the initial setup, from account creation and API key generation to executing a successful first API call. Energi provides a RESTful API for retrieving various data points related to the Danish energy market, including electricity spot prices, gas prices, and power grid information. The API supports a free tier for initial exploration, offering limited requests and access to 24-hour historical data, which is suitable for testing and development before committing to a paid plan.
The process is streamlined by comprehensive API documentation and available SDKs for Python, JavaScript, PHP, and Ruby, which abstract away some of the complexities of HTTP requests and response parsing. Adherence to API key authentication is crucial for all requests, ensuring secure access to data. This getting started page aims to provide a clear path to making your first successful interaction with the Energi API.
Quick reference steps
| Step | What to do | Where |
|---|---|---|
| 1. Account Creation | Register for a new user account. | Energi Signup Page |
| 2. API Key Generation | Generate your unique API key from the dashboard. | Energi API Keys Dashboard |
| 3. Install SDK (Optional) | Install the preferred language SDK (e.g., Python). | Energi SDK Documentation |
| 4. Make First Request | Construct and execute an API call using your key. | Energi API Examples |
| 5. Explore Endpoints | Review available data endpoints for specific needs. | Energi API Endpoints Reference |
Create an account and get keys
To begin using the Danish data service Energi API, the first step is to create an account. Navigate to the Energi signup page and complete the registration process. This typically involves providing an email address, setting a password, and agreeing to the terms of service. Upon successful registration, you will gain access to your personal Energi dashboard.
Once logged into your dashboard, locate the section dedicated to API keys. This is usually found under settings or a specific API management tab, such as the Energi API Keys Dashboard. Here, you will have the option to generate a new API key. It is recommended to create a separate API key for each application or environment (e.g., development, staging, production) to facilitate easier key management and revocation if necessary. Your API key is a unique identifier that authenticates your requests to the Energi API, and it should be treated as sensitive information, similar to a password. Do not hardcode it directly into client-side code or publicly expose it. For secure handling of API keys, consider using environment variables or a secrets management service, as recommended by general API security practices outlined in resources like Swagger's API Key Authentication guide.
The free tier account provides immediate access to the API with certain limitations, including a cap on the number of requests and historical data access limited to the past 24 hours. This free tier is ideal for development and testing purposes. Should your project require higher request volumes or more extensive historical data, you can review the Energi pricing plans and upgrade your account accordingly.
Your first request
After successfully obtaining your API key, you are ready to make your first request to the Danish data service Energi API. This example demonstrates how to retrieve current electricity spot prices, a common use case for the Energi API. We will use Python for this example, leveraging the requests library, which is a widely used HTTP client for Python, as detailed in the MDN Web Docs on HTTP.
Prerequisites
- Python installed on your system.
- The
requestslibrary installed (pip install requests). - Your Energi API key.
Python example
This Python script fetches the latest electricity spot prices. Replace YOUR_API_KEY with the actual API key you generated from your Energi dashboard.
import requests
import json
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.energi.dk/v1"
ENDPOINT = "/spotprices"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Accept": "application/json"
}
params = {
"limit": 1 # Get only the latest spot price
}
try:
response = requests.get(f"{BASE_URL}{ENDPOINT}", headers=headers, params=params)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
data = response.json()
print("Successfully fetched electricity spot prices:")
print(json.dumps(data, indent=2))
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response content: {response.text}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An unexpected error occurred: {req_err}")
This script constructs a GET request to the /spotprices endpoint, including your API key in the Authorization header as a Bearer token. The limit=1 parameter ensures that only the most recent spot price data is returned, which is efficient for a first test. Upon a successful response, the JSON data is parsed and printed to the console.
Expected output
A successful response will typically return a JSON object containing an array of spot price data. An example structure might look like this:
{
"data": [
{
"timestamp": "2026-05-29T10:00:00Z",
"price_dkk_per_mwh": 750.50,
"currency": "DKK",
"unit": "MWh"
}
],
"meta": {
"total": 1,
"limit": 1,
"offset": 0
}
}
The exact fields and values will vary based on the latest data available and the specific endpoint called. The Energi API Endpoints Reference provides detailed schema information for each available endpoint.
Common next steps
After successfully making your first API call, you can explore the broader capabilities of the Danish data service Energi API. Here are some common next steps:
- Explore additional endpoints: The Energi API offers various endpoints beyond spot prices, including gas prices, power grid data, and consumption data. Review the API documentation to identify endpoints relevant to your application's needs.
- Implement error handling: Production applications require robust error handling. Expand your code to gracefully manage various HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error) and network issues. The IETF RFC 9110 provides a comprehensive list of HTTP status code definitions.
- Utilize SDKs: While direct HTTP requests are feasible, using one of the official Energi SDKs (Python, JavaScript, PHP, Ruby) can simplify integration. SDKs often handle authentication, request formatting, and response parsing, reducing boilerplate code.
- Implement data caching: To optimize performance and reduce API call volume, consider implementing a caching strategy for frequently accessed static or semi-static data. Ensure your caching policy respects data freshness requirements.
- Monitor API usage: Keep track of your API call volume through your Energi dashboard to stay within your plan's limits, especially if you are on the free tier or a usage-based paid plan.
- Plan for scaling: As your application grows, anticipate increased API usage. Review the Energi pricing page for higher-tier plans that offer increased request limits and access to more extensive historical data.
- Secure your API key: Reiterate the importance of securing your API key. Never embed it directly in client-side code, and use environment variables or a secrets management service in server-side applications.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting steps and common problems along with their solutions:
Common issues
-
401 Unauthorized: This is almost always an issue with your API key. Ensure it is correctly included in the
Authorizationheader with theBearerprefix, as shown in the Energi API authentication documentation. Double-check for typos or leading/trailing spaces. Verify that the key has not been revoked or expired through your Energi API Keys Dashboard. - 403 Forbidden: This typically indicates that your API key does not have the necessary permissions to access the requested resource. For example, if you are attempting to access historical data beyond 24 hours on the free tier, you will receive a 403 error. Check your current plan and its associated access levels on the Energi pricing page.
- 404 Not Found: This error suggests that the endpoint URL is incorrect or the resource you are trying to access does not exist. Verify the endpoint path against the Energi API Endpoints Reference. Check for typos in the base URL or the specific endpoint.
-
429 Too Many Requests: You have exceeded the rate limits for your current plan. The free tier has strict rate limits. Implement exponential backoff or increase your plan tier to handle higher request volumes. The API response often includes
Retry-Afterheaders to indicate when you can safely retry the request, as discussed in MDN Web Docs on Retry-After. -
Network/Connection Errors: If you receive errors like "Connection refused" or "Timeout," check your internet connection. Also, ensure that no firewalls or proxy settings are blocking outgoing requests from your development environment to
api.energi.dk. - Invalid JSON Response: If your code fails to parse the JSON response, inspect the raw response content. There might be an error message in HTML or plain text instead of JSON, often indicating a server-side error or an unhandled exception before JSON serialization.
Debugging tips
- Print full response: Always print the full HTTP response (status code, headers, and body) when debugging. This provides comprehensive information about what the API server is sending back.
- Use a tool like Postman/Insomnia: Before writing code, test your API calls with a dedicated API client like Postman or Insomnia. These tools allow you to construct requests, add headers, and inspect responses without writing any code, helping to isolate issues to either your request parameters or your code logic.
- Consult documentation: Refer to the Energi API documentation for specific endpoint requirements, expected parameters, and response structures.
- Check server logs (if applicable): If you have access to server-side logs for your application, they might provide further insights into how your application is interacting with the Energi API.