Exploring Currency Data with BCRA API: A Practical Guide

November 19, 2024

In the world of software development, playing with APIs is an excellent way to expand your skills and gain insight into real-world applications. Recently, I discovered the BCRA API (Banco Central de la República Argentina), which provides data on currency exchange rates and statistics. This article walks through how I explored this API to fetch currency details and exchange rates, complete with example code and tests.


Understanding the API

The BCRA API features endpoints under its “Estadísticas Cambiarias” section, which are accessible via Swagger documentation. Specifically, I focused on the following:

  1. Currency List Endpoint (/estadisticascambiarias/v1.0/Maestros/Divisas): Fetches a list of currencies and their codes.
  2. Currency Exchange Rate Endpoint (/estadisticascambiarias/v1.0/Cotizaciones/{codMoneda}): Retrieves the exchange rate for a specific currency code.

Implementation

Using Ruby, I wrote a class called Coins to interact with the API. Here’s a breakdown of its functionality:

Coins Class

require "json"
require "rest-client"

class Coins
  def initialize
    @server = "https://api.bcra.gob.ar"
    @coins_endpoint = "/estadisticascambiarias/v1.0/Maestros/Divisas"
    @values_endpoint = "/estadisticascambiarias/v1.0/Cotizaciones/{codMoneda}"
  end

  # Fetches a list of all currencies
  def coins
    JSON.parse(RestClient::Request.execute(url: "#{@server}#{@coins_endpoint}", method: :get, verify_ssl: false))["results"]
  end

  # Fetches details of a specific currency by code
  def coin(code)
    self.coins.find { |coin| coin["codigo"] == code }
  end

  # Fetches the exchange rate for a specific currency
  def values(code)
    response = RestClient::Request.execute(url: "#{@server}#{@values_endpoint.gsub('{codMoneda}', code)}", method: :get, verify_ssl: false)
    JSON.parse(response)["results"].first["detalle"].first["tipoCotizacion"]
  end
end

🚀 Need Expert Ruby on Rails Developers to Elevate Your Project?

Fill out our form! >>

🚀 Need Expert Ruby on Rails Developers to Elevate Your Project?

Testing the Implementation

To ensure the reliability of the Coins class, I wrote unit tests using RSpec. These tests cover both fetching data and validating expected outcomes.

RSpec Tests

require "coins"

RSpec.describe Coins, "#coins" do
  context "Fetching the list of currencies" do
    subject { Coins.new }

    it "returns a list of 44 currencies" do
      coins = subject.coins
      expect(coins.count).to eq(44)
    end

    it "includes Dollar, Euro, and Real" do
      coins = subject.coins.select { |coin| ["USD", "BRL", "EUR"].include?(coin["codigo"]) }
      expect(coins).to eq([
        { "codigo" => "BRL", "denominacion" => "REAL" },
        { "codigo" => "EUR", "denominacion" => "EURO" },
        { "codigo" => "USD", "denominacion" => "DOLAR E.E.U.U." }
      ])
    end

    it "retrieves details for Florin currency" do
      coin = subject.coin("AWG")
      expect(coin).to eq({ "codigo" => "AWG", "denominacion" => "FLORIN (ANTILLAS HOLANDESAS)" })
    end
  end

  context "Fetching currency exchange rates" do
    subject { Coins.new }

    it "returns a numeric value for Dollar exchange rate" do
      value = subject.values("USD")
      expect(value.class).to eq(Float)
    end

    it "returns a numeric value for Real exchange rate" do
      value = subject.values("BRL")
      expect(value.class).to eq(Float)
    end
  end
end

Key Learnings

  1. Working with APIs: The BCRA API offers structured, real-time data, making it an excellent tool for learning and experimentation.
  2. Testing API Integration: Writing tests for APIs ensures your implementation is robust and capable of handling various scenarios.
  3. Practical Applications: With this setup, you could build a currency converter, monitor exchange rates, or integrate this data into a financial application.

Potential Use Cases

  • Currency Conversion: Use the API to create a dynamic currency converter.
  • Market Insights: Analyze historical exchange rate trends for financial forecasting.
  • Learning Tool: Enhance your understanding of APIs, data parsing, and testing with real-world examples.

Conclusion

Exploring APIs like BCRA’s is both fun and educational. By interacting with endpoints, designing a robust class, and writing thorough tests, you not only build useful tools but also improve your coding skills. If you’re interested in financial data or APIs in general, give this exercise a try—you’ll gain valuable insights while building something practical.

Leave a comment