認証情報を公開せず、出典と観測時刻を保持してサーバー側で実装します。
要点
APIキーはサーバーだけに保存する。
通貨コードと金額を検証する。
成功したレスポンスをキャッシュする。
出典と観測時刻を表示する。
手順 1
コード例copy
require "net/http" require "json" class ExchangeRateClient Error = Class.new(StandardError) def convert(from:, to:, amount:) from = from.to_s.upcase to = to.to_s.upcase raise Error, "invalid currency code" unless [from, to].all? { |code| code.match?(/A[A-Z]{3}z/) } key = ["fx-convert", from, to, amount.to_d.to_s("F")] Rails.cache.fetch(key, expires_in: 60.seconds) do uri = URI("https://api.exchangerate.dev/v1/convert/#{from}/#{to}/#{amount}") request = Net::HTTP::Get.new(uri) request["Authorization"] = "Bearer #{ENV.fetch("EXCHANGERATE_API_KEY")}" response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 2, read_timeout: 5) { |http| http.request(request) } raise Error, "exchange-rate API returned #{response.code}" unless response.is_a?(Net::HTTPSuccess) JSON.parse(response.body) end rescue Net::OpenTimeout, Net::ReadTimeout => error raise Error, "exchange-rate API timed out: #{error.class}" end end
手順 2
コード例copy
class ConversionsController < ApplicationController def show amount = BigDecimal(params.require(:amount)) result = ExchangeRateClient.new.convert( from: params.require(:from).upcase, to: params.require(:to).upcase, amount: amount ) render json: result.slice("from", "to", "amount", "rate", "converted", "source", "market_session", "data_updated_at") rescue ExchangeRateClient::Error, ArgumentError => error render json: { error: error.message }, status: :bad_gateway end end
手順 3
サーバー側で実行し、入力を検証してレスポンスのメタデータを保存します。
手順 4
サーバー側で実行し、入力を検証してレスポンスのメタデータを保存します。
ガイド
表示される値は参考レートであり、決済価格ではありません。
ER
exchangerate.dev
通貨データを扱う開発者向けの実践ガイド。
