在跨境贸易、金融系统、跨境电商等业务中,实时获取全球主要货币的汇率信息是基础且关键的需求。本文以多币种汇率查询接口为例,演示如何通过 Python 快速集成汇率数据获取功能。
一、接口概览
请求方式:GET
返回格式:JSON
响应示例:
js{
"code": 1,
"msg": "操作成功",
"data": {
"from": "CNY",
"from_name": "人民币",
"to": "USD",
"to_name": "美元",
"exchange": "0.139170",
"money": "0.139170",
"updatetime": "2025-06-12 11:22:34"
}
}
二、Python 调用示例
安装依赖、

核心调用函数
jsimport os
import sys
import requests
def get_exchange_rate(from_currency: str, to_currency: str) -> dict:
"""
获取指定货币对的实时汇率。
:param from_currency: 原始货币代码(如 CNY)
:param to_currency: 目标货币代码(如 USD)
:return: JSON 响应数据
"""
app_code = os.getenv("TANSHU_APPCODE")
if not app_code:
print("请设置环境变量 TANSHU_APPCODE", file=sys.stderr)
sys.exit(1)
url = "https://www.tanshuapi.com/market/detail-84"#地址
headers = {
"Authorization": f"APPCODE {app_code}"
}
params = {
"from": from_currency,
"to": to_currency
}
try:
resp = requests.get(url, headers=headers, params=params, timeout=5)
resp.raise_for_status()
except requests.RequestException as e:
print(f"请求失败: {e}", file=sys.stderr)
return {}
return resp.json()
if __name__ == "__main__":
result = get_exchange_rate(from_currency="CNY", to_currency="USD")
if not result:
sys.exit(1)
code = result.get("code")
if code != 1:
print(f"查询失败:{result.get('msg')}")
else:
data = result.get("data", {})
print(f"汇率:{data['from']} → {data['to']}")
print(f"兑换比例:{data['exchange']}")
print(f"更新时间:{data['updatetime']}")
三、扩展功能支持
获取所有支持币种列表
jsdef get_all_currencies(): url = "https://www.tanshuapi.com/market/detail-84" headers = {"Authorization": f"APPCODE {os.getenv('TANSHU_APPCODE')}"} try: resp = requests.get(url, headers=headers, timeout=5) resp.raise_for_status() return resp.json() except requests.RequestException as e: print(f"获取币种失败:{e}", file=sys.stderr) return {}查询单币种对多种货币的汇率
jsdef get_rates_from(base_currency: str): url = "https://www.tanshuapi.com/market/detail-84" headers = {"Authorization": f"APPCODE {os.getenv('TANSHU_APPCODE')}"} params = {"from": base_currency} try: resp = requests.get(url, headers=headers, params=params, timeout=5) resp.raise_for_status() return resp.json() except requests.RequestException as e: print(f"获取汇率失败:{e}", file=sys.stderr) return {}四、总结
通过本文介绍的方法,你可以快速在 Python 中接入多币种汇率查询接口,满足跨境电商、国际贸易、金融系统等多种业务需求。