Authentication overview

Etherscan API employs a straightforward authentication model centered around API keys. An API key serves as a unique identifier and secret token that authenticates your application or user when making requests to Etherscan's various endpoints. This model is common for many web services that provide read-only or limited write access, allowing for easy integration while maintaining control over data access and usage limits. Each API key is associated with an Etherscan account, linking API usage to specific user profiles and their respective service tiers, such as the Etherscan API pricing summary.

The primary function of the API key is to verify that incoming requests originate from an authorized source. Without a valid API key, Etherscan API endpoints will return an authentication error, preventing unauthorized access to blockchain data. This method helps Etherscan manage resource allocation, enforce rate limits, and provide differentiated service levels based on user subscriptions. It is crucial to treat API keys as sensitive credentials, similar to passwords, to prevent misuse and unauthorized data retrieval.

Supported authentication methods

The Etherscan API exclusively supports API key authentication. This method involves generating a unique alphanumeric string from your Etherscan account dashboard and including it as a query parameter in every API request. The simplicity of API key authentication makes it accessible for developers across various programming languages and environments, aligning with the API's goal of providing direct access to Ethereum blockchain data.

While other authentication schemes like OAuth 2.0 authorization or mutual TLS might offer more complex security features, API key authentication is deemed sufficient for the read-only and public data access provided by Etherscan. It balances ease of implementation with necessary security for controlling access to public blockchain information and managing usage quotas. Developers are responsible for securely storing and transmitting these keys to prevent unauthorized access to their Etherscan API credits and data.

Authentication Method Details

Method When to Use Security Level
API Key (Query Parameter) All Etherscan API requests Moderate (requires secure key management)

Getting your credentials

To obtain your Etherscan API key, follow these steps:

  1. Create an Etherscan Account: If you do not already have one, register for a free account on the Etherscan homepage. A valid email address and password are required for registration.
  2. Log In: Access your Etherscan account using your registered credentials.
  3. Navigate to API Keys: Once logged in, locate the 'API Keys' section, typically found within your user profile or dashboard settings. This section is specifically designed for managing your API access.
  4. Generate New API Key: Click on the button or link to create a new API key. Etherscan may prompt you to provide a name for your key, which helps in identifying its purpose if you manage multiple keys. For instance, you might name a key 'MyDappFrontend' or 'BackendService'.
  5. Copy Your API Key: After generation, your unique API key (an alphanumeric string) will be displayed. It is critical to copy this key immediately and store it securely, as it may not be fully retrievable again for security reasons. If lost, you would typically need to generate a new key and revoke the old one.
  6. Understand Rate Limits: Be aware that your API key is subject to rate limits, which vary based on your Etherscan plan. The Etherscan API documentation outlines the specific credit limits for free and paid tiers, starting with 100,000 credits/day for the free tier. Exceeding these limits will result in temporary blocking of your API key until the next reset period.

Each API key is tied to your account's usage limits. For enhanced security and better management, Etherscan permits the generation of multiple API keys. This allows you to create separate keys for different applications or environments (e.g., development, staging, production), making it easier to track usage and revoke specific keys if compromised without affecting others. Regularly reviewing and rotating your API keys is a recommended security practice.

Authenticated request example

Once you have your Etherscan API key, you can include it in your requests. The API key is typically passed as a query parameter named apikey. Below are examples demonstrating how to make an authenticated request using cURL and Python, fetching the Ether balance for a specific address. The Etherscan Accounts API endpoint documentation provides further details on available parameters.

cURL Example

This cURL command retrieves the Ether balance for a given address. Replace YOUR_API_KEY with your actual Etherscan API key and 0x... with the target Ethereum address.

curl "https://api.etherscan.io/api?module=account&action=balance&address=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae&tag=latest&apikey=YOUR_API_KEY"

Python Example

This Python example uses the requests library to perform the same query. Ensure you replace the placeholder values with your specific API key and address.

import requests

API_KEY = "YOUR_API_KEY"
ETH_ADDRESS = "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae"

url = f"https://api.etherscan.io/api"

params = {
    "module": "account",
    "action": "balance",
    "address": ETH_ADDRESS,
    "tag": "latest",
    "apikey": API_KEY
}

response = requests.get(url, params=params)
data = response.json()

if data["status"] == "1":
    balance_wei = int(data["result"])
    balance_eth = balance_wei / (10**18)
    print(f"Ether Balance for {ETH_ADDRESS}: {balance_eth} ETH")
else:
    print(f"Error: {data['message']}")

These examples illustrate the standard practice of including the apikey query parameter in your requests. It's important to always use HTTPS for all API calls to ensure the API key and other data are encrypted during transit, protecting them from interception.

Security best practices

Securing your Etherscan API keys is essential to prevent unauthorized access, protect your account's credit limits, and maintain the integrity of your application. Adhering to established security practices helps mitigate risks associated with API key exposure.

  1. Do Not Embed Keys Directly in Client-Side Code: Never hardcode API keys directly into public client-side JavaScript, mobile applications, or any code that will be distributed to end-users. Such keys can be easily extracted and misused. Instead, use a backend server to make API calls, passing the key securely from the server.
  2. Use Environment Variables for Server-Side Applications: When deploying server-side applications, store API keys in environment variables rather than directly in your codebase. This prevents the key from being committed to version control systems like Git and makes it easier to manage keys across different deployment environments. For example, in a Linux environment, you might use export ETHERSCAN_API_KEY="YOUR_API_KEY".
  3. Restrict API Key Usage: While Etherscan API keys do not have built-in IP address or domain restrictions, exercising caution with their distribution is still paramount. If your infrastructure allows, consider implementing your own access control layer to limit which IP addresses or services can use your Etherscan API key.
  4. Regularly Rotate API Keys: Periodically generate new API keys and revoke old ones. This practice, known as key rotation, reduces the window of opportunity for a compromised key to be exploited. A common rotation schedule might be every 90 days, though this can vary based on your security policies.
  5. Monitor API Key Usage: Keep an eye on your Etherscan account dashboard for unusual activity or unexpected spikes in API usage. Early detection of suspicious patterns can help you identify and respond to potential compromises quickly.
  6. Implement HTTPS/TLS: Always ensure that all your API requests to Etherscan are made over HTTPS. This encrypts the communication channel between your application and the Etherscan servers, protecting your API key and other sensitive data from eavesdropping during transit. The Transport Layer Security (TLS) protocol is fundamental for secure internet communications.
  7. Error Handling and Logging: Implement robust error handling in your application to gracefully manage API errors, including authentication failures. Log API request and response details (excluding the API key itself) to assist with debugging and monitoring, but ensure logs are secured and do not expose sensitive information.
  8. Revoke Compromised Keys Immediately: If you suspect an API key has been compromised, revoke it immediately from your Etherscan account dashboard and generate a new one. Update all applications using that key with the new credential.

By following these best practices, developers can significantly enhance the security posture of their applications interacting with the Etherscan API, safeguarding both their data access and their Etherscan account credits.