Authentication overview

CoinAPI secures access to its cryptocurrency market data services primarily through API key authentication. This method verifies the identity of the client application making requests to the API, allowing CoinAPI to manage access permissions and enforce usage limits associated with different subscription tiers. All communications with CoinAPI's endpoints are expected to be encrypted using Transport Layer Security (TLS) to protect the API key and data in transit, aligning with industry standards for secure API interactions.

An API key functions as a unique identifier and secret token provided by CoinAPI to its users. When an application sends a request to a CoinAPI endpoint, this key is included in the request headers. CoinAPI's servers then validate the key against their records to confirm the client's authenticity and authorization for the requested data. This mechanism applies across CoinAPI's REST, WebSocket, and FIX APIs, ensuring consistent security protocols regardless of the data access method.

The use of API keys is a common practice for authenticating access to web services, offering a balance between security and ease of implementation for developers. While simpler than more complex token-based authentication flows like OAuth 2.0, API keys require careful management to prevent unauthorized access. Best practices, such as storing keys securely and rotating them periodically, are essential for maintaining the integrity of an application's data access.

Supported authentication methods

CoinAPI primarily supports API key authentication. This method involves generating a unique API key from the CoinAPI dashboard and including it in the HTTP headers of every request. The API key serves as both an identifier and a secret, granting access to the data and services permitted by the user's subscription plan.

For REST API requests, the API key is typically passed in the X-CoinAPI-Key HTTP header. For WebSocket connections, the API key is often provided as a query parameter during the initial connection handshake or within a specific message after establishing the connection, depending on the client library or implementation. The FIX API, designed for institutional trading, also incorporates API key-like credentials as part of its session initiation process, adhering to its specific protocol standards.

The following table summarizes the primary authentication method:

Method When to Use Security Level
API Key (Header) All REST API requests, WebSocket connections, FIX API sessions. Ideal for server-to-server communication and client applications with secure key storage. Moderate to High (when combined with HTTPS/TLS and proper key management).

Getting your credentials

To obtain your CoinAPI credentials, you need to register for an account and generate an API key through the CoinAPI user dashboard. The process generally involves these steps:

  1. Sign Up/Log In: Navigate to the CoinAPI website and either create a new account or log in to an existing one.
  2. Access Dashboard: After logging in, you will typically be directed to your user dashboard or a similar portal.
  3. Navigate to API Keys Section: Look for a section labeled "API Keys," "My API Key," or "Developers." The exact naming may vary, but it will be dedicated to managing your access credentials.
  4. Generate New API Key: Within this section, there should be an option to generate a new API key. Some platforms allow you to name your keys for easier management, especially if you plan to use multiple keys for different applications.
  5. Copy Your API Key: Once generated, your API key will be displayed. It is crucial to copy this key immediately and store it securely, as it may only be shown once for security reasons. If you lose it, you might need to generate a new one and revoke the old one.
  6. Review Permissions: Depending on your subscription plan (e.g., Starter, Hobbyist, Professional), your API key will have specific permissions and rate limits. Ensure your plan meets your application's requirements.

CoinAPI's documentation provides specific instructions and visual guides for generating and managing API keys within their dashboard. Referencing the official CoinAPI documentation for the most up-to-date credential acquisition process is recommended.

Authenticated request example

Once you have obtained your API key, you can use it to make authenticated requests to CoinAPI's endpoints. For REST API calls, the API key is typically included in the HTTP request header. Below is an example using curl, a common command-line tool for making HTTP requests, and a Python example using the requests library.

Curl Example (REST API)

This example demonstrates fetching exchange rates for Bitcoin (BTC) to US Dollar (USD) using the /v1/exchangerate/{asset_id_base}/{asset_id_quote} endpoint.

curl --request GET \
  --url 'https://rest.coinapi.io/v1/exchangerate/BTC/USD' \
  --header 'X-CoinAPI-Key: YOUR_API_KEY'

Replace YOUR_API_KEY with your actual CoinAPI key.

Python Example (REST API)

This Python snippet performs the same exchange rate query using the popular requests library.

import requests

api_key = "YOUR_API_KEY"
url = "https://rest.coinapi.io/v1/exchangerate/BTC/USD"

headers = {
    "X-CoinAPI-Key": api_key
}

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # Raise an HTTPError for bad responses (4xx or 5xx)
    data = response.json()
    print(data)
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}")

Remember to replace "YOUR_API_KEY" with your actual API key.

WebSocket Example (Python)

For WebSocket connections, the API key is typically sent during the initial connection or as part of a subscription message. Here's a conceptual Python example using websocket-client, demonstrating how to include the API key in the initial connection parameters or a subsequent message if required by the protocol.

import websocket
import json

api_key = "YOUR_API_KEY"
websocket_url = f"wss://ws.coinapi.io/v1/"

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print(f"### closed ### {close_status_code} {close_msg}")

def on_open(ws):
    print("Opened connection")
    # Send API key and subscription request after connection is open
    subscribe_message = {
        "type": "hello",
        "apikey": api_key,
        "heartbeat": False,
        "subscribe_data_type": ["exrate"],
        "subscribe_filter_asset_id": ["BTC", "USD"]
    }
    ws.send(json.dumps(subscribe_message))

if __name__ == "__main__":
    # websocket.enableTrace(True)
    ws = websocket.WebSocketApp(websocket_url,
                                on_open=on_message,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

This example illustrates how the API key is passed within a hello message after the WebSocket connection is established, as specified by the CoinAPI WebSocket API documentation. Always consult the specific API documentation for the correct method of passing credentials for WebSocket connections.

Security best practices

Securing your API keys is crucial to prevent unauthorized access to your CoinAPI account and data. Adhering to these best practices can help mitigate security risks:

  • Keep API Keys Confidential: Treat your API key like a password. Never embed it directly in client-side code (e.g., JavaScript in a web browser) where it can be exposed. Store it in environment variables, secret management services, or secure configuration files on your server.
  • Use Environment Variables: For server-side applications, storing API keys as environment variables prevents them from being committed to source control and makes it easier to manage different keys across development, staging, and production environments.
  • Avoid Hardcoding: Do not hardcode API keys directly into your application's source code. This practice makes key rotation difficult and increases the risk of exposure if your code repository is compromised.
  • Restrict IP Addresses (if available): If CoinAPI offers functionality to restrict API key usage to specific IP addresses or CIDR blocks, configure this feature. This adds an extra layer of security, ensuring that even if a key is stolen, it can only be used from authorized locations.
  • Regularly Rotate API Keys: Periodically generate new API keys and revoke old ones. This practice limits the window of opportunity for a compromised key to be exploited. The frequency of rotation depends on your security policy and risk assessment.
  • Implement Least Privilege: If CoinAPI supports granular permissions for API keys, assign only the minimum necessary permissions required for a specific application or service. This limits the impact of a compromised key.
  • Monitor API Usage: Regularly review your API usage logs for any unusual activity. Spikes in requests or access from unexpected locations could indicate a compromised key.
  • Use HTTPS/TLS: Always ensure that your API requests are made over HTTPS (TLS). This encrypts the communication between your application and CoinAPI's servers, protecting your API key and data from interception during transit. The Transport Layer Security (TLS) protocol is essential for secure internet communication.
  • Error Handling: Implement robust error handling in your application to gracefully manage authentication failures. Avoid logging API keys in error messages or application logs.
  • Secure Development Practices: Follow general secure coding practices, such as input validation and protection against common web vulnerabilities, to safeguard your application and its secrets.