Authentication overview

Dune provides a platform for querying and analyzing blockchain data, offering programmatic access through its API. Authentication is required to secure interactions with the API, ensuring that only authorized users or applications can access private data, execute queries, and manage dashboards. Dune's authentication model focuses on simplicity and security, primarily utilizing API keys for direct access.

The API allows developers to integrate Dune's analytical capabilities into custom applications, automate data retrieval, and build bespoke dashboards. Proper authentication is a prerequisite for utilizing these features, especially when dealing with private datasets or sensitive operational commands. Understanding the available authentication methods and their appropriate use cases is crucial for secure and efficient integration with the Dune platform.

Users on paid tiers, such as Plus and Enterprise, gain access to the Dune API, which enables programmatic interaction with their curated data and queries. This includes fetching query results, executing queries, and managing private content Dune pricing details. The API is designed to support various use cases, from automated reporting to embedding blockchain analytics directly into other software solutions.

Supported authentication methods

Dune primarily supports API key authentication for its programmatic interfaces.

Method When to Use Security Level
API Key Programmatic access to Dune API for fetching data, executing queries, and managing dashboards. Suitable for server-to-server communication or backend applications. High (when properly managed and rotated)

API Key Authentication

API keys are unique, alphanumeric strings that act as a secret token, identifying the calling application or user to the Dune API. When an API key is included in an API request, Dune verifies the key against its records to determine if the request is authorized. This method is common for web services due to its straightforward implementation and effectiveness in securing access to specific resources OAuth 2.0 Bearer Token usage.

Dune's API keys are associated with a user account and inherit the permissions of that account. This means that an API key can perform any action that the associated user account is authorized to perform within the Dune platform. Consequently, treating API keys with the same level of security as user credentials is a critical best practice.

API keys are typically passed in the Authorization header of HTTP requests, using the Bearer token scheme. For example:

Authorization: Bearer YOUR_DUNE_API_KEY

This standard practice ensures that the API key is transmitted securely over HTTPS/TLS, protecting it from interception during transit. It is important to note that while API keys provide authentication, they do not inherently provide fine-grained authorization beyond the scope of the associated user account. Developers should implement their own authorization logic where necessary within their applications.

Getting your credentials

To obtain an API key for Dune, you must have an active subscription to one of their paid plans (e.g., Plus or Enterprise), as API access is not available on the free tier. Once subscribed, you can generate your API key through the Dune platform's user interface.

  1. Log in to your Dune account: Access the Dune website and log in with your registered credentials Dune homepage.
  2. Navigate to Account Settings: Look for a section related to your profile or account settings. This is usually accessible by clicking on your profile icon or username in the top navigation bar.
  3. Locate API Key Management: Within your account settings, there should be a dedicated section for managing API keys. The exact naming might vary but commonly includes terms like "API Keys," "Developer Settings," or "Integrations."
  4. Generate a New API Key: Follow the prompts to generate a new API key. Dune typically allows you to create multiple keys, which can be useful for different applications or environments. When generating a key, you might have the option to name it for easier identification.
  5. Copy and Store Your API Key: Once generated, the API key will be displayed. It is crucial to copy this key immediately and store it securely. For security reasons, Dune often displays the key only once upon creation and does not allow you to retrieve it later. If lost, you would typically need to generate a new key and revoke the old one.

Remember that API keys are sensitive credentials. Treat them with the same care as passwords. Avoid hardcoding them directly into your application's source code or committing them to version control systems like Git. Instead, use environment variables or a secure secret management solution.

Authenticated request example

This example demonstrates how to make an authenticated request to the Dune API to fetch the results of a specific query using a Python script. We'll assume you have a Dune query ID and your API key.

First, ensure you have the requests library installed:

pip install requests

Then, use the following Python code:

import requests
import os

# --- Configuration ---
# It's best practice to load API keys from environment variables
DUNE_API_KEY = os.getenv("DUNE_API_KEY", "YOUR_DUNE_API_KEY_HERE")
QUERY_ID = 123456789 # Replace with an actual Dune query ID

# --- API Endpoints ---
BASE_URL = "https://api.dune.com/api/v1"
QUERY_RESULTS_ENDPOINT = f"{BASE_URL}/queries/{QUERY_ID}/results"

# --- Request Headers ---
headers = {
    "x-dune-api-key": DUNE_API_KEY,
    "Content-Type": "application/json"
}

def get_query_results(query_id: int):
    """
    Fetches the latest execution results for a given Dune query ID.
    """
    url = f"{BASE_URL}/queries/{query_id}/results"
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
        print(f"Response body: {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 error occurred: {req_err}")
    return None


if __name__ == "__main__":
    if DUNE_API_KEY == "YOUR_DUNE_API_KEY_HERE":
        print("Please set your DUNE_API_KEY environment variable or replace the placeholder.")
    else:
        print(f"Fetching results for Query ID: {QUERY_ID}...")
        results = get_query_results(QUERY_ID)
        if results:
            print("Query Results:")
            # Print a snippet of the results
            if 'result' in results and 'rows' in results['result']:
                for i, row in enumerate(results['result']['rows']):
                    print(row)
                    if i >= 4: # Print first 5 rows
                        break
            else:
                print("No 'result' or 'rows' found in the response.")
        else:
            print("Failed to retrieve query results.")

In this example, the x-dune-api-key header is used to pass the API key. This is a common pattern for custom API key authentication schemes, as opposed to the more generic Authorization: Bearer header. Always consult the Dune API documentation for the exact header name required.

Security best practices

Securing your Dune API keys and integrations is essential to protect your data and prevent unauthorized access. Adhering to these best practices will help maintain the integrity and confidentiality of your interactions with the Dune platform.

1. API Key Management

  • Treat API Keys as Passwords: Your API key grants access to your Dune account's capabilities. Never expose it in client-side code, public repositories, or unsecured environments.
  • Use Environment Variables: Store API keys in environment variables rather than hardcoding them directly into your application's source code. This keeps keys out of your codebase and makes it easier to manage different keys for different environments (development, staging, production).
  • Secure Secret Management: For more complex deployments, use dedicated secret management services (e.g., AWS Secrets Manager, Google Secret Manager, HashiCorp Vault) to store and retrieve API keys securely. These services offer robust access controls, auditing, and rotation capabilities Google Secret Manager overview.
  • Regular Rotation: Periodically rotate your API keys. If a key is compromised, rotating it minimizes the window of exposure. Dune's platform should provide functionality to revoke old keys and generate new ones.
  • Least Privilege: If Dune offers granular permissions for API keys (e.g., read-only vs. read-write), always generate keys with the minimum necessary permissions required for the task.

2. Secure Communication

  • Always Use HTTPS/TLS: Ensure all API requests to Dune are made over HTTPS (HTTP Secure) to encrypt data in transit. This protects your API key and data from eavesdropping and tampering. Dune's API endpoints are inherently served over HTTPS.
  • Verify SSL Certificates: Your HTTP client should be configured to verify SSL/TLS certificates to prevent man-in-the-middle attacks. Most modern HTTP libraries do this by default.

3. Application Security

  • Input Validation: If your application accepts user input that is then used to construct API requests (e.g., query parameters), always validate and sanitize this input to prevent injection attacks.
  • Error Handling: Implement robust error handling to gracefully manage API errors. Avoid exposing sensitive information (like API keys or internal server details) in error messages returned to end-users.
  • Rate Limiting and Throttling: Be aware of Dune's API rate limits and implement client-side rate limiting or exponential backoff strategies to avoid hitting limits and ensure your application behaves responsibly.

4. Monitoring and Auditing

  • Monitor API Usage: Keep an eye on your API usage patterns. Unusual spikes or activity might indicate a compromised key or an issue with your application.
  • Audit Logs: If Dune provides audit logs for API access or key usage, regularly review these logs for any suspicious activity.

By diligently applying these security practices, developers can significantly reduce the risk of unauthorized access and ensure the secure operation of their applications integrated with Dune.