Python xử lý gọi API rất tốt. Có thể lấy tỷ giá chuyển đổi ngoại tệ thời gian thực và lịch sử.
Sử dụng forex-python
Module forex-python cung cấp cách trực tiếp nhất. Hàm get_rate(base, target) trả về tỷ giá hiện tại.
Ví dụ
from forex_python.converter import CurrencyRates
c = CurrencyRates()
print(c.get_rate('USD', 'GBP'))
Kết quả
0.7357387755
Tỷ giá lịch sử
Thêm đối tượng datetime để lấy tỷ giá tại thời điểm cụ thể.
Ví dụ
from forex_python.converter import CurrencyRates
import datetime
c = CurrencyRates()
dt = datetime.datetime(2020, 3, 27, 11, 21, 13, 114505)
print(c.get_rate('USD', 'INR', dt))
Kết quả
75.4937596793
Sử dụng Web API
Gọi API công khai (cần API key), nhận JSON, xử lý thêm.
Ví dụ
import requests url = 'https://v6.exchangerate-api.com/v6/336ccxxxxxxxxx8e74eac/latest/USD' response = requests.get(url) data = response.json() print(data)
Kết quả
{'result': 'success', 'documentation': 'https://www.exchangerate-api.com/docs', ...}