Authentication overview

Twelve Data's API authentication process focuses on using API keys to grant and manage access to its financial data services. An API key acts as a unique identifier and secret token that clients include with their API requests to prove their identity and authorize their access to specific data endpoints Twelve Data API documentation. This method is common for RESTful APIs, providing a straightforward way to control who can consume data.

When you sign up for a Twelve Data account, an API key is generated for you. This key is associated with your account's subscription plan, which dictates your request limits, available data endpoints, and other service parameters. Properly handling and securing your API key is crucial to prevent unauthorized access to your account and data, as well as to avoid exceeding your rate limits due to misuse.

Twelve Data enforces authentication for nearly all API requests, from fetching real-time stock prices to querying historical forex data. The authentication mechanism ensures that all interactions with the platform's resources are legitimate and conform to the user's entitlements. The platform supports various SDKs across multiple programming languages, simplifying the integration of API key-based authentication into diverse applications.

Supported authentication methods

Twelve Data primarily utilizes a single, consistent authentication method across its API endpoints: API Key authentication. This method involves passing a unique, secret key with each API request.

Here's a breakdown of the supported method:

Method When to Use Security Level Notes
API Key (Query Parameter) All API calls requiring authentication Moderate The key is passed directly in the URL query string. Requires HTTPS to protect the key in transit.

The API key is typically included as a query parameter named apikey in your API request URLs. For example, a request might look like https://api.twelvedata.com/time_series?symbol=AAPL&apikey=YOUR_API_KEY. While simple to implement, it is vital to ensure that all communications occur over HTTPS to encrypt the API key and prevent interception. The use of HTTPS is a fundamental security practice for any API interaction involving sensitive data or credentials Cloudflare's explanation of HTTPS.

Getting your credentials

To begin using Twelve Data's API, you will need to obtain an API key. This key serves as your primary credential for authenticating all your API requests. The process is straightforward and is managed through the Twelve Data developer dashboard.

  1. Sign Up or Log In: Visit the Twelve Data homepage and either create a new account or log in to your existing one. A new account typically starts with access to the free tier, which includes a limited number of requests per day.
  2. Access the Dashboard: Once logged in, navigate to your developer dashboard. This is usually accessible through a prominent link or menu item labeled "Dashboard" or "API Dashboard."
  3. Locate Your API Key: On the dashboard, your API key will be displayed prominently, often in a section dedicated to API access or credentials. It's a long alphanumeric string. You may have the option to generate new keys or revoke existing ones for security purposes.
  4. Copy Your API Key: Copy the displayed API key carefully. You will need to include this exact string in every API request you make to Twelve Data. Store this key securely, as it grants access to your account's API usage.

It is generally recommended to generate a new API key if you suspect your current key has been compromised or if you are rotating keys as part of your security policy. The dashboard provides controls for key management, allowing you to maintain better oversight of your API access.

Authenticated request example

This example demonstrates how to make an authenticated request to the Twelve Data API using Python, one of the primary languages mentioned in the entity payload. The example retrieves a basic time series for a given stock symbol.

First, ensure you have your API key. For security, it's best to store it as an environment variable rather than hardcoding it directly into your script.

Python Example (using requests library)


import os
import requests

# Securely retrieve your API key from environment variables
API_KEY = os.getenv("TWELVEDATA_API_KEY")

if not API_KEY:
    raise ValueError("TWELVEDATA_API_KEY environment variable not set.")

BASE_URL = "https://api.twelvedata.com"
ENDPOINT = "time_series"
SYMBOL = "AAPL"
INTERVAL = "1min"

params = {
    "symbol": SYMBOL,
    "interval": INTERVAL,
    "apikey": API_KEY  # Your API key is included here
}

full_url = f"{BASE_URL}/{ENDPOINT}"

try:
    response = requests.get(full_url, params=params)
    response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)
    data = response.json()

    if data and 'values' in data:
        print(f"Latest {SYMBOL} data ({INTERVAL}):")
        for entry in data['values'][:5]: # Print first 5 entries
            print(f"  Datetime: {entry['datetime']}, Open: {entry['open']}, High: {entry['high']}, Low: {entry['low']}, Close: {entry['close']}, Volume: {entry['volume']}")
    elif data and 'status' in data and data['status'] == 'error':
        print(f"API Error: {data.get('message', 'Unknown error')}")
    else:
        print("No data or unexpected response format.")

except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
    if response.status_code == 401: # Unauthorized
        print("Check your API key. It might be invalid or expired.")
    elif response.status_code == 429: # Too Many Requests
        print("You have exceeded your rate limit. Wait before making more requests.")
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}")
except ValueError as ve:
    print(f"Configuration error: {ve}")

To run this example:

  1. Install the requests library: pip install requests
  2. Set your environment variable: export TWELVEDATA_API_KEY="YOUR_ACTUAL_API_KEY" (on Linux/macOS) or $env:TWELVEDATA_API_KEY="YOUR_ACTUAL_API_KEY" (on PowerShell). Replace YOUR_ACTUAL_API_KEY with the key obtained from your Twelve Data dashboard.
  3. Save the code as a .py file (e.g., twelve_data_auth.py) and run it: python twelve_data_auth.py

Security best practices

Protecting your API key is paramount to maintaining the security and integrity of your applications and data when interacting with Twelve Data. Adhering to these best practices will help mitigate common security risks:

  • Never Hardcode API Keys: Avoid embedding your API key directly in your source code. Hardcoded keys can be exposed if your code repository is compromised or accidentally made public. Instead, use environment variables, configuration files, or a secure secrets management service AWS Secrets Manager documentation.
  • Use Environment Variables: For server-side applications, storing API keys as environment variables (e.g., TWELVEDATA_API_KEY) is a widely accepted practice. This keeps keys out of your codebase and allows for easy rotation without code changes.
  • Restrict Access to Keys: Limit who has access to your API keys. Only authorized personnel or automated systems should be able to retrieve and use them.
  • Always Use HTTPS: Ensure all your API requests to Twelve Data are made over HTTPS. This encrypts the communication channel, protecting your API key and data in transit from eavesdropping and man-in-the-middle attacks. Twelve Data's API primarily supports HTTPS, but it's crucial that your client-side implementation also enforces it.
  • Implement Rate Limit Handling: While not directly an authentication security measure, robust rate limit handling helps prevent denial-of-service attacks against your application that might occur if your API key is misused or if your application makes excessive requests. Gracefully handle 429 Too Many Requests responses.
  • Monitor API Usage: Regularly check your Twelve Data dashboard for API usage statistics. Unexpected spikes in usage could indicate a compromised key or an issue with your application's logic.
  • Key Rotation: Periodically rotate your API keys. Define a schedule (e.g., every 90 days) to generate a new key and revoke the old one. This minimizes the window of exposure if a key is ever compromised.
  • Client-Side/Public Applications: For client-side applications (e.g., web browsers, mobile apps), directly exposing your API key is highly discouraged. If your application needs to access Twelve Data from a client, consider routing requests through a secure backend server that holds the API key, acting as a proxy. This server can then enforce additional access controls and rate limiting.
  • Error Handling: Implement comprehensive error handling for API responses, especially for authentication-related errors (e.g., HTTP 401 Unauthorized). This allows your application to respond gracefully and alert administrators to potential security issues.