Backcurrency conversion

How To Use The Currency Conversion API with PHP, Python, and Other Popular Programming Languages

06 February 2023

Currency conversion API is critical for developers. It can add real-time currency conversion rate retrieval features that enrich the user experience. In this article, we will take you through various examples. We will show the use of the converter API with different programming languages. Let us start with learning more about the service and the API.

What is the Currency Conversion API Service?

Currency Conversion API service allows users to get currency conversion rates instantly. Users can send an HTTP request to the vendor’s server and get the conversion rate value as a response. Developers can integrate this API into their websites and applications to facilitate the display of live currency conversion rates updated in real-time.

Our currency exchange rate API service aims to assist developers in keeping users updated about the latest conversion rates. Our exchange rates API supports numerous currencies and thus helps developers enrich their apps and websites with excellent data retrieval features, including historical rates.

The currency conversion API helps in many other ways. Developers can build:

  • Tables with periodical currency conversion rates, 
  • Charts, and 
  • Graphs to ease users for in-depth forex analysis. 

We provide aggregated and curated forex data. It can be an excellent reference feed to make informed trading decisions.

What is the Currency Conversion API?

Currency conversion API is an effective tool to get conversion rate values instantly. Developers should specify the base and target currencies. The API serves as the tool to get real-time currency conversion rates. You need to send a request and receive a response. 

How does the Currency Conversion API Work?

The currency data our API provides helps developers add data retrieval features. They can integrate it into their trading apps, websites, and other platforms. It is practical to get currency exchange rates at an instance. You need to send a request and get a response from our server. Specify both currencies and provide your API key. That way, you get the outcome response through every API request. 

You can set up websites and apps to retrieve the real-time currency conversion value. It is also possible to get the value of a desired currency in the local currency. You need to deploy geological detection of dynamic user displays in web browsers. You can get the foreign exchange rate for specific times for historical chart references.

How to Use the Currency Conversion API Through Various Popular Programming Languages? 

You need, an API key to get conversion rates for desired currency pairs. Our free currency converter API (up to 1000 free requests rate limit per month) is practical to use and set up. You can sign up for the free API Key. We provide several examples of various popular programming languages. A vertical menu on your left-hand side on our Data Documentation Page lists the supported programming languages. 

Examples on Our Website

Let us glance at the example snippets available on our data documentation page. These examples help programmers add data retrieval features to their websites and applications:

PHP (Curl)

The PHP snippet helps developers, looking to build:

  • CMS scripts, 
  • Custom display pages, or 
  • Insert tables of currency exchange rates 

Also, publishers can use the PHP code. It helps add support to the currency exchange API for web page platforms. (like WordPress, Drupal, and Jumla)

Below is an example showing converting exchange rate data using PHP (CURL):


$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_PORT => "443",
  CURLOPT_URL => "",



//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($curl);

$err = curl_error($curl);


if ($err) {

  echo "cURL Error #:" . $err;

} else {

  echo $response;




The Python snippets help developers working on Django, flask, and other frameworks. They can add API scripts to their code.

Below is an example to get live exchange rates data using Python:

See our tutorial on Fetch Forex API with Python and Pandas.

import requests
url = ""
querystring = {"from":"EUR","to":"GBP","api_key":"API_KEY","amount":1000}
response = requests.get(url, params=querystring)


Below is an example to get live exchange rates data using R:

See our detailed tutorial: Learn how to get live and historical forex data using R language.

library (httr)
library (jsonlite)

req <- ""

data_raw <- GET(url = req)
data_text = content(data_raw, "text", encoding = "UTF-8")
data_json = fromJSON(data_text, flatten=TRUE)
dataframe =




Below is an example to get live exchange rates data using Golang:

For further explanation, see our tutorials: Get live forex data and parse REST JSON API with GoLang.

package main

  import (



type data struct {

      Endpoint       string                   `json:'endpoint'`

      Quotes         []map[string]interface{} `json:'quotes'`

      Requested_time string                   `json:'requested_time'`

      Timestamp      int32                    `json:'timestamp'`


  func main(){
      api_key := "API_KEY"
      from := "EUR"
      to := "GBP"
      amount := "10000"

      url := "" + from + "&to=" + to + "&amount=" + amount + "&api_key=" + api_key

      resp, getErr := http.Get(url)
      if getErr != nil {

      body, readErr := ioutil.ReadAll(resp.Body)
      if readErr != nil {

      data_obj := data{}
      jsonErr := json.Unmarshal(body, &data_obj)
      if jsonErr != nil {


      fmt.Println("endpoint", data_obj.Endpoint, "requested time", data_obj.Requested_time, "timestamp", data_obj.Timestamp)
      for key, value := range data_obj.Quotes {




Below is an example to get live exchange rates data using C#:

For further explanation, see our tutorials: Get live forex data and parse REST JSON API with C#.

using System;
Using System.Net.Http;
Using Newtonsoft.Json;
namespace crest

    class Program
        static async System.Threading.Tasks.Task Main(string[] args)
            HttpClient client = new HttpClient();
            var requestString="";
            Console.WriteLine(" Request String: " + requestString);
            HttpResponseMessage response = await client.GetAsync(requestString);

            var responseBody = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<Quotes>(responseBody);
            Console.WriteLine("Results " + responseBody);

        public class Quotes


            public string base_currency { get; set; }
            public string endpoint { get; set; }
            public string quote { get; set; }        
            public string quote_currency { get; set; }
            public string requested_time { get; set; }
            public string timestamp { get; set; }
            public string total { get; set; }



Using Axios

Below is an example to get historical exchange rates data using JavaScript, Axios, and NodeJS:

For further explanation, see our tutorials: Get live forex data and parse REST JSON API with JavaScript, Axios, and NodeJS.

const axios = require('axios');


  .then(response => {


  .catch(error => {

JavaScript (fetch)

Below is an example to get historical exchange rates data using fetch:

var requestOptions = {

method : 'GET',
redirect : 'follow'

fetch( '''', requestOptions)
.then(response => response.text())
.then(result =>  console.log(result))
.catch(error =>  console.log( 'error', error));

JavaScript (jQuery)

Below is an example to get historical exchange rate data using jQuery:

var settings = {

"url": "''",
"method": "GET",
"timeout": 0,

$.ajax(settings).done(function (response) {

Examples in Other Popular Programming Languages

Here are a few more examples in other programming languages:



data class Quote(

    val baseCurrency: String,
    val quoteCurrency: String,
    val bid: Double,
    val ask: Double,
    val mid: Double

) {

    override fun toString(): String {
        return "$baseCurrency$quoteCurrency: Bid=$bid, Ask=$ask, Mid=$mid"

data class Response(

    val endpoint: String,
    val quotes: List<Quote>,
    val requestedTime: String,
    val timestamp: Long

) {

    override fun toString(): String {
        return "Endpoint: $endpoint, Requested Time: $requestedTime, Timestamp: $timestamp"

data class Data(

    val endpoint: String,
    val quotes: List<Map<String, Any>>,
    val requested_time: String,
    val timestamp: Long

fun main() {

    val apiKey = "API_KEY"
    val from = "EUR"
    val to = "GBP"
    val amount = "10000"

    val url =

    val response = URL(url).readText()
    val gson = GsonBuilder().create()
    val dataObj = gson.fromJson(response,

    val responseObj = Response(

        endpoint = dataObj.endpoint,
        quotes = {
                baseCurrency = it["base_currency"] as String,
                quoteCurrency = it["quote_currency"] as String,
                bid = it["bid"] as Double,
                ask = it["ask"] as Double,
                mid = it["mid"] as Double

        requestedTime = dataObj.requested_time,
        timestamp = dataObj.timestamp

    responseObj.quotes.forEachIndexed { index, quote ->
        println("${index + 1}. ${quote.toString()}")


require 'json'
require 'net/http'
require 'uri'
class Data

attr_accessor :endpoint, :quotes, :requested_time, :timestamp

api_key = "API_KEY"
from = "EUR"
to = "GBP"
amount = "10000"

url = "{from}&to=#{to}&amount=#{amount}&api_key=#{api_key}"

uri = URI.parse(url)

response = Net::HTTP.get_response(uri)

if response.is_a?(Net::HTTPSuccess)
body = response.body
data_obj = JSON.parse(body)

puts "endpoint: #{data_obj["endpoint"]}, requested time: #{data_obj["requested_time"]}, timestamp: #{data_obj["timestamp"]}"

data_obj["quotes"].each_with_index do |value, index|
puts "#{index}. #{value}"

puts "Failed to fetch data"


import Foundation

struct Data: Decodable {

    let endpoint: String
    let quotes: [Quote]
    let requestedTime: String
    let timestamp: Int32

    enum CodingKeys: String, CodingKey {
        case endpoint
        case quotes
        case requestedTime = "requested_time"
        case timestamp

struct Quote: Decodable {
    let code: String
    let value: Double

    enum CodingKeys: String, CodingKey {
        case code
        case value

let apiKey = "API_KEY"
let from = "EUR"
let to = "GBP"
let amount = "10000"

let url = "\(from)&to=\(to)&amount=\(amount)&api_key=\(apiKey)"

guard let urlEncoded = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let urlObj = URL(string: urlEncoded) else {

    print("Failed to encode URL")

let task = URLSession.shared.dataTask(with: urlObj) { (data, response, error) in
    if let error = error {
        print("Error: \(error.localizedDescription)")

    guard let data = data else {
        print("No data received")

    do {
        let dataObj = try JSONDecoder().decode(Data.self, from: data)
        print("endpoint: \(dataObj.endpoint), requested time: \(dataObj.requestedTime), timestamp: \(dataObj.timestamp)")

        for (index, quote) in dataObj.quotes.enumerated() {
            print("\(index). \(quote.code): \(quote.value)")
    } catch {
        print("Error decoding JSON: \(error.localizedDescription)")



use strict;
use warnings;
use LWP::UserAgent;
use JSON;

my $apiKey = "API_KEY";
my $from = "EUR";
my $to = "GBP";
my $amount = "10000";
my $url = "$from&to=$to&amount=$amount&api_key=$apiKey";
my $ua = LWP::UserAgent->new;
my $response = $ua->get($url);

if ($response->is_success) {
my $body = $response->decoded_content;
my $data_obj = decode_json($body);
print "endpoint: $data_obj->{endpoint}, requested time: $data_obj->{requested_time}, timestamp: $data_obj->{timestamp}\n";

foreach my $index (0 .. $#{$data_obj->{quotes}}) {
my $quote = $data_obj->{quotes}[$index];
print "$index. $quote->{code}: $quote->{value}\n";
} else {
print "Failed to fetch data\n";

The Final Thoughts

This tutorial takes you through various examples in popular programming languages to help you access and use our market data. Our API provides free currency conversion for you to start with (Free up to 1000 requests a month). We hope the examples covered here will help developers proficient in many programming languages extract the desired results conveniently. 

Please get in touch with our market data experts through live chat or email in case of any technical queries or suggestions.