Skip to content
RateFlowAPI

Reference

Code Examples

On this page

Each example below is a complete program in cURL, PHP, JavaScript, Python, Rust, Go and C#. Pick a language in the tabs above any example. Every example on the page then switches to that language, and the docs remember your choice for your next visit.

Before You Start

The examples read your API key from the RATEFLOW_API_KEY environment variable, so the key never sits in your code:

Shell
export RATEFLOW_API_KEY="your-api-key"

Successful responses use the { "success": true, "data": { ... } } envelope, so the values live under data. Errors use { "success": false, "error": { ... } }. Every example checks the HTTP status and, for an error, prints the HTTP status, the error code and its detail (see Errors).

What each language needs:

  • cURL: version 7.76 or newer, for --fail-with-body.
  • JavaScript: Node.js 18 or newer. Save the code as an .mjs file, because it uses await at the top level.
  • Python: the requests package (pip install requests).
  • Rust: these dependencies in Cargo.toml:
TOML
[dependencies]
reqwest = { version = "0.12", features = ["blocking", "json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Latest Rates

Fetch the newest EUR rates and print the rate for USD.

cURL
curl -sS --fail-with-body \
  -H "X-API-Key: $RATEFLOW_API_KEY" \
  "https://api.rateflowapi.com/v1/rates/latest?base=EUR"
PHP
<?php

$ch = curl_init('https://api.rateflowapi.com/v1/rates/latest?base=EUR');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('RATEFLOW_API_KEY')],
]);
$body = json_decode((string) curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

if ($status !== 200) {
    fwrite(STDERR, "{$status} {$body['error']['code']}: {$body['error']['detail']}" . PHP_EOL);
    exit(1);
}

echo "EUR to USD on {$body['data']['date']}: {$body['data']['rates']['USD']}" . PHP_EOL;
JavaScript
const response = await fetch('https://api.rateflowapi.com/v1/rates/latest?base=EUR', {
    headers: { 'X-API-Key': process.env.RATEFLOW_API_KEY },
});
const body = await response.json();

if (!response.ok) {
    throw new Error(`${response.status} ${body.error.code}: ${body.error.detail}`);
}

console.log(`EUR to USD on ${body.data.date}: ${body.data.rates.USD}`);
Python
import os

import requests

response = requests.get(
    "https://api.rateflowapi.com/v1/rates/latest",
    params={"base": "EUR"},
    headers={"X-API-Key": os.environ["RATEFLOW_API_KEY"]},
    timeout=10,
)
body = response.json()

if not response.ok:
    raise SystemExit(f"{response.status_code} {body['error']['code']}: {body['error']['detail']}")

print(f"EUR to USD on {body['data']['date']}: {body['data']['rates']['USD']}")
Rust
use serde::{de::DeserializeOwned, Deserialize};
use std::{collections::BTreeMap, env, error::Error};

#[derive(Deserialize)]
struct Success<T> {
    data: T,
}

#[derive(Deserialize)]
struct Failure {
    error: ApiError,
}

#[derive(Deserialize)]
struct ApiError {
    code: String,
    detail: String,
}

#[derive(Deserialize)]
struct Latest {
    date: String,
    rates: BTreeMap<String, f64>,
}

fn get<T: DeserializeOwned>(path: &str) -> Result<T, Box<dyn Error>> {
    let response = reqwest::blocking::Client::new()
        .get(format!("https://api.rateflowapi.com/v1{path}"))
        .header("X-API-Key", env::var("RATEFLOW_API_KEY")?)
        .send()?;

    let status = response.status();
    if status.is_success() {
        return Ok(response.json::<Success<T>>()?.data);
    }

    let body = response.text()?;
    let message = match serde_json::from_str::<Failure>(&body) {
        Ok(failure) => format!("{} {}: {}", status.as_u16(), failure.error.code, failure.error.detail),
        Err(_) => format!("HTTP {status}"),
    };
    Err(message.into())
}

fn main() -> Result<(), Box<dyn Error>> {
    let latest: Latest = get("/rates/latest?base=EUR")?;
    let usd = latest.rates.get("USD").ok_or("USD is missing")?;
    println!("EUR to USD on {}: {usd}", latest.date);
    Ok(())
}
Go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	req, err := http.NewRequest("GET", "https://api.rateflowapi.com/v1/rates/latest?base=EUR", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("X-API-Key", os.Getenv("RATEFLOW_API_KEY"))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	var body struct {
		Data struct {
			Date  string             `json:"date"`
			Rates map[string]float64 `json:"rates"`
		} `json:"data"`
		Error struct {
			Code   string `json:"code"`
			Detail string `json:"detail"`
		} `json:"error"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		panic(err)
	}

	if resp.StatusCode != http.StatusOK {
		fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, body.Error.Code, body.Error.Detail)
		os.Exit(1)
	}

	fmt.Printf("EUR to USD on %s: %v\n", body.Data.Date, body.Data.Rates["USD"])
}
C#
using System.Text.Json;

using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("RATEFLOW_API_KEY"));

var response = await client.GetAsync("https://api.rateflowapi.com/v1/rates/latest?base=EUR");
var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;

if (!response.IsSuccessStatusCode)
{
    var error = body.GetProperty("error");
    Console.Error.WriteLine($"{(int)response.StatusCode} {error.GetProperty("code")}: {error.GetProperty("detail")}");
    Environment.ExitCode = 1;
    return;
}

var data = body.GetProperty("data");
Console.WriteLine($"EUR to USD on {data.GetProperty("date")}: {data.GetProperty("rates").GetProperty("USD")}");

Convert an Amount

Convert 100 EUR to USD with the pair endpoint. Leave out amount to get only the rate.

cURL
curl -sS --fail-with-body \
  -H "X-API-Key: $RATEFLOW_API_KEY" \
  "https://api.rateflowapi.com/v1/rates/pair/EUR/USD?amount=100"
PHP
<?php

$ch = curl_init('https://api.rateflowapi.com/v1/rates/pair/EUR/USD?amount=100');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('RATEFLOW_API_KEY')],
]);
$body = json_decode((string) curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

if ($status !== 200) {
    fwrite(STDERR, "{$status} {$body['error']['code']}: {$body['error']['detail']}" . PHP_EOL);
    exit(1);
}

echo "100 EUR = {$body['data']['converted']} USD (rate {$body['data']['rate']})" . PHP_EOL;
JavaScript
const response = await fetch('https://api.rateflowapi.com/v1/rates/pair/EUR/USD?amount=100', {
    headers: { 'X-API-Key': process.env.RATEFLOW_API_KEY },
});
const body = await response.json();

if (!response.ok) {
    throw new Error(`${response.status} ${body.error.code}: ${body.error.detail}`);
}

console.log(`100 EUR = ${body.data.converted} USD (rate ${body.data.rate})`);
Python
import os

import requests

response = requests.get(
    "https://api.rateflowapi.com/v1/rates/pair/EUR/USD",
    params={"amount": 100},
    headers={"X-API-Key": os.environ["RATEFLOW_API_KEY"]},
    timeout=10,
)
body = response.json()

if not response.ok:
    raise SystemExit(f"{response.status_code} {body['error']['code']}: {body['error']['detail']}")

print(f"100 EUR = {body['data']['converted']} USD (rate {body['data']['rate']})")
Rust
use serde::{de::DeserializeOwned, Deserialize};
use std::{env, error::Error};

#[derive(Deserialize)]
struct Success<T> {
    data: T,
}

#[derive(Deserialize)]
struct Failure {
    error: ApiError,
}

#[derive(Deserialize)]
struct ApiError {
    code: String,
    detail: String,
}

#[derive(Deserialize)]
struct Pair {
    rate: f64,
    converted: f64,
}

fn get<T: DeserializeOwned>(path: &str) -> Result<T, Box<dyn Error>> {
    let response = reqwest::blocking::Client::new()
        .get(format!("https://api.rateflowapi.com/v1{path}"))
        .header("X-API-Key", env::var("RATEFLOW_API_KEY")?)
        .send()?;

    let status = response.status();
    if status.is_success() {
        return Ok(response.json::<Success<T>>()?.data);
    }

    let body = response.text()?;
    let message = match serde_json::from_str::<Failure>(&body) {
        Ok(failure) => format!("{} {}: {}", status.as_u16(), failure.error.code, failure.error.detail),
        Err(_) => format!("HTTP {status}"),
    };
    Err(message.into())
}

fn main() -> Result<(), Box<dyn Error>> {
    let pair: Pair = get("/rates/pair/EUR/USD?amount=100")?;
    println!("100 EUR = {} USD (rate {})", pair.converted, pair.rate);
    Ok(())
}
Go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	req, err := http.NewRequest("GET", "https://api.rateflowapi.com/v1/rates/pair/EUR/USD?amount=100", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("X-API-Key", os.Getenv("RATEFLOW_API_KEY"))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	var body struct {
		Data struct {
			Rate      float64 `json:"rate"`
			Converted float64 `json:"converted"`
		} `json:"data"`
		Error struct {
			Code   string `json:"code"`
			Detail string `json:"detail"`
		} `json:"error"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		panic(err)
	}

	if resp.StatusCode != http.StatusOK {
		fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, body.Error.Code, body.Error.Detail)
		os.Exit(1)
	}

	fmt.Printf("100 EUR = %v USD (rate %v)\n", body.Data.Converted, body.Data.Rate)
}
C#
using System.Text.Json;

using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("RATEFLOW_API_KEY"));

var response = await client.GetAsync("https://api.rateflowapi.com/v1/rates/pair/EUR/USD?amount=100");
var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;

if (!response.IsSuccessStatusCode)
{
    var error = body.GetProperty("error");
    Console.Error.WriteLine($"{(int)response.StatusCode} {error.GetProperty("code")}: {error.GetProperty("detail")}");
    Environment.ExitCode = 1;
    return;
}

var data = body.GetProperty("data");
Console.WriteLine($"100 EUR = {data.GetProperty("converted")} USD (rate {data.GetProperty("rate")})");

Historical Rate

Fetch the EUR to USD rate for 1 March 2026. Historical rates need a Pro or Business plan. On a Free plan the examples print the 403 PLAN_UPGRADE_REQUIRED error. The response field date is the day the rate was published. It can be earlier than the day you asked for, for example on a weekend (see Historical Rates).

cURL
curl -sS --fail-with-body \
  -H "X-API-Key: $RATEFLOW_API_KEY" \
  "https://api.rateflowapi.com/v1/rates/history/EUR/USD/2026-03-01"
PHP
<?php

$ch = curl_init('https://api.rateflowapi.com/v1/rates/history/EUR/USD/2026-03-01');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('RATEFLOW_API_KEY')],
]);
$body = json_decode((string) curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

if ($status !== 200) {
    fwrite(STDERR, "{$status} {$body['error']['code']}: {$body['error']['detail']}" . PHP_EOL);
    exit(1);
}

echo "EUR to USD on {$body['data']['date']}: {$body['data']['rate']}" . PHP_EOL;
JavaScript
const response = await fetch('https://api.rateflowapi.com/v1/rates/history/EUR/USD/2026-03-01', {
    headers: { 'X-API-Key': process.env.RATEFLOW_API_KEY },
});
const body = await response.json();

if (!response.ok) {
    throw new Error(`${response.status} ${body.error.code}: ${body.error.detail}`);
}

console.log(`EUR to USD on ${body.data.date}: ${body.data.rate}`);
Python
import os

import requests

response = requests.get(
    "https://api.rateflowapi.com/v1/rates/history/EUR/USD/2026-03-01",
    headers={"X-API-Key": os.environ["RATEFLOW_API_KEY"]},
    timeout=10,
)
body = response.json()

if not response.ok:
    raise SystemExit(f"{response.status_code} {body['error']['code']}: {body['error']['detail']}")

print(f"EUR to USD on {body['data']['date']}: {body['data']['rate']}")
Rust
use serde::{de::DeserializeOwned, Deserialize};
use std::{env, error::Error};

#[derive(Deserialize)]
struct Success<T> {
    data: T,
}

#[derive(Deserialize)]
struct Failure {
    error: ApiError,
}

#[derive(Deserialize)]
struct ApiError {
    code: String,
    detail: String,
}

#[derive(Deserialize)]
struct Historical {
    date: String,
    rate: f64,
}

fn get<T: DeserializeOwned>(path: &str) -> Result<T, Box<dyn Error>> {
    let response = reqwest::blocking::Client::new()
        .get(format!("https://api.rateflowapi.com/v1{path}"))
        .header("X-API-Key", env::var("RATEFLOW_API_KEY")?)
        .send()?;

    let status = response.status();
    if status.is_success() {
        return Ok(response.json::<Success<T>>()?.data);
    }

    let body = response.text()?;
    let message = match serde_json::from_str::<Failure>(&body) {
        Ok(failure) => format!("{} {}: {}", status.as_u16(), failure.error.code, failure.error.detail),
        Err(_) => format!("HTTP {status}"),
    };
    Err(message.into())
}

fn main() -> Result<(), Box<dyn Error>> {
    let historical: Historical = get("/rates/history/EUR/USD/2026-03-01")?;
    println!("EUR to USD on {}: {}", historical.date, historical.rate);
    Ok(())
}
Go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	req, err := http.NewRequest("GET", "https://api.rateflowapi.com/v1/rates/history/EUR/USD/2026-03-01", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("X-API-Key", os.Getenv("RATEFLOW_API_KEY"))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	var body struct {
		Data struct {
			Date string  `json:"date"`
			Rate float64 `json:"rate"`
		} `json:"data"`
		Error struct {
			Code   string `json:"code"`
			Detail string `json:"detail"`
		} `json:"error"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		panic(err)
	}

	if resp.StatusCode != http.StatusOK {
		fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, body.Error.Code, body.Error.Detail)
		os.Exit(1)
	}

	fmt.Printf("EUR to USD on %s: %v\n", body.Data.Date, body.Data.Rate)
}
C#
using System.Text.Json;

using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("RATEFLOW_API_KEY"));

var response = await client.GetAsync("https://api.rateflowapi.com/v1/rates/history/EUR/USD/2026-03-01");
var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;

if (!response.IsSuccessStatusCode)
{
    var error = body.GetProperty("error");
    Console.Error.WriteLine($"{(int)response.StatusCode} {error.GetProperty("code")}: {error.GetProperty("detail")}");
    Environment.ExitCode = 1;
    return;
}

var data = body.GetProperty("data");
Console.WriteLine($"EUR to USD on {data.GetProperty("date")}: {data.GetProperty("rate")}");