Skip to content

Instantly share code, notes, and snippets.

@jeremyikwuje
Last active February 24, 2026 07:54
Show Gist options
  • Select an option

  • Save jeremyikwuje/272b8e98892df7644d6dcdfd1b29361e to your computer and use it in GitHub Desktop.

Select an option

Save jeremyikwuje/272b8e98892df7644d6dcdfd1b29361e to your computer and use it in GitHub Desktop.
Monierate API — Golden Snippets for LLM

Monierate API — Golden Snippets

Base URL: https://api.monierate.com/public

Auth: api_key header

TypeScript / JavaScript:

// TypeScript
import axios from 'axios';

const client = axios.create({
  baseURL: 'https://api.monierate.com/public',
  headers: { api_key: process.env.MONIERATE_API_KEY },
});

// 1. Get markets for a ticker (e.g. "USDTNGN")
const getMarkets = async (ticker: string) => {
  const res = await client.get(`/rates/platforms.json?ticker=${ticker}&rate_mode=automated`);
  return res.data?.data?.platforms ?? [];
};

// 2. Get latest rates
const getLatest = async () => {
  const res = await client.get('/rates/latest.json');
  return res.data?.data ?? {};
};

// 3. Get historical rates
const getHistory = async (params: {
  ticker: string;
  page: number;
  interval: number;
  start_date?: number; // unix timestamp
  end_date?: number;   // unix timestamp
  market?: string;
  changer?: string;
}) => {
  const query = new URLSearchParams(
    Object.entries(params)
      .filter(([, v]) => v != null)
      .map(([k, v]) => [k, String(v)])
  );
  const res = await client.get(`/rates/historical.json?${query}`);
  return res.data?.data ?? {};
};

// 4. Get a pair quote
const quotePair = async (params: {
  from: string;
  to: string;
  amount: number;
  changer?: string;
}) => {
  const res = await client.post('/rates/pair_quote.json', params);
  return res.data?.data ?? {};
};

JS / CommonJS

// JavaScript (CommonJS)
const axios = require('axios');

const client = axios.create({
  baseURL: 'https://api.monierate.com/public',
  headers: { api_key: process.env.MONIERATE_API_KEY },
});

async function getMarkets(ticker) {
  const res = await client.get(`/rates/platforms.json?ticker=${ticker}&rate_mode=automated`);
  return res.data?.data?.platforms ?? [];
}

async function getLatest() {
  const res = await client.get('/rates/latest.json');
  return res.data?.data ?? {};
}

async function getHistory({ ticker, page, interval, start_date, end_date, market, changer }) {
  const params = { ticker, page, interval, start_date, end_date, market, changer };
  const query = new URLSearchParams(
    Object.entries(params).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])
  );
  const res = await client.get(`/rates/historical.json?${query}`);
  return res.data?.data ?? {};
}

async function quotePair({ from, to, amount, changer }) {
  const res = await client.post('/rates/pair_quote.json', { from, to, amount, changer });
  return res.data?.data ?? {};
}

Python

import os
import requests

BASE_URL = "https://api.monierate.com/public"
HEADERS = {"api_key": os.environ["MONIERATE_API_KEY"]}

def get_markets(ticker: str) -> list:
    res = requests.get(
        f"{BASE_URL}/rates/platforms.json",
        params={"ticker": ticker, "rate_mode": "automated"},
        headers=HEADERS,
    )
    res.raise_for_status()
    return res.json().get("data", {}).get("platforms", [])

def get_latest() -> dict:
    res = requests.get(f"{BASE_URL}/rates/latest.json", headers=HEADERS)
    res.raise_for_status()
    return res.json().get("data", {})

def get_history(
    ticker: str,
    page: int,
    interval: int,
    start_date: int = None,   # unix timestamp
    end_date: int = None,     # unix timestamp
    market: str = None,
    changer: str = None,
) -> dict:
    params = {k: v for k, v in {
        "ticker": ticker, "page": page, "interval": interval,
        "start_date": start_date, "end_date": end_date,
        "market": market, "changer": changer,
    }.items() if v is not None}
    res = requests.get(f"{BASE_URL}/rates/historical.json", params=params, headers=HEADERS)
    res.raise_for_status()
    return res.json().get("data", {})

def quote_pair(from_currency: str, to_currency: str, amount: float, changer: str = None) -> dict:
    payload = {k: v for k, v in {
        "from": from_currency, "to": to_currency,
        "amount": amount, "changer": changer,
    }.items() if v is not None}
    res = requests.post(f"{BASE_URL}/rates/pair_quote.json", json=payload, headers=HEADERS)
    res.raise_for_status()
    return res.json().get("data", {})

Golang

package monierate

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"strconv"
)

const baseURL = "https://api.monierate.com/public"

func newRequest(method, path string, body io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(method, baseURL+path, body)
	if err != nil {
		return nil, err
	}
	req.Header.Set("api_key", os.Getenv("MONIERATE_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	return req, nil
}

// GetMarkets fetches platform rates for a ticker (e.g. "USDTNGN")
func GetMarkets(ticker string) ([]interface{}, error) {
	req, _ := newRequest("GET", fmt.Sprintf("/rates/platforms.json?ticker=%s&rate_mode=automated", ticker), nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	data, _ := result["data"].(map[string]interface{})
	platforms, _ := data["platforms"].([]interface{})
	return platforms, nil
}

// GetLatest fetches the latest rates
func GetLatest() (map[string]interface{}, error) {
	req, _ := newRequest("GET", "/rates/latest.json", nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	data, _ := result["data"].(map[string]interface{})
	return data, nil
}

// GetHistory fetches historical rates
type HistoryParams struct {
	Ticker    string
	Page      int
	Interval  int
	StartDate *int64 // unix timestamp, optional
	EndDate   *int64 // unix timestamp, optional
	Market    *string
	Changer   *string
}

func GetHistory(p HistoryParams) (map[string]interface{}, error) {
	q := url.Values{}
	q.Set("ticker", p.Ticker)
	q.Set("page", strconv.Itoa(p.Page))
	q.Set("interval", strconv.Itoa(p.Interval))
	if p.StartDate != nil { q.Set("start_date", strconv.FormatInt(*p.StartDate, 10)) }
	if p.EndDate != nil   { q.Set("end_date",   strconv.FormatInt(*p.EndDate, 10)) }
	if p.Market != nil    { q.Set("market",  *p.Market) }
	if p.Changer != nil   { q.Set("changer", *p.Changer) }

	req, _ := newRequest("GET", "/rates/historical.json?"+q.Encode(), nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	data, _ := result["data"].(map[string]interface{})
	return data, nil
}

// QuotePair fetches a conversion quote between two currencies
type QuoteParams struct {
	From    string  `json:"from"`
	To      string  `json:"to"`
	Amount  float64 `json:"amount"`
	Changer *string `json:"changer,omitempty"`
}

func QuotePair(p QuoteParams) (map[string]interface{}, error) {
	body, _ := json.Marshal(p)
	req, _ := newRequest("POST", "/rates/pair_quote.json", bytes.NewReader(body))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)
	data, _ := result["data"].(map[string]interface{})
	return data, nil
}

PHP

<?php

class MonierateClient
{
    private string $baseUrl = 'https://api.monierate.com/publc';
    private string $apiKey;

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
    }

    private function request(string $method, string $path, array $query = [], array $body = []): array
    {
        $url = $this->baseUrl . $path;
        if (!empty($query)) {
            $url .= '?' . http_build_query(array_filter($query, fn($v) => $v !== null));
        }

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => [
                'api_key: ' . $this->apiKey,
                'Content-Type: application/json',
            ],
        ]);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true)['data'] ?? [];
    }

    // Get platform rates for a ticker (e.g. "USDTNGN")
    public function getMarkets(string $ticker): array
    {
        return $this->request('GET', '/rates/platforms.json', [
            'ticker'    => $ticker,
            'rate_mode' => 'automated',
        ])['platforms'] ?? [];
    }

    // Get latest rates
    public function getLatest(): array
    {
        return $this->request('GET', '/rates/latest.json');
    }

    // Get historical rates
    public function getHistory(
        string $ticker,
        int $page,
        int $interval,
        ?int $start_date = null,  // unix timestamp
        ?int $end_date = null,    // unix timestamp
        ?string $market = null,
        ?string $changer = null
    ): array {
        return $this->request('GET', '/rates/historical.json', compact(
            'ticker', 'page', 'interval', 'start_date', 'end_date', 'market', 'changer'
        ));
    }

    // Get a conversion quote between two currencies
    public function quotePair(
        string $from,
        string $to,
        float $amount,
        ?string $changer = null
    ): array {
        $body = array_filter(compact('from', 'to', 'amount', 'changer'), fn($v) => $v !== null);
        return $this->request('POST', '/rates/pair_quote.json', [], $body);
    }
}

// Usage
$client = new MonierateClient($_ENV['MONIERATE_API_KEY']);

$markets = $client->getMarkets('USDTNGN');
$latest  = $client->getLatest();
$history = $client->getHistory('USDTNGN', page: 1, interval: 24);
$quote   = $client->quotePair(from: 'USDT', to: 'NGN', amount: 100);

Rust

require 'net/http'
require 'uri'
require 'json'

class MonierateClient
  BASE_URL = 'https://api.monierate.com/publc'

  def initialize(api_key = ENV['MONIERATE_API_KEY'])
    @api_key = api_key
  end

  # Get platform rates for a ticker (e.g. "USDTNGN")
  def get_markets(ticker)
    data = get('/rates/platforms.json', ticker: ticker, rate_mode: 'automated')
    data.dig('platforms') || []
  end

  # Get latest rates
  def get_latest
    get('/rates/latest.json')
  end

  # Get historical rates
  def get_history(ticker:, page:, interval:, start_date: nil, end_date: nil, market: nil, changer: nil)
    params = { ticker:, page:, interval:, start_date:, end_date:, market:, changer: }
               .compact
    get('/rates/historical.json', params)
  end

  # Get a conversion quote between two currencies
  def quote_pair(from:, to:, amount:, changer: nil)
    body = { from:, to:, amount:, changer: }.compact
    post('/rates/pair_quote.json', body)
  end

  private

  def get(path, params = {})
    uri = URI("#{BASE_URL}#{path}")
    uri.query = URI.encode_www_form(params) unless params.empty?

    req = Net::HTTP::Get.new(uri)
    req['api_key'] = @api_key

    response(req, uri)
  end

  def post(path, body = {})
    uri = URI("#{BASE_URL}#{path}")

    req = Net::HTTP::Post.new(uri)
    req['api_key']      = @api_key
    req['Content-Type'] = 'application/json'
    req.body = body.to_json

    response(req, uri)
  end

  def response(req, uri)
    Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
      res = http.request(req)
      JSON.parse(res.body).dig('data') || {}
    end
  end
end

# Usage
client = MonierateClient.new

markets = client.get_markets('USDTNGN')
latest  = client.get_latest
history = client.get_history(ticker: 'USDTNGN', page: 1, interval: 24)
quote   = client.quote_pair(from: 'USDT', to: 'NGN', amount: 100)

Key facts the LLM should always know

Detail Value
Base URL https://api.monierate.com/public
Auth header api_key (not Authorization: Bearer)
Markets endpoint GET /rates/platforms.json?ticker=USDTNGN&rate_mode=automated
Latest endpoint GET /rates/latest.json
Historical endpoint GET /rates/historical.json (params: ticker, page, interval, optional start_date/end_date as unix timestamps)
Quote endpoint POST /rates/pair_quote.json with JSON body { from, to, amount, changer? }
Response envelope { data: { ... } } — always unwrap .data

This response was AI generated and was not tested for all languages. Please refer to the Monierate API documentation for the most accurate and up-to-date information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment