API Integrations

Go
package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
    "log"
)

func convertCurrency(from string, to string, amount float64, date string) {
    client := &http.Client{}
    url := fmt.Sprintf("https://api.plutusfx.io/api/v1/convert/%s_%s?amount=%.2f", from, to, amount)

    if date != "" {
        url = fmt.Sprintf("%s&date=%s", url, date)
    }

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Fatal(err)
    }

    req.Header.Add("X-Api-Key", "your_api_key_here")

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(body))
}

func main() {
    convertCurrency("USD", "EUR", 100, "2023-07-01")
}
PHP
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

function convertCurrency($from, $to, $amount, $date = null) {
    $client = new Client();

    // Define the base URL for the API
    $baseUrl = sprintf('https://api.plutusfx.io/api/v1/convert/%s_%s', $from, $to);

    // Prepare query parameters
    $queryParams = [
        'amount' => $amount,
    ];

    // If a date is provided, add it to the query parameters
    if ($date) {
        $queryParams['date'] = $date;
    }

    try {
        // Send GET request
        $response = $client->request('GET', $baseUrl, [
            'query' => $queryParams,
            'headers' => [
                'X-Api-Key' => 'your_api_key_here'
            ]
        ]);

        // Get the response body
        $body = $response->getBody();
        $data = json_decode($body, true);

        // Handle the response data
        return $data;
    } catch (Exception $e) {
        // Handle the exception
        echo 'Request failed: ' . $e->getMessage();
    }
}

// Example usage
$fromCurrency = 'USD';
$toCurrency = 'EUR';
$amount = 100;
$date = '2023-07-01'; // Optional, can be null

$result = convertCurrency($fromCurrency, $toCurrency, $amount, $date);
print_r($result);
Node.js
const axios = require('axios');

async function convertCurrency(from, to, amount, date) {
    let url = `https://api.plutusfx.io/api/v1/convert/${from}_${to}?amount=${amount}`;

    if (date) {
        url += `&date=${date}`;
    }

    try {
        const response = await axios.get(url, {
            headers: {
                'X-Api-Key': 'your_api_key_here'
            }
        });
        console.log(response.data);
    } catch (error) {
        console.error(`Request failed: ${error}`);
    }
}

// Example usage
convertCurrency('USD', 'EUR', 100, '2023-07-01');
Python
import requests

def convert_currency(from_currency, to_currency, amount, date=None):
    url = 'https://api.plutusfx.io/api/v1/convert/{}_{}'.format(from_currency, to_currency)
    params = {
        'amount': amount
    }
    if date:
        params['date'] = date

    headers = {
        'X-Api-Key': 'your_api_key_here'
    }

    response = requests.get(url, params=params, headers=headers)

    if response.status_code == 200:
        return response.json()
    else:
        return {'error': 'Request failed', 'status_code': response.status_code}

# Example usage
result = convert_currency('USD', 'EUR', 100, '2023-07-01')
print(result)
Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CurrencyConverter {
    private static final String API_KEY = "your_api_key_here";

    public static void main(String[] args) {
        try {
            convertCurrency("USD", "EUR", 100, "2023-07-01");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void convertCurrency(String from, String to, double amount, String date) throws Exception {
        String urlString = String.format("https://api.plutusfx.io/api/v1/convert/%s_%s?amount=%.2f", from, to, amount);
        if (date != null && !date.isEmpty()) {
            urlString += "&date=" + date;
        }

        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("X-Api-Key", API_KEY);

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println(response.toString());
        } else {
            System.out.println("GET request failed. Response Code: " + responseCode);
        }
    }
}
Kotlin
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.features.logging.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    convertCurrency("USD", "EUR", 100.0, "2023-07-01")
}

suspend fun convertCurrency(from: String, to: String, amount: Double, date: String?) {
    val client = HttpClient {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
        install(Logging) {
            level = LogLevel.INFO
        }
    }

    var url = "https://api.plutusfx.io/api/v1/convert/$from_$to?amount=$amount"
    if (date != null) {
        url += "&date=$date"
    }

    try {
        val response: HttpResponse = client.get(url) {
            header("X-Api-Key", "your_api_key_here")
        }
        val body = response.readText()
        println(body)
    } catch (e: Exception) {
        println("Request failed: ${e.message}")
    } finally {
        client.close()
    }
}
Rust
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }

use reqwest::Error;

#[tokio::main]
async fn main() -> Result<(), Error> {
    convert_currency("USD", "EUR", 100.0, Some("2023-07-01")).await?;
    Ok(())
}

async fn convert_currency(from: &str, to: &str, amount: f64, date: Option<&str>) -> Result<(), Error> {
    let client = reqwest::Client::new();
    let mut url = format!("https://api.plutusfx.io/api/v1/convert/{}_{}?amount={}", from, to, amount);

    if let Some(d) = date {
        url = format!("{}&date={}", url, d);
    }

    let response = client
        .get(&url)
        .header("X-Api-Key", "your_api_key_here")
        .send()
        .await?;

    let body = response.text().await?;
    println!("{}", body);

    Ok(())
}
C#
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        await ConvertCurrency("USD", "EUR", 100, "2023-07-01");
    }

    public static async Task ConvertCurrency(string from, string to, double amount, string date = null)
    {
        var url = $"https://api.plutusfx.io/api/v1/convert/{from}_{to}?amount={amount}";
        if (!string.IsNullOrEmpty(date))
        {
            url += $"&date={date}";
        }

        client.DefaultRequestHeaders.Add("X-Api-Key", "your_api_key_here");

        HttpResponseMessage response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();

        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}