全国油价批量拉取 API:一次拿回各省市区六种油品价格

要建本地油价库、做全国价格监控大屏、或者给测算模型灌一批基准价,逐地区逐个油品去查显然不现实:几百次请求、还要自己拼地区清单。oilprice.all 就是为这种「一次拉全」场景准备的:一个 GET 请求,不带任何参数,返回当前生效批次下全部地区的价格记录,覆盖 0# / -10# / -35# 柴油与 92# / 95# / 98# 汽油共六种油品。

需要提醒的是:这是按次计费的重接口(5 元/次),鉴权通过即扣费,所以它只适合低频批量同步,不适合放在用户请求链路上。

接口速览

一、哪些业务需要这一步

二、请求参数

2.1 请求头

2.2 业务参数

无。 接口固定返回当前生效批次的全部启用记录,不支持按地区筛选、不支持分页、不支持排序定制。

如果你只需要某个地区某一个油品的价格,用 oilprice.realtime(0.01 元/次)更划算,不要浪费一次全量调用。

三、返回字段

3.1 顶层与 data

data 字段:

3.2 list[] 明细字段

3.3 三个必须理解的口径

  1. null 的价格 ≠ 0 元。某油品字段为 null 表示该地区没有维护这个油品的价格(例如南方多数地区不供应 -35# 柴油),展示时应写「暂无」而不是 0。
  2. 地区为 null 是统一定价。city 为 null = 全省统一价;district 为 null = 全市统一价。两者都为 null 就是省级统一价记录。
  3. effectiveDate 与 dataUpdateTime 不是一回事。前者是价格开始生效的日期,后者是数据的维护时间,判断数据新旧要看 dataUpdateTime。

内部字段(id / status / deleted)不对外返回。

四、调用示例

4.1 curl

curl -s "https://api.xujian.tech/openapi/oilprice/all" \
  -H "X-API-Key: 你的APIKey"

4.2 Java(Hutool)

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class OilPriceAllClient {

    private static final String API_URL = "https://api.xujian.tech/openapi/oilprice/all";

    /**
     * 拉取当前生效批次的全部油价
     *
     * @param apiKey 开发者 API Key
     * @return data 节点;失败返回 null(鉴权失败不扣费,业务失败也已扣费)
     */
    public static JSONObject all(String apiKey) {
        JSONObject json = JSONUtil.parseObj(
                HttpRequest.get(API_URL)
                        .header("X-API-Key", apiKey)
                        .timeout(30000)
                        .execute().body());
        if (json.getInt("code") == null || json.getInt("code") != 0) {
            System.out.println("查询失败:" + json.getStr("msg"));
            return null;
        }
        return json.getJSONObject("data");
    }

    public static void main(String[] args) {
        JSONObject data = all("你的APIKey");
        if (data == null) {
            return;
        }
        JSONArray list = data.getJSONArray("list");
        System.out.println("生效日期:" + data.getStr("effectiveDate") + ",共 " + list.size() + " 条");
        for (int i = 0; i < list.size(); i++) {
            JSONObject row = list.getJSONObject(i);
            System.out.printf("%s %s 92#: %s 0#柴油: %s%n",
                    row.getStr("province"), row.getStr("city"),
                    row.getBigDecimal("priceGas92"), row.getBigDecimal("priceDiesel0"));
        }
    }
}

4.3 Python

import requests


def oil_all(api_key: str):
    """返回 data 节点;失败返回 None"""
    resp = requests.get(
        "https://api.xujian.tech/openapi/oilprice/all",
        headers={"X-API-Key": api_key},
        timeout=30,
    )
    result = resp.json()
    if result.get("code") != 0:
        print("查询失败:", result.get("msg"))
        return None
    return result["data"]


if __name__ == "__main__":
    data = oil_all("你的APIKey")
    if data:
        print(data["effectiveDate"], len(data["list"]))

4.4 JavaScript

async function oilAll(apiKey) {
  const resp = await fetch("https://api.xujian.tech/openapi/oilprice/all", {
    headers: { "X-API-Key": apiKey }
  });
  const result = await resp.json();
  if (result.code !== 0) {
    throw new Error(result.msg);
  }
  return result.data;
}

五、返回示例

{
  "code": 0,
  "msg": "success",
  "data": {
    "effectiveDate": "2026-09-24",
    "total": 2,
    "list": [
      {
        "effectiveDate": "2026-09-24",
        "provinceCode": "500000",
        "province": "重庆市",
        "cityCode": null,
        "city": null,
        "districtCode": null,
        "district": null,
        "priceDiesel0": 7.28,
        "priceDiesel10": 7.72,
        "priceDiesel35": 8.05,
        "priceGas92": 7.86,
        "priceGas95": 8.31,
        "priceGas98": 9.36,
        "dataUpdateTime": "2026-09-24 09:00:00"
      },
      {
        "effectiveDate": "2026-09-24",
        "provinceCode": "330000",
        "province": "浙江省",
        "cityCode": "330100",
        "city": "杭州市",
        "districtCode": null,
        "district": null,
        "priceDiesel0": 7.25,
        "priceDiesel10": 7.69,
        "priceDiesel35": null,
        "priceGas92": 7.83,
        "priceGas95": 8.28,
        "priceGas98": 9.32,
        "dataUpdateTime": "2026-09-24 09:00:00"
      }
    ],
    "apiCode": "oilprice.all",
    "apiName": "全量发改委价格查询",
    "chargeType": "PER_CALL",
    "balance": 94.9900,
    "costMs": 12
  }
}

当前没有生效批次时,不是失败,而是空列表(仍已扣费):

{
  "code": 0,
  "msg": "success",
  "data": {
    "effectiveDate": null,
    "total": 0,
    "list": [],
    "apiCode": "oilprice.all",
    "apiName": "全量发改委价格查询",
    "chargeType": "PER_CALL",
    "balance": 94.9900,
    "costMs": 8
  }
}

六、可直接复用的两段代码

6.1 落库前归一化(把 null 地区还原成统一定价标记)

def normalize(rows):
    """把 null 的地区字段转成可落库的标记,价格 null 保持 None 不写 0"""
    out = []
    for r in rows:
        out.append({
            "effective_date": r["effectiveDate"],
            "province_code": r["provinceCode"],
            "province": r["province"],
            "city_code": r["cityCode"] or "000000",
            "city": r["city"] or "全省统一价",
            "district_code": r["districtCode"] or "000000",
            "district": r["district"] or "全市统一价",
            "price_gas92": r["priceGas92"],
            "price_gas95": r["priceGas95"],
            "price_gas98": r["priceGas98"],
            "price_diesel0": r["priceDiesel0"],
            "price_diesel10": r["priceDiesel10"],
            "price_diesel35": r["priceDiesel35"],
            "data_update_time": r["dataUpdateTime"],
        })
    return out

6.2 按生效日期做幂等,避免重复拉

import json
import os

STATE = "oil_all_state.json"


def sync_once(api_key: str):
    """同一个 effectiveDate 只写一次库,重复执行直接跳过"""
    data = oil_all(api_key)
    if not data or not data.get("effectiveDate"):
        return 0

    state = {}
    if os.path.exists(STATE):
        state = json.load(open(STATE, encoding="utf-8"))
    if state.get("effective_date") == data["effectiveDate"]:
        print("批次未变化,跳过")
        return 0

    rows = normalize(data["list"])
    # TODO: 写入自己的库
    json.dump({"effective_date": data["effectiveDate"], "total": len(rows)},
              open(STATE, "w", encoding="utf-8"))
    return len(rows)

七、实践建议

  1. 必须缓存,不要每次业务请求都打。5 元/次的重接口,一次调价周期内拉一次即可。
  2. 不要放在用户请求链路上。走后台定时任务,用户侧查本地库。
  3. 用 effectiveDate 做幂等。同批次只写一次,任务重跑不会产生费用以外的脏数据。
  4. 先确认价格再决定要不要用。5 元/次不便宜,如果你只关心 3 个省份,oilprice.realtime(0.01 元/次)查 3 次更省。
  5. 价格 null 不要当 0。展示写「暂无」,计算时跳过,否则会把成本算成 0。
  6. 地区 null 要还原语义。全省统一价 / 全市统一价是展示信息,落库时建议写成明确标记而不是留空。
  7. 响应体可能较大。按市维护时是数百条记录,超时建议设到 30 秒,客户端按流式或分批处理。
  8. 配合调价周期接口排程。oilprice.cycle 免费,用它算出调价日,只在调价日当天拉一次全量。

八、错误码与排查

计费时机要特别注意:本接口先鉴权扣费、再查数据,因此参数错误、查不到数据这类情况都已计费。这一点与地址解析、企业查询那类「查不到不收费」的接口不同,不要把两套说法混用。

九、计费与接入

接入流程:注册开发者账号 → 控制台创建 API Key → 请求头带上 X-API-Key 即可调用,无需签名或加密。控制台可查看调用量、扣费流水与余额。

服务站点:api.xujian.tech(纯文本域名,不做跳转)。接口试用、数据与充值咨询可在控制台提交工单,或联系 Vxujian_cq。

十、小结

oilprice.all 的定位很清晰:用一次较高的成本,换一批完整、口径统一的数据。它不适合高频调用,但在建库、大屏、批量测算这类场景里,比循环调用单地区接口省事得多,也更容易保证数据批次一致。

使用时要记住四条:

  • 5 元/次,鉴权通过即扣费:必须缓存、必须幂等、不能放在用户链路上;
  • 只返回当前生效批次:未来生效的价格查不到,想提前拿要用 oilprice.advance;
  • null 有两种含义:地区 null 是统一定价,价格 null 是未维护,都不能当 0;
  • 没有分页:一次返回全部,注意响应体大小与超时设置。

配套接口:oilprice.realtime(0.01 元/次,单地区单油品)、oilprice.cycle(免费,调价日期列表)、oilprice.advance(按年付费,提前 2 小时拿新价)。

扫码添加微信
联系作者 · 微信二维码

微信号:xujian_cq

接口对接、充值 / 授权、定制需求都可以直接聊