DEV Community

Cover image for How to use CoinAPI to access crypto exchange rates using Python, Javascript and Java.
Ada from CoinAPI for CoinAPI

Posted on

How to use CoinAPI to access crypto exchange rates using Python, Javascript and Java.

CoinAPI provides a powerful interface for interacting with multiple cryptocurrency markets, allowing for efficient data retrieval and processing.

This tutorial walks you through the process of using CoinAPI's API to access exchange rates data using Python, Javascript and Java.The objective here is to equip you with the necessary know-how to utilize our API for your crypto projects.

Prerequisites

  • A CoinAPI key (obtainable by signing up on the CoinAPI website)
  • Familiarity with RESTful APIs and JSON (JavaScript Object Notation)
  • A basic understanding of at least one programming language: Python, Javascript or Java

API Key Generation

Before we dive into code, it's crucial to understand that to use the CoinAPI, you need an API key. This key identifies your application and authorizes requests.

  • Visit the CoinAPI website.
  • Register an account or login if you already have one.
  • Navigate to the API Keys section and generate a new API key.

Remember to store your key safely - it's your credential!

Making an API Request with Python

To connect to CoinAPI in Python, we'll use the requests library. If you don't have the 'requests' library installed, you can add it using pip:

pip install requests

Here's an example of access-coinapi-data.py python script:

import requests

def fetch_data():
    url = "https://rest.coinapi.io/v1/exchangerate/BTC/USD"
    headers = {
        "X-CoinAPI-Key": "YOUR-API-KEY" # Replace with your API key
    }
    response = requests.get(url, headers=headers)
    return response.json()

print(fetch_data())
Enter fullscreen mode Exit fullscreen mode

This script fetches the current exchange rate of Bitcoin (BTC) to USD.
To execute script, run python access-coinapi-data.py command.

python access-coinapi-data.py
{
    "time": "2023-07-24T11:31:56.0000000Z",
    "asset_id_base": "BTC",
    "asset_id_quote": "USD",
    "rate": 29295.929694597355
}
Enter fullscreen mode Exit fullscreen mode

Note: Don't forget to replace YOUR-API-KEY with your actual API key.

Making an API Request with Javascript

Makes sure to install nodejs runtime environment before.
Add package.json with node-fetch module dependency.

{
  "type": "module",
  "dependencies": {
    "node-fetch": "^3.3.1"
  }
}
Enter fullscreen mode Exit fullscreen mode

Create file access-coinapi-data.js with following code:

import fetch from 'node-fetch';

fetch('https://rest.coinapi.io/v1/exchangerate/BTC/USD', {
  headers: {
    "X-CoinAPI-Key": "YOUR_API_KEY" // Replace with your API key
    }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

This example fetches the current exchange rate from BTC to USD.

Install dependencies via npm install command.
Execute your program in nodejs runtime environment with node access-coinapi-data.js command.

>node access-coinapi-data.js
{
    "time": "2023-07-24T11:31:56.0000000Z",
    "asset_id_base": "BTC",
    "asset_id_quote": "USD",
    "rate": 29295.929694597355
}
Enter fullscreen mode Exit fullscreen mode

Note: Don't forget to replace YOUR-API-KEY with your actual API key.

Making an API Request with Java

Make sure to install Java Development Kit (JDK) as it includes runtime environment (JRE) plus additional tools and utilities required for Java development. To check whether JRE and JDK are already installed on your system you may use java -version command.

Java offers multiple ways to send HTTP requests. Here we'll use the HttpURLConnection class.
Create Main.java file with following content:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    private static final String API_KEY = "YOUR-API-KEY"; // Replace with your API key

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://rest.coinapi.io/v1/exchangerate/BTC/USD");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("X-CoinAPI-Key", API_KEY);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }

        in.close();
        conn.disconnect();

        System.out.println(content.toString());
    }
}
Enter fullscreen mode Exit fullscreen mode

This script fetches the current exchange rate of Bitcoin (BTC) to USD.

Use javac Main.java command to compile java source file into bytecode.
Resulting bytecode file will be named Main.class.
After the compilation step, you can execute the program using java Main to see the exchange rate output.

>javac Main.Java
>java Main
{
    "time": "2023-07-24T11:31:56.0000000Z",
    "asset_id_base": "BTC",
    "asset_id_quote": "USD",
    "rate": 29295.929694597355
}
Enter fullscreen mode Exit fullscreen mode

Note: Don't forget to replace YOUR-API-KEY with your actual API key.

Understanding the Response

CoinAPI returns data in JSON format, which we convert to a Python dictionary using response.json(). The /v1/exchangerate/BTC/USD endpoint response includes:

time: The timestamp of the last data update.

asset_id_base: The base asset (in our case, BTC).

asset_id_quote: The quote asset (in our case, USD).

rate: The current exchange rate from BTC to USD.

Converting Between Cryptocurrencies

The /v1/exchangerate/BTC/USD endpoint retrieves the current exchange rate of BTC to USD.

Additionally, the Exchange Rates endpoint provides the flexibility to obtain exchange rates between BTC and various other assets,
allowing users to access the conversion rates for multiple asset pairs involving BTC.

import requests 

url = 'https://rest.coinapi.io/v1/exchangerate/BTC' 
headers = {'X-CoinAPI-Key' : 'YOUR_API_KEY'} 
response = requests.get(url, headers=headers) 
print(response.json())
Enter fullscreen mode Exit fullscreen mode

Here's the response for BTC exchange rate to various assets, e.g EUR, USD, ETH, XRP:

{
    "asset_id_base": "BTC",
    "rates": [
        {
            "time": "2023-07-24T13:00:43.0000000Z",
            "asset_id_quote": "EUR",
            "rate": 26371.195622912368
        },
        {
            "time": "2023-07-24T13:00:43.0000000Z",
            "asset_id_quote": "USD",
            "rate": 29222.332203558577
        },
        {
            "time": "2023-07-24T13:00:43.0000000Z",
            "asset_id_quote": "ETH",
            "rate": 15.780394091251145
        },
        {
            "time": "2023-07-24T13:00:43.0000000Z",
            "asset_id_quote": "XRP",
            "rate": 41915.164263881525
        },
        // ...more BTC exchange rates with various other assets...
}
Enter fullscreen mode Exit fullscreen mode

To perform a cryptocurrency conversion from one currency to another, simply multiply the given amount by the exchange rate of the target cryptocurrency. Here's an example of converting 1.5 BTC to ETH:

import requests 
url = 'https://rest.coinapi.io/v1/exchangerate/BTC' 
headers = {'X-CoinAPI-Key' : "YOUR_API_KEY"}
response = requests.get(url, headers=headers) 

rates = response.json()['rates'] # exchange rates with BTC as base asset
eth_rate = [x['rate'] for x in rates if x['asset_id_quote'] == 'ETH'][0] # finding exchange rate for ETH (quote asset)
btc_amount = 1.5

eth_amount = btc_amount * eth_rate # actual conversion
print(f'1.5 BTC is equivalent to {eth_amount} ETH')
Enter fullscreen mode Exit fullscreen mode

Below is the result of 1.5 BTC to ETH conversion:

console>python convert.py
1.5 BTC is equivalent to 23.671802476675076 ETH
Enter fullscreen mode Exit fullscreen mode

Exchange rates endpoint plays a critical role in providing real-time conversion rates for cryptocurrencies.

The rate represents the conversion factor that determines the value of one unit of the base currency in terms of the target currency. It indicates how much of the target currency you would get in exchange for one unit of the base currency.

For more information, you can check REST API Exchange Rates docs

Best Practices

  • Security: never expose your API key publicly or commit it to version control. Store it in a secure and encrypted location and treat your API key as password.
  • Error Handling: CoinAPI can return various error codes (like 400, 403, 429) indicating issues such as invalid input or rate limit exceeding. Make sure to handle these potential errors in your code.
  • Rate Limiting: Ensure your application gracefully handles rate limit errors by implementing retry logic. Refer to CoinAPI's Rate Limiting documentation for more details.

Error Handling

Include robust error handling to account for potential issues such as network errors, API limits, or invalid responses.
Here's a simple example:

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # Raises a HTTPError if the status is 4xx, 5xx
except requests.exceptions.RequestException as err:
    print(f"An Error Occured: {err}")
else:
    data = response.json()
Enter fullscreen mode Exit fullscreen mode

Rate Limiting

Keep track of your API usage to avoid hitting rate limits. CoinAPI provides different request tiers based on your subscription level.

print(response.headers.get("X-RateLimit-Used"))
print(response.headers.get("X-RateLimit-Limit"))
print(response.headers.get("X-RateLimit-Remaining"))
print(response.headers.get("X-RateLimit-Request-Cost"))
print(response.headers.get("X-RateLimit-Reset"))
Enter fullscreen mode Exit fullscreen mode

For more information about rate limiting check REST API Limits.

API Key Security

Never expose your API key in a client-side application or a public code repository. Always keep it securely on your server.

Once your API key falls into the wrong hands, it can be used to make requests within your subscription.

Caching

To minimize API calls and maximize efficiency, consider implementing caching on your end.

Troubleshooting

If you encounter any issues while connecting to CoinAPI, make sure to:

Verify that your API key is correct.

  • Check if you have reached the API rate limit.
  • Confirm that you're using the right endpoint and method (GET, POST, etc.).
  • Ensure you've installed the correct libraries and dependencies and are using a supported version of the programming language.

You're now ready to use CoinAPI's API to access cryptocurrency data efficiently and effectively.
For more information, you can check REST API Exchange Rates docs

Happy coding!

Top comments (0)