Getting started overview

This guide provides a focused walkthrough for developers to initiate API access with Twelve Data. It covers the necessary steps to set up an account, obtain credentials, and execute a foundational API request. Twelve Data offers access to various financial market data, including real-time and historical data for stocks, forex, and cryptocurrency markets, designed for integration into applications requiring financial insights. The process involves account registration, API key retrieval, and constructing a request to one of the available endpoints.

The following table outlines the key steps to get started:

Step What to do Where
1. Account Creation Sign up for a free Twelve Data account. Twelve Data homepage
2. API Key Retrieval Locate your unique API key in your dashboard. Twelve Data API Key documentation
3. Make First Request Construct and execute an API call using your key. Twelve Data API reference
4. Explore SDKs Consider using a client library for your preferred language. Twelve Data SDKs documentation

Create an account and get keys

To begin using the Twelve Data API, an account is required to generate an API key. This key authenticates requests and manages access tiers, including the free tier which permits up to 250 requests per day. Higher request limits and extended features are available through Twelve Data's paid plans, starting at $29/month.

Account Registration

  1. Navigate to the official Twelve Data website.
  2. Click on the "Sign Up" or "Get Started Free" button.
  3. Complete the registration form by providing an email address and creating a password. Account verification may be required via email.

API Key Retrieval

Upon successful registration and login, your API key will be accessible through your Twelve Data user dashboard. This key is a unique alphanumeric string that must be included with every API request.

  1. Log in to your Twelve Data account dashboard.
  2. Locate the "API Key" section, typically found under "Settings" or "API Access".
  3. Copy your API key. It is recommended to store this key securely and avoid exposing it in client-side code or public repositories.

Your first request

After obtaining your API key, you can make your first API call. A common starting point is to retrieve real-time stock data for a specific symbol. This example uses the Python programming language with the requests library, though similar HTTP request paradigms apply across other supported languages and SDKs. The base URL for the API is https://api.twelvedata.com.

Example: Real-time Stock Price (Python)

This example demonstrates how to fetch the current price for Apple Inc. (AAPL).


import requests
import json

# Replace 'YOUR_API_KEY' with your actual Twelve Data API key
API_KEY = 'YOUR_API_KEY'
SYMBOL = 'AAPL'

def get_realtime_price(symbol, api_key):
    url = f"https://api.twelvedata.com/price?symbol={symbol}&apikey={api_key}"
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)
        data = response.json()
        if 'price' in data:
            return data['price']
        elif 'message' in data:
            print(f"API Error: {data['message']}")
            return None
        else:
            print(f"Unexpected API response: {data}")
            return None
    except requests.exceptions.HTTPError as errh:
        print(f"HTTP Error: {errh}")
    except requests.exceptions.ConnectionError as errc:
        print(f"Error Connecting: {errc}")
    except requests.exceptions.Timeout as errt:
        print(f"Timeout Error: {errt}")
    except requests.exceptions.RequestException as err:
        print(f"Something went wrong: {err}")
    return None

price = get_realtime_price(SYMBOL, API_KEY)

if price is not None:
    print(f"The current price of {SYMBOL} is: {price}")
else:
    print(f"Failed to retrieve price for {SYMBOL}.")

Explanation of the Python Example:

  • API_KEY: Your personal API key obtained from your Twelve Data dashboard. Replace the placeholder.
  • SYMBOL: The stock ticker symbol for which you want data (e.g., AAPL for Apple).
  • url: Constructs the API endpoint for fetching the current price, including the symbol and your API key as query parameters.
  • requests.get(url): Sends an HTTP GET request to the specified URL. The requests library simplifies HTTP interactions in Python, as detailed in the Requests library quickstart.
  • response.raise_for_status(): Checks if the request was successful. If not (e.g., 4xx or 5xx status codes), it raises an HTTPError.
  • response.json(): Parses the JSON response body into a Python dictionary.
  • Error Handling: Includes try-except blocks to catch common network and API-related errors, providing more informative feedback.

For JavaScript developers, an equivalent fetch request would look like this:


const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
const SYMBOL = 'GOOGL';

async function getRealtimePrice(symbol, apiKey) {
  const url = `https://api.twelvedata.com/price?symbol=${symbol}&apikey=${apiKey}`;
  try {
    const response = await fetch(url);
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message || 'Unknown error'}`);
    }
    const data = await response.json();
    if (data.price) {
      return data.price;
    } else if (data.message) {
      console.error(`API Error: ${data.message}`);
      return null;
    } else {
      console.error(`Unexpected API response:`, data);
      return null;
    }
  } catch (error) {
    console.error(`Failed to fetch price for ${symbol}:`, error);
    return null;
  }
}

getRealtimePrice(SYMBOL, API_KEY).then(price => {
  if (price !== null) {
    console.log(`The current price of ${SYMBOL} is: ${price}`);
  } else {
    console.log(`Failed to retrieve price for ${SYMBOL}.`);
  }
});

This JavaScript example uses the fetch API, a standard web API for making network requests, which is widely supported in modern browsers and Node.js environments. The MDN Web Docs on Fetch API provide further details on its usage.

Common next steps

After successfully making your first request, consider these common next steps to further integrate Twelve Data into your applications:

  • Explore Endpoints: Review the Twelve Data API reference to discover other available endpoints. These include historical data, technical indicators, fundamental data, and data for other asset classes like forex and cryptocurrencies.
  • Utilize SDKs: Twelve Data provides official client libraries (SDKs) for several languages, including Python, JavaScript, PHP, Ruby, Go, C#, and Java. Using an SDK can simplify API interactions by handling request construction, response parsing, and error management.
  • Implement Webhooks: For real-time event-driven applications, explore webhook functionality if supported by your plan. Webhooks allow the API to push data to your application when specific events occur, reducing the need for constant polling.
  • Manage Authentication: Ensure your API key is handled securely. For production environments, consider using environment variables or a secrets management service instead of hardcoding the key.
  • Monitor Usage: Keep track of your API usage through your Twelve Data dashboard to avoid hitting rate limits, especially on the free or lower-tier plans.
  • Error Handling and Retries: Implement robust error handling and retry mechanisms in your application to manage transient network issues or API rate limit responses gracefully.

Troubleshooting the first call

Encountering issues during the initial API call is common. Here are some troubleshooting steps:

  • Check API Key: Verify that your API key is correct and has been copied accurately from your Twelve Data dashboard. A common error is a mistyped or expired key.
  • Rate Limits: Even on the free tier, there are rate limits. If you make too many requests too quickly, you may receive a 429 Too Many Requests error. Wait a few moments before retrying.
  • Incorrect Endpoint or Parameters: Ensure the API endpoint URL and any query parameters (like symbol or interval) are correctly formatted according to the API reference documentation.
  • Network Connectivity: Confirm that your development environment has stable internet connectivity and that no firewall rules are blocking outgoing HTTP requests to api.twelvedata.com.
  • HTTP Status Codes: Pay attention to the HTTP status code returned in the API response. Common codes include:
    • 200 OK: Success.
    • 400 Bad Request: Often due to missing or invalid parameters.
    • 401 Unauthorized: Incorrect or missing API key.
    • 403 Forbidden: Your API key does not have access to the requested data. This might happen if you try to access premium features on a free plan.
    • 404 Not Found: The requested resource (e.g., an invalid symbol) does not exist.
    • 5xx Server Error: Indicates an issue on Twelve Data's side. If these persist, check the Twelve Data support channels.
  • Response Body: Always inspect the response body for error messages, which often provide specific details about what went wrong.
  • CORS Issues (Browser-based): If making requests from a web browser, Cross-Origin Resource Sharing (CORS) policies might block requests. Twelve Data's API supports CORS for browser-based applications, but ensure your request headers are correctly configured if you encounter related errors.