0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで為替レートを取得してみる

0
Posted at

はじめに

今回はAPIを使って為替レートを取得するスクリプトを書いてみました。無料で使え、APIキーも不要な Frankfurter API を利用しました。

やりたいこと

Python で現在の為替レートを取得します(今回は例としてUSD → JPYのレート)。

実際のコード

code.py
import requests

def get_exchange_rate(base, target):
    url = f"https://api.frankfurter.app/latest?from={base}&to={target}"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        rate = data["rates"][target]
        return rate
    else:
        raise Exception(f"APIエラー: {response.status_code}")
    
# 例: USD→JPYのレート取得
rate = get_exchange_rate("USD", "JPY")
print(f"1 USD = {rate} JPY")

# 計算例: 100ドルを円に変換
usd_amount = 100
jpy_amount = usd_amount * rate
print(f"{usd_amount} USD = {jpy_amount:.2f} JPY")

上記を実行すると、下記のように結果が表示されます。

1 USD = 150.23 JPY
100 USD = 15023.00 JPY

ポイント

✅requests で簡単に API を叩ける
✅response.json() で JSON データをそのまま辞書として扱え、rates の中から目的の通貨レートを取り出すだけ
✅API の URL で from や to の通貨コードを変えれば、他の通貨ペアでも使えます。

まとめ

Python と Frankfurter API を使えば、数行のコードで為替レートを取得できます。まずは USD→JPY のようなシンプルな例で動作を確認しました。今後、必要に応じて複数通貨やグラフ化などにも拡張してみてようと思います。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?