在本指南的结尾,您将能够查询任何宏观经济指标,查看可用数据的完整目录,并查看即将发布的日期. 图表QL 的终点 使用的东西只有 curl您还将知道如何将多个查询分组成一个往返的单个查詢,
预先要求
- 没有人知道. 汇率数据API键 美元指标和数据目录是免费的,没有密钥;所有其他货币都需要一个. 没有任何其他信息.
curl(或任何HTTP客户端) 进行初始测试调用- 通过Python 3.9+
requests图书馆 (pip install requests) 对于Python示例 - 对于JavaScript示例来说,Node.js 18+
- 基本熟悉 GraphQL 查询语法 (卷曲括号内的字段列表)
为什么要使用 GraphQL 而不是 REST?
FXMacroData REST API 在自己的终点上服务于每个指标 每种货币/指标组合一次往返. GraphQL 允许您正确声明您需要的字段,并将多个独立查询组合到一个单个 HTTP 请求中. 如果您想要EUR通胀序列 并且 英政策利率 并且 两种货币的即将发布日程,即一个POST而不是四个GET请求.
图像QL表面完全反映了公共REST终端:相同的身份验证规则,相同的数据,相同领域名称
POST /api/v1/graphql 终点是用JSON体的.
一子的 GraphQL 终点
- 标签:
https://fxmacrodata.com/api/v1/graphql - 方法: 邮政
- 编者:
?api_key=YOUR_API_KEY查询参数 - 内容类型:
application/json - 免费访问: 美元指标和
dataCatalogue现在我们要做什么?calendar(没有需要钥匙) - 查询字段:
announcements没有人知道.dataCatalogue没有人知道.calendar
步骤1 发送您的第一个 GraphQL 查询
每个 GraphQL 请求都是一个 JSON 对象, query 关键的值是您的 GraphQL 查询字符串. 开始使用免费的美元通胀查询 无需 API 键:
curl -s -X POST "https://fxmacrodata.com/api/v1/graphql" \
-H "Content-Type: application/json" \
-d '{
"query": "{ announcements(currency: \"USD\", indicator: \"inflation\") { currency indicator data { date val pctChange } } }"
}'
响应是标准的GraphQL JSON,包裹在一个 data 封面:
{
"data": {
"announcements": {
"currency": "USD",
"indicator": "inflation",
"data": [
{ "date": "2025-01-01", "val": 3.0, "pctChange": null },
{ "date": "2025-02-01", "val": 2.8, "pctChange": -6.67 },
{ "date": "2025-03-01", "val": 2.4, "pctChange": -14.29 }
]
}
}
}
对于任何非美元货币,请在终点URL上添加您的API键作为查询参数:
https://fxmacrodata.com/api/v1/graphql?api_key=YOUR_API_KEY
提示号召
pctChange 是与前一个数据点相比的月度 (或期度) 变化. 序列中的第一个点总是返回
null 因为没有任何先前的值可以比较.
步骤2 发现可用的指标 dataCatalogue
在查询特定指标之前,您可以问API它对任何货币的数据. dataCatalogue 查询返回每个可用指标,其可读取的人类名称,单位,发布频率,以及央行是否发布官方预测.
curl -s -X POST "https://fxmacrodata.com/api/v1/graphql" \
-H "Content-Type: application/json" \
-d '{
"query": "{ dataCatalogue(currency: \"EUR\") { currency indicators { slug name unit frequency hasOfficialForecast } } }"
}'
举例答案 (简称):
{
"data": {
"dataCatalogue": {
"currency": "EUR",
"indicators": [
{ "slug": "inflation", "name": "Inflation (CPI)", "unit": "%", "frequency": "monthly", "hasOfficialForecast": false },
{ "slug": "policy_rate", "name": "Policy Rate", "unit": "%", "frequency": "irregular", "hasOfficialForecast": true },
{ "slug": "gdp", "name": "GDP Growth", "unit": "%", "frequency": "quarterly", "hasOfficialForecast": false },
{ "slug": "unemployment", "name": "Unemployment", "unit": "%", "frequency": "monthly", "hasOfficialForecast": false }
]
}
}
}
没有什么. slug 值是你通过的字符串, indicator
后面会有这样的论点. announcements 您可以在互动方式浏览整个指标目录
API数据文件现在我们要做什么?
步骤3 使用可选日期过器获取历史数据
没有什么. announcements 查询接受可选 startDate 现在我
endDate 没有任何理由. YYYY-MM-DD 没有它们,API返回一个合理的默认窗口 (通常为1224个月).您还可以在将现实读数与官方利率目标进行比较时,在系列旁边请求央行目标.
curl -s -X POST "https://fxmacrodata.com/api/v1/graphql?api_key=YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "query { announcements(currency: \"AUD\", indicator: \"policy_rate\", startDate: \"2024-01-01\") { currency indicator hasOfficialForecast cbTarget { description current { effectiveFrom target } } data { date val announcementDatetime } } }"
}'
答案的重点:
{
"data": {
"announcements": {
"currency": "AUD",
"indicator": "policy_rate",
"hasOfficialForecast": true,
"cbTarget": {
"description": "RBA cash rate target band",
"current": { "effectiveFrom": "2023-11-07", "target": 4.35 }
},
"data": [
{ "date": "2024-02-06", "val": 4.35, "announcementDatetime": 1707199200 },
{ "date": "2024-03-19", "val": 4.35, "announcementDatetime": 1710813600 }
]
}
}
}
announcementDatetime 是官方出版物的一个Unix时间 (秒,UTC).您可以在
澳元政策利率文件现在我们要做什么?
步骤4 查询发布日程
没有什么. calendar 查询返回给定货币的每一个即将发布的指标的计划UTC公告时间. 通过可选的 indicator
结果缩小到一个指标.
curl -s -X POST "https://fxmacrodata.com/api/v1/graphql?api_key=YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "{ calendar(currency: \"GBP\", indicator: \"inflation\") { currency data { release announcementDatetime } } }"
}'
{
"data": {
"calendar": {
"currency": "GBP",
"data": [
{ "release": "inflation", "announcementDatetime": 1745917200 }
]
}
}
}
转换 announcementDatetime 在Python中,将时间转换为可读的UTC时间,
datetime.utcfromtimestamp(1745917200)或用JavaScript来编写
new Date(1745917200 * 1000).toISOString()详情见英通胀指标的
英通货膨胀数据现在我们要做什么?
步骤5 在一个请求中批量多个查询
GraphQL 的最大实用优势是能够在单个 HTTP POST 中命名和发送多个独立查询. 使用查询别名来避免字段名称冲突. data 答案对象.
curl -s -X POST "https://fxmacrodata.com/api/v1/graphql?api_key=YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "query MultiIndicator { eurInflation: announcements(currency: \"EUR\", indicator: \"inflation\") { currency indicator data { date val } } gbpRate: announcements(currency: \"GBP\", indicator: \"policy_rate\") { currency indicator data { date val } } audCalendar: calendar(currency: \"AUD\") { currency data { release announcementDatetime } } }"
}'
响应将所有三个结果都包含在一个有效载荷中:
{
"data": {
"eurInflation": { "currency": "EUR", "indicator": "inflation", "data": [ ... ] },
"gbpRate": { "currency": "GBP", "indicator": "policy_rate", "data": [ ... ] },
"audCalendar": { "currency": "AUD", "data": [ ... ] }
}
}
提示号召
步骤6 Python 客户端
下面的模式将 GraphQL 请求包裹在一个小的辅助器中,以便您的应用程序代码保持可读性. 它支持单个查询和批次别名查询,具有相同的功能.
import requests
GRAPHQL_URL = "https://fxmacrodata.com/api/v1/graphql"
API_KEY = "YOUR_API_KEY" # leave empty for free USD/catalogue endpoints
def gql(query: str) -> dict:
"""Send a GraphQL query and return the parsed `data` object."""
params = {"api_key": API_KEY} if API_KEY else {}
resp = requests.post(
GRAPHQL_URL,
params=params,
json={"query": query},
headers={"Content-Type": "application/json"},
timeout=15,
)
resp.raise_for_status()
payload = resp.json()
if "errors" in payload:
raise RuntimeError(f"GraphQL errors: {payload['errors']}")
return payload["data"]
# ── Discover indicators for AUD ──────────────────────────────────────────────
catalogue = gql('{ dataCatalogue(currency: "AUD") { indicators { slug name frequency } } }')
for ind in catalogue["dataCatalogue"]["indicators"]:
print(f" {ind['slug']:25s} {ind['name']} ({ind['frequency']})")
# ── Fetch EUR inflation + GBP policy rate in one round-trip ─────────────────
batch = gql('''
query {
eurInflation: announcements(currency: "EUR", indicator: "inflation") {
currency indicator data { date val pctChange }
}
gbpRate: announcements(currency: "GBP", indicator: "policy_rate") {
currency indicator data { date val }
}
}
''')
eur_latest = batch["eurInflation"]["data"][-1]
gbp_latest = batch["gbpRate"]["data"][-1]
print(f"EUR CPI {eur_latest['date']}: {eur_latest['val']}% ({eur_latest['pctChange']:+.2f}% MoM)")
print(f"GBP Rate {gbp_latest['date']}: {gbp_latest['val']}%")
步骤7 JavaScript / Node.js 客户端
这位原住民 fetch API (Node.js 18+) 处理 GraphQL 请求,使用最小的热水器.模式反映了上面的 Python 助手.
const GRAPHQL_URL = "https://fxmacrodata.com/api/v1/graphql";
const API_KEY = "YOUR_API_KEY"; // set to "" for free USD/catalogue endpoints
async function gql(query) {
const url = API_KEY ? `${GRAPHQL_URL}?api_key=${API_KEY}` : GRAPHQL_URL;
const resp = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query }),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const payload = await resp.json();
if (payload.errors) throw new Error(JSON.stringify(payload.errors));
return payload.data;
}
// Batched query: EUR inflation + calendar
const data = await gql(`
query {
eurInflation: announcements(currency: "EUR", indicator: "inflation") {
data { date val pctChange }
}
eurCalendar: calendar(currency: "EUR", indicator: "inflation") {
data { release announcementDatetime }
}
}
`);
const latest = data.eurInflation.data.at(-1);
const nextRelease = data.eurCalendar.data[0];
console.log(`EUR CPI ${latest.date}: ${latest.val}% (${latest.pctChange > 0 ? "+" : ""}${latest.pctChange?.toFixed(2)}% MoM)`);
if (nextRelease) {
const dt = new Date(nextRelease.announcementDatetime * 1000).toISOString();
console.log(`Next EUR inflation release: ${dt}`);
}
步骤8 优雅地处理错误
GraphQL 返回 HTTP 200 即使查询字段失败. 错误出现在顶级字段中.
errors 它们的位置在任何部分的位置. data 检查这个数组使用之前的响应一个失败的别名在批次查询不会阻止其他别名返回数据.
payload = resp.json()
# Partial success: some aliases may have data, others may have errors
if "errors" in payload:
for err in payload["errors"]:
print(f"[GraphQL error] {err.get('message')} — path: {err.get('path')}")
data = payload.get("data") or {}
if "eurInflation" in data and data["eurInflation"]:
process(data["eurInflation"])
信息通报
- 没有支持的货币 没有
errors列表将包含这样的消息 "不支持货币:XYZ"检查您的货币代码与 应用程序文件现在我们要做什么? - 无效的指示器 运行一个
dataCatalogue查询首先确认指标存在于目标货币. - 认证错误 HTTP 401 或 GraphQL 错误引用一个不有效的密钥. 验证
api_key附加到URL,而不是JSON体.
总结情况
你所取得的成就
- ✓ 发送您的第一个 GraphQL 查询到
https://fxmacrodata.com/api/v1/graphql - ✓ 使用
dataCatalogue发现货币的每一个可用指标 - ✓使用选的历史数据获取
startDate现在我endDate论点 - ✓ 查找即将发布的时间
calendar查询 - ✓使用命名别名组合多个独立查询到单个HTTP POST
- ✓ 在Python和JavaScript中建立可重复使用的GraphQL辅助函数
- ✓处理部分错误,而没有丢弃其他号的有效数据
下一步
现在你可以流地查询GraphQL终端点, 几个自然的扩展将使你的集成生产准备好:
-
按时间安排查询. 结合了
calendar查询与时间表模式描述在 如何使用发布日历API来安排指标检索 在每次公告之前醒来,然后开火announcements查询新数据发布时. -
探索整个模式. 如果您可以访问开发环境,
ENABLE_GRAPHIQL=true打开/api/v1/graphql在浏览器中使用内置的GraphiQL IDE,为每个字段提供自动填写和直线文档. -
扩大您的覆盖范围, 现在就跑吧.
dataCatalogue对于每个支持货币美元,欧元,英,澳元,CAD,日元,瑞郎和新西兰元,以建立一个全面的图像,了解G8外汇世界中可用的数据.
汇率数据团队