Node 和 Python 各写一遍:同一批接口的最小封装与降级
Node 和 Python 各写一遍:同一批接口的最小封装与降级
public-apis 仓库不提供 SDK,也不托管任何接口。它就是一张表格:2186 个条目、51 个分类,每行五个字段告�你还剩多少工作量——要不要 Key、是不是 HTTPS、CORS 认不认。真正的坑从你把链接粘进代码那一刻才开始:有的源返回 403 + Cloudflare 挑战页,有的源 HTTP 200 但响应体里写着 success: false,还有的源文档页还在、接口早废。
本文不写"十大免费 API 推荐"。我们直接从 apis.json 里做选型统计,挑出三组真实可用的源,然后用同一套契约在 Python 和 Node 里各写一遍最小封装,重点对比三件事:超时、重试、缓存究竟该放在哪一层,以及当一个源失效时,降级链怎么判断"它真的坏了"。
一、先看清清单的可用面:2186 条里有多少能零配置直接用
仓库的结构比大多数人以为的更工程化。README 是 2720 行的 Markdown 表格,而 apis.json 是它的机器可读镜像,每条记录长这样:
{"category": "Currency Exchange", "name": "Frankfurter",
"url": "https://frankfurter.dev", "desc": "Exchange rates, currency conversion and time series",
"auth": "No", "https": "Yes", "cors": "Yes", "line": 600}
字段 line 直接指回 README 的行号,这对 CI 很关键——PR 校验失败时能定位到具体表格行,而不是让人在 32 万字符里搜索。
对这份快照做一次聚合,几个数字值得记住:
| 维度 | 分布 |
|---|---|
| 总条目 / 分类数 | 2186 / 51 |
| Auth | No 1048、`apiKey` 978、`OAuth` 150、`X-Mashape-Key` 6、`User-Agent` 3 |
| HTTPS | Yes 2097、No 88 |
| CORS | Unknown 1035、Yes 892、No 258 |
| 零 Key + HTTPS + CORS=Yes | 525 |
| 零 Key + HTTPS + CORS=Unknown | 359 |
apiKey + CORS=Yes |
340 |
结论很直接:能"拿 URL 就打"的候选只有 525 条,不到四分之一。另有 1035 条 CORS 标着 Unknown,这意味着它们能不能在浏览器里用,取决于你愿不愿意自己发一次 OPTIONS 预检去验证,而不是相信清单。
还有一个数据质量问题必须提前处理:CORS=Unknown 里有一条值写成 `Unknown`、HTTPS 里有一条写成 `Yes`、Auth 里有一条写成 `No`(README 第 2330 行的 QiuXiaoCe Football)。而 scripts/validate/format.py 的白名单是硬编码的:
auth_keys = ['apiKey', 'OAuth', 'X-Mashape-Key', 'User-Agent', 'No']
https_keys = ['Yes', 'No']
cors_keys = ['Yes', 'No', 'Unknown']
auth 字段除了 No 之外必须用反引号包裹,https/cors 则不允许反引号。所以适配器的第一层不是发请求,而是 normalize:去反引号、转小写、把无法归一的值当作"不可信"直接剔除。清单是数据源,不是可信输入。
同一份 format 校验还定义了表格的硬约束,这决定了你能不能把"源声明"继续用 Markdown 维护:
num_segments = 5
min_entries_per_category = 3
max_description_length = 100
五列、每类至少三条、描述不超 100 字符、同类内按字母序。这些规则由 scripts/github_pull_request.sh 和 .github/workflows/validate_links.yml 在 CI 里强制执行——注意那个脚本的巧妙之处:它 curl 下 PR 的 diff,egrep "+" 只取新增行,再对新增行跑链接校验。只校验增量,这是任何"接口清单"类项目都值得抄的做法。
二、统一抽象:三层契约,错误码直接复用校验脚本的分类
封装的最小可行结构只有三层,多一层都是浪费:
- Contract:统一输出结构 + 统一错误类型。上层业务只认识
Weather,不认识任何字段名差异。 - Adapter:一个源一个函数,负责拼 URL、解字段、做语义校验。
- Chain:编排多个 adapter,按顺序尝试,统一预算与熔断。
错误分类不必重新发明。scripts/validate/links.py 里已经在用一套前缀,直接沿用能省掉大量沟通成本:
except requests.exceptions.SSLError as error:
error_message = f'ERR:SSL: {error} : {link}'
except requests.exceptions.ConnectionError as error:
error_message = f'ERR:CNT: {error} : {link}'
except (TimeoutError, requests.exceptions.ConnectTimeout):
error_message = f'ERR:TMO: {link}'
except requests.exceptions.TooManyRedirects as error:
error_message = f'ERR:TMR: {error} : {link}'
再补两个在线服务才需要的类别:ERR:BLK(被反爬/挑战页拦截)和 ERR:SEM(HTTP 通了但语义不对)。契约在 Python 侧:
# contract.py
from dataclasses import dataclass
from enum import Enum
from typing import Protocol
class Kind(str, Enum):
CLT = "ERR:CLT" # 4xx/5xx
TMO = "ERR:TMO"
CNT = "ERR:CNT"
SSL = "ERR:SSL"
TMR = "ERR:TMR"
BLK = "ERR:BLK" # 挑战页 / 反爬
SEM = "ERR:SEM" # 结构或值域校验失败
UKN = "ERR:UKN"
class SourceError(Exception):
def __init__(self, kind: Kind, source: str, detail: str = ""):
super().__init__(f"{kind.value} {source} {detail}".strip())
self.kind, self.source, self.detail = kind, source, detail
@dataclass(frozen=True)
class Weather:
source: str
temp_c: float
code: int
observed_at: str
class WeatherSource(Protocol):
name: str
def fetch(self, lat: float, lon: float, budget: float) -> Weather: ...
Node 侧是同一份契约的镜像,差别只在语言习惯——用 class extends Error 带 kind 字段,用 number 表示毫秒预算:
// contract.mjs
export const Kind = Object.freeze({
CLT: 'ERR:CLT', TMO: 'ERR:TMO', CNT: 'ERR:CNT', SSL: 'ERR:SSL',
TMR: 'ERR:TMR', BLK: 'ERR:BLK', SEM: 'ERR:SEM', UKN: 'ERR:UKN',
});
export class SourceError extends Error {
constructor(kind, source, detail = '') {
super(`${kind} ${source} ${detail}`.trim());
this.name = 'SourceError';
this.kind = kind; this.source = source; this.detail = detail;
}
}
注意统一的是结构而不是字段映射的实现。适配器内部允许丑陋:wttr.in 返回 temp_C,Open-Meteo 返回 current.temperature_2m,它们各自在 fetch() 里转换,出了这个函数就只有 Weather。这就是"把接口差异收进一层"的真实含义——差异不会消失,只会被限制在一个函数的作用域里。
三、实测:不要用 HTTP 200 判断成败
选三组源做真实验证(单次探测,结果会随网络与对方策略变化):
| 源 | 场景 | 实测结果 |
|---|---|---|
| Open-Meteo | 天气 | 返回合法 JSON,current.temperature_2m 等字段正常 |
Frankfurter /v1/latest |
汇率 | 200,约 0.56s |
Exchangerate.dev /v1/latest |
汇率 | 200,约 1.82s,响应带 sources 逐币种状态 |
| jsDelivr 上的 currency-api | 汇率(静态快照) | 200,约 1.39s |
ipapi.co /json/ |
IP 定位 | 403 + text/html,Cloudflare "Just a moment..." 挑战页 |
REST Countries /v3.1/alpha/jp |
国家信息 | 连接正常,响应体是 {"success": false, "errors": [{"message": "This API version has been deprecated..."}]} |
后两条是教科书级的反例:
- ipapi.co 在清单里标的是
No认证、CORS=Yes,看起来是"最省事"的源,实际从机房出口访问直接被 Cloudflare 拦。如果你的代码写if (res.ok)再res.json(),会得到一个解析异常,错误类型完全指错方向——真正的问题是被拦截,不是 JSON 坏了。 - REST Countries 更阴:它没 5xx、没断连,版本被废弃后用 200 语义的
success: false告诉你"请迁移到 v5"。这类"活着但已经死了"的源,只有语义校验能识别。
顺带说明清单里的注释为什么可信:Exchangerate.host 的描述直接写着 (keyless access ended 2023),并且 Auth 已从 No 改为 `apiKey`。清单会随现实修正,但你的代码不会自动跟着修正——这就是必须有降级链的理由。
Python 侧的语义校验与拦截识别:
import json
CHALLENGE_FLAGS = ("Just a moment", "cf-chl", "Checking your browser",
"DDoS protection by", "cf-spinner")
def is_blocked(status: int, headers, body: str) -> bool:
server = (headers.get("Server") or "").lower()
if status not in (403, 503):
return False
if "cloudflare" not in server and "cloudflare" not in body.lower():
return False
return any(flag in body for flag in CHALLENGE_FLAGS)
def parse_json(resp, source: str):
ctype = (resp.headers.get("Content-Type") or "").lower()
if "json" not in ctype:
raise SourceError(Kind.SEM, source, f"content-type={ctype}")
try:
return json.loads(resp.text)
except ValueError as exc:
raise SourceError(Kind.SEM, source, "invalid json") from exc
def weather_open_meteo(lat, lon, budget) -> Weather:
data = get_json("https://api.open-meteo.com/v1/forecast",
params={"latitude": lat, "longitude": lon,
"current": "temperature_2m,weather_code"},
source="open-meteo", budget=budget)
cur = data.get("current") or {}
temp = cur.get("temperature_2m")
if not isinstance(temp, (int, float)) or not -90 < temp < 60:
raise SourceError(Kind.SEM, "open-meteo", f"temp={temp!r}")
return Weather("open-meteo", float(temp), int(cur.get("weather_code", -1)),
str(cur.get("time", "")))
值域校验(-90 < temp < 60)不是洁癖。免费源常见的一种退化是"字段还在,值变成占位符或 0",只查键存在会把它当成真实数据写进缓存,然后污染下游一整天。
四、超时、重试、缓存:两套实现的位置差异
这一节是全文真正有分歧的地方。Python 和 Node 的默认语义不一样,照抄对方的写法就错。
超时的语义完全不同。 requests 的 timeout=(connect, read) 是连接超时 + 每次读的间隔超时,不是总预算。一个慢速滴流(每秒吐一个字节)的响应可以让 read 计时器反复重置,最终耗时远超你写的数字。所以 Python 侧必须自己维护 deadline:
import random, time, requests
_session = requests.Session()
UA = "public-apis-adapter/0.1 (+https://example.invalid)"
def get_json(url, *, source, budget=6.0, params=None, max_attempts=3):
deadline = time.monotonic() + budget
delay = 0.25
for attempt in range(max_attempts):
remaining = deadline - time.monotonic()
if remaining <= 0.05:
raise SourceError(Kind.TMO, source, "budget exhausted")
try:
resp = _session.get(
url, params=params, timeout=(min(3.0, remaining), remaining),
headers={"User-Agent": UA},
)
except requests.exceptions.SSLError as exc:
raise SourceError(Kind.SSL, source, str(exc)) from exc
except (requests.exceptions.ConnectionError,) as exc:
raise SourceError(Kind.CNT, source, str(exc)) from exc
except (requests.exceptions.Timeout, TimeoutError):
raise SourceError(Kind.TMO, source, "read timeout") from None
except requests.exceptions.TooManyRedirects as exc:
raise SourceError(Kind.TMR, source, str(exc)) from exc
# 读完之后再对一次预算:read 超时管不住"慢慢吐"
if time.monotonic() - (deadline - budget) > budget:
raise SourceError(Kind.TMO, source, "over budget after body")
if resp.status_code == 429 or resp.status_code >= 500:
if attempt == max_attempts - 1:
raise SourceError(Kind.CLT, source, f"status={resp.status_code}")
wait = _retry_after(resp.headers.get("Retry-After"), delay)
if time.monotonic() + wait >= deadline:
raise SourceError(Kind.CLT, source, "no budget left for retry")
time.sleep(wait + random.uniform(0, 0.1))
delay *= 2
continue
if resp.status_code >= 400:
if is_blocked(resp.status_code, resp.headers, resp.text):
raise SourceError(Kind.BLK, source, f"status={resp.status_code}")
raise SourceError(Kind.CLT, source, f"status={resp.status_code}")
return parse_json(resp, source)
raise SourceError(Kind.UKN, source, "attempts exhausted")
Node 侧反过来:AbortSignal.timeout(ms) 是整体预算,一旦触发,连接与 body 读取一起中断,不需要手写 deadline 循环。但要注意 Node 18 内置 fetch 底层 undici 的 headersTimeout / bodyTimeout 默认是分钟级的,等到你的 6 秒业务超时先触发反而不一定——显式传 signal 才是可控的。
const UA = 'public-apis-adapter/0.1 (+https://example.invalid)';
async function getJson(url, { source, budgetMs = 6000, maxAttempts = 3 }) {
const deadline = Date.now() + budgetMs;
let delay = 250;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const remaining = deadline - Date.now();
if (remaining < 50) throw new SourceError(Kind.TMO, source, 'budget exhausted');
let res;
try {
res = await fetch(url, {
signal: AbortSignal.timeout(remaining),
headers: { 'user-agent': UA, accept: 'application/json' },
});
} catch (err) {
const kind = err.name === 'TimeoutError' ? Kind.TMO
: err.cause?.code === 'CERT_HAS_EXPIRED' ? Kind.SSL : Kind.CNT;
throw new SourceError(kind, source, err.message);
}
if (res.status === 429 || res.status >= 500) {
if (attempt === maxAttempts - 1) {
throw new SourceError(Kind.CLT, source, `status=${res.status}`);
}
const wait = retryAfter(res.headers.get('retry-after'), delay);
if (Date.now() + wait >= deadline) {
throw new SourceError(Kind.CLT, source, 'no budget left for retry');
}
await sleep(wait + Math.random() * 100);
delay *= 2;
continue;
}
if (res.status >= 400) {
const body = await res.text();
if (isBlocked(res.status, res.headers, body)) {
throw new SourceError(Kind.BLK, source, `status=${res.status}`);
}
throw new SourceError(Kind.CLT, source, `status=${res.status}`);
}
const text = await res.text();
if (!(res.headers.get('content-type') || '').includes('json')) {
throw new SourceError(Kind.SEM, source, 'content-type');
}
try { return JSON.parse(text); }
catch { throw new SourceError(Kind.SEM, source, 'invalid json'); }
}
}
重试应该放在适配器层,而不是 HTTP 客户端的全局拦截器。 很多人用 HTTPAdapter(max_retries=Retry(...)) 一把梭,问题是:Retry-After 是每个源各自的策略,429 的等待时间和 5xx 的退避曲线没有通用解;更糟的是,全局重试会把"上游已经明确弃用(4xx)"也重试一遍,白白消耗预算。上面两个实现里还有一条硬约束:重试不能把总预算吃穿,Date.now() + wait >= deadline 就直接放弃——降级链要的是"快速失败换下一个源",不是"在一个源上死磕"。
缓存的位置差异更明显。 Python 服务通常跑 gunicorn/uwsgi 多 worker,进程内 dict 的命中率会被 worker 数量整除;而 Node 单进程单事件循环,一个 Map 就是全局缓存,还能顺手做 single-flight(同一个 key 的并发请求共享一个 Promise),代价几乎为零:
const cache = new Map(); // key -> { value, expires }
const inflight = new Map(); // key -> Promise
async function cached(key, ttlMs, producer) {
const hit = cache.get(key);
if (hit && hit.expires > Date.now()) return hit.value;
if (inflight.has(key)) return inflight.get(key);
const task = producer()
.then((value) => { cache.set(key, { value, expires: Date.now() + ttlMs }); return value; })
.finally(() => inflight.delete(key));
inflight.set(key, task);
return task;
}
Python 侧要得到同样的语义,要么把缓存外移到 Redis,要么显式加锁 + 按 key 记账:
import threading
_lock = threading.Lock()
_cache: dict[str, tuple[float, object]] = {}
def cached(key: str, ttl: float, producer):
now = time.monotonic()
with _lock:
hit = _cache.get(key)
if hit and hit[0] > now:
return hit[1]
value = producer()
with _lock:
_cache[key] = (now + ttl, value)
return value
缓存键的设计比实现更容易出错。天气的 key 必须包含坐标精度:Open-Meteo 会把 39.9042 吸附到格点,同一城市不同小数位会命中不同的上游缓存;如果 key 用原始浮点,你的缓存命中率会被无意义的精度差异吃掉。汇率的 key 必须包含 base 与 symbols 集合(排序后再序列化),否则 USD→CNY 和 CNY→USD 会串。
五、接口失效时如何自动切换:把"哪个源坏了"变成状态机
降级链的实现本身很短,难的是判断什么时候该切。基于上面的错误分类,规则可以写死:
ERR:BLK、ERR:TMO、ERR:CNT、ERR:CLT(5xx/429)→ 换源,并对该源记一次失败。ERR:CLT(401/403/404)→ 换源,且用长熔断。这类错误几乎总意味着"Key 没了 / 路径改了 / 服务下线",短期重试毫无意义。ERR:SEM→ 换源。数据形状不对和连接失败一样不可用。- 参数类错误(例如非法坐标)不应该触发换源,那是调用方的问题,换十个源也一样错。
Python 的链:
def weather(lat: float, lon: float, *, budget: float = 6.0) -> Weather:
deadline = time.monotonic() + budget
errors: list[SourceError] = []
for source in breaker.filter(WEATHER_CHAIN):
remaining = deadline - time.monotonic()
if remaining < 0.2:
break
try:
return source.fetch(lat, lon, min(remaining, 3.0))
except SourceError as exc:
breaker.record(exc)
errors.append(exc)
raise AggregateError(errors, "all weather sources failed") from errors[-1]
关键在 min(remaining, 3.0):总预算与单源上限分开。如果每个源都拿完整剩余预算,第一个慢源就会把时间吃光,排在后面的备用源永远没机会被调用——"有备用但用不上"是降级链最常见的失效模式。
Node 的链结构相同,只是用 AggregateError 聚合:
export async function weather(lat, lon, { budgetMs = 6000 } = {}) {
const errors = [];
const deadline = Date.now() + budgetMs;
for (const source of breaker.filter(WEATHER_CHAIN)) {
const remaining = deadline - Date.now();
if (remaining < 200) break;
try {
return await source.fetch(lat, lon, Math.min(remaining, 3000));
} catch (err) {
if (!(err instanceof SourceError)) throw err;
breaker.record(err);
errors.push(err);
}
}
throw new AggregateError(errors, `weather failed: ${errors.map((e) => e.kind).join(',')}`);
}
熔断器只需要两个计数器加一个时间戳:连续失败到阈值就 open,open 期直接跳过(不要"再试一次看看",那会把恢复时间拖长),到期进入 half-open 放一个请求探路,成功则清零。真正需要小心的是计数口径:把 ERR:SEM 和 ERR:TMO 混在一个计数器里,会让一个偶发的数据结构变更直接熔断掉本来健康的源。
健康探针可以直接借鉴 scripts/validate/links.py 里的思路,那段代码已经考虑过"403 不一定是挂了,可能是 Cloudflare 挡了爬虫":
if code in [403, 503] and server == 'cloudflare':
html = resp.text
flags_found = [flag in html for flag in cloudflare_flags]
但复制到生产前必须修三处边界,否则误判率很高:
server == 'cloudflare'是精确等值比较,实际响应头常是cloudflare、cloudflare-nginx或直接缺失,改成'cloudflare' in (server or '').lower()。- scripts/validate/links.py 的
get_host_from_link()用的是if/elif链:URL 同时含/和?时只截路径,query 会残留进 host。生产代码里请直接用urllib.parse(Python)或new URL()(Node)。 - 手动设置
Host请求头在少数 CDN 与 HTTP/2 场景下会直接拿到 400,探测脚本可以这么做,业务请求不要学。
另外,那个脚本对单个链接只发一次请求、统一 timeout=25——这是批量巡检的正确取舍(几千条链接,重试会让 CI 时间不可控);而在线服务是单次请求语义,必须重试 + 熔断。同一个仓库里两种策略都对,因为目标函数不同。
六、把封装沉淀成可复用的模板
最后一步是把"选型"变成"声明"。既然 apis.json 已经是机器可读的,就不要手写注册表——直接从清单里筛出候选,生成 sources 的骨架,人只补 parse 函数:
import json
def candidates(category: str, *, require_cors: bool = True):
rows = json.load(open("apis.json", encoding="utf-8"))
for row in rows:
auth = row["auth"].strip("`")
cors = row["cors"].strip("`")
https = row["https"].strip("`")
if row["category"] != category or auth != "No":
continue
if https != "Yes" or (require_cors and cors != "Yes"):
continue
yield {"name": row["name"], "url": row["url"],
"readme_line": row["line"], "auth": auth, "cors": cors}
这段脚本在真实数据上会给出:天气 22 条零认证候选、汇率 15 条、地理编码 24 条(零认证且 CORS 明确为 Yes)。readme_line 一并带出来,注释里写 # README:600,将来这个源下线时,你能在一分钟内找到该改哪一行、该给仓库提什么 PR。
模板的落地形态建议是这样一张表,而不是一堆散落的类:
| 层 | 职责 | 允许变化 |
|---|---|---|
清单(apis.json / README 表格) |
记录源的元信息与可用性承诺 | 随社区 PR 更新 |
| Registry | 从清单筛选出的有序候选,含每源超时与 TTL | 每次上线前重新生成 |
| Adapter | URL 拼装、字段映射、语义校验 | 每个源一个函数,只在此处脏 |
| Chain / Breaker | 预算分配、换源、熔断、错误聚合 | 全项目共用一份 |
新增一个源的成本因此被压到两处:清单里加一行 Markdown(遵守五列、字母序、描述 ≤100 字符,CI 会替你检查),代码里加一个 fetch()。清单就是注册表,代码不再维护第二份 URL 列表——这是这个仓库最值得借鉴的工程习惯,也是"封装"和"抄链接"的分界线。
回到标题:Node 和 Python 各写一遍,真正不同的不是语法,而是三个运行时事实——requests 的读超时不是总预算,Node 的 AbortSignal 是;Python 多 worker 让进程内缓存打折,Node 的单事件循环让 single-flight 几乎免费;两边的 4xx/5xx 分类可以共用一套 ERR:* 词表,但重试与熔断必须挂在适配器上,挂在 HTTP 客户端上就会把"该换源"变成"该等更久"。
清单里那 525 条零 Key 可直连的接口是起点,不是保障。把它们当成一组会随时退化的依赖,用统一的契约、语义校验和带预算的降级链兜住,才是"用免费 API"和"被免费 API 用"的区别。