Cloudflare调用手册

查找域名的 Zone ID

把自己的根域名转换为 DNS 和缓存接口需要的 Zone ID。

官方资料核对 2026-10-15示例代码,未进行真实接口实测
← 返回平台功能

接入准备

  • 账号能访问目标 Zone;令牌具备 Zone → Zone → Read(接口标识 Zone Zone Read)。

准备环境变量

示例值需要替换为自己的凭证或资源 ID。代码在本机或服务端运行;密钥不应放进公开网页。

CLOUDFLARE_API_TOKEN
使用自定义 API Token,并限制到指定 Zone;不要使用 Global API Key。
终端
export CLOUDFLARE_API_TOKEN='replace_with_scoped_api_token'

以上 export 适用于 macOS / Linux 的终端,在同一终端内运行后续代码。Python 示例保存为 request.py 后执行 python3 request.py。

调用步骤

  1. 01

    登录 Cloudflare 控制台 → My Profile → API Tokens → Create Token → Create Custom Token。

  2. 02

    Permissions 只添加 Zone → Zone → Read;Zone Resources 选择 Include → Specific zone → 你的域名。

  3. 03

    按需要限制客户端 IP、有效时间,确认摘要后生成;只在本地或服务器环境变量保存 CLOUDFLARE_API_TOKEN。

  4. 04

    将下方 name=example.com 改为自己的根域名,例如 example.org;不要填 https:// 或页面路径。

调用 01

按域名查询 Zone

只列出 Token 可访问的 Zone;保存精确匹配域名那一项的 id。

GEThttps://api.cloudflare.com/client/v4/zones?name=example.com&per_page=20&page=1

请求头

Authorization
Bearer ${CLOUDFLARE_API_TOKEN}

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
nameQuerystring可选根域名,示例 example.com 为保留演示域名,必须替换。
per_pageQueryinteger可选每页 5–50 个,本例 20。
pageQueryinteger可选页码从 1 开始。

调用代码

替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。

cURL
# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request GET \
  --url "https://api.cloudflare.com/client/v4/zones?name=example.com&per_page=20&page=1" \
  --header "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}"
Python 3
import json
import os
import re
import urllib.request
import urllib.error

def expand(value):
    return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
                  lambda match: os.environ[match.group(1)], value)

url = expand("https://api.cloudflare.com/client/v4/zones?name=example.com&per_page=20&page=1")
headers = {
    "Authorization": expand("Bearer ${CLOUDFLARE_API_TOKEN}"),
}
data = None
request = urllib.request.Request(url, data=data, headers=headers, method="GET")
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
if isinstance(result, dict) and "success" in result and result["success"] != True:
    raise SystemExit("平台返回业务错误,请结合下方排错说明检查响应")
Node.js
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
  return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
    if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
    return process.env[name];
  });
}

const url = expand("https://api.cloudflare.com/client/v4/zones?name=example.com&per_page=20&page=1");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bearer ${CLOUDFLARE_API_TOKEN}"
}).map(([key, value]) => [key, expand(value)])
);
const response = await fetch(url, {
  method: "GET",
  headers,
  signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));
if (Object.hasOwn(result, "success") && result["success"] !== true) {
  throw new Error('平台返回业务错误,请结合下方排错说明检查响应');
}

返回示例

按官方字段整理的响应结构示意,ID、文本和数字均为虚构,非接口实测结果。取 result[].id,不能用 account.id 代替。 以下为结构示意,非本站实测结果。

JSON
{
  "success": true,
  "errors": [],
  "messages": [],
  "result": [
    {
      "id": "00000000000000000000000000000000",
      "name": "example.com",
      "status": "active",
      "account": {
        "id": "11111111111111111111111111111111",
        "name": "示例账号"
      }
    }
  ],
  "result_info": {
    "page": 1,
    "per_page": 20,
    "total_pages": 1,
    "count": 1,
    "total_count": 1
  }
}

常见错误与排查

HTTP 401 / 403认证或权限校验未通过。
核对 Bearer Token、资源范围、有效期与 IP 限制;读取返回 errors[].message 确认具体原因。
HTTP 429管理 API 触发限流。
遵守 retry-after,降低并发;全局额度与产品专属配额分别检查。

调用注意

  • HTTP 成功后仍检查 success。空列表可表示没有匹配域名,也可能是 Token 资源范围不包含它。
  • 从不同账号批量查询时,官方限制不能一次跨超过 500 个账号列 Zone。

注意事项

  • 一般管理 API 为每用户或账号 Token 每 5 分钟 1,200 次,另有每 IP 每秒 200 次限制;产品端点可能更严格。
  • 这里仅使用域名管理 API;套餐的 DNS/CDN 等资源规则继续适用,不把 Token 本身当成产品套餐。

核验来源

本站按官方资料整理本场景的必要调用步骤与代码,覆盖范围以本页列出的接口为准。官方资料用于追溯规范及查看变更。

  1. 01
  2. 02
    Cloudflare 管理 API 限流核验日期 2026-10-15
  3. 03
    List Zones核验日期 2026-10-15

Cloudflare的其他调用手册

← 返回Cloudflare的全部功能