Polovni Automobili API 调用计划与费用
一次典型的查询分四步:
- 从 brands 取得品牌标签。
- 用 models 查到车型的写法。
- 执行带筛选条件的搜索并逐页读取。
- 用 listing 打开你关心的广告。
前两步的结果不取决于后面的搜索,所以每个品牌调用一次 brands 和一次 models,就能用于许多次搜索;如果要做筛选表单,filter-options 也属于这一准备阶段。费用按调用累加:一次 models 调用 4.5 积分,一次 brands 调用、每个搜索页和每条 listing 各 3 积分。
因此,若查找柴油 Golf 时结果在一页(最多 200 行)以内,再完整读取其中五条,总费用为 3 + 4.5 + 3 + 15 = 25.5 积分。第一个示例按这个计划执行,只有一处不同:标签 Volkswagen 已知,所以跳过 brands;搜索使用的车型 Golf 来自 models 响应;只因第 1 页报告了 has_more 才发送第 2 页;listing 的 ad_id 从第 1 页的某一行复制。
确定品牌标签与车型写法
品牌值是精确标签。确定标签与车型写法的步骤如下:
- 从 brands 条目中取
label而不是slug,并原样发送,因为带连字符的变体会被拒绝。 - 用这个标签调用 models。响应列出在采样广告中找到的
{model, ads_seen}对,并通过ads_sampled和sample_coverage_pct说明读取了多少广告。 - 如果预期的车型没有出现,而覆盖率低于 100,就用更大的
sample_pages再调用一次,最大为 10。 - 把返回的每个
model字符串原样放进 search 的model数组;放入两个或更多名称,就能一次搜索多个车型。
做筛选表单时,filter-options 会提供允许的取值,以及可在旁边显示的塞尔维亚语标签。
把需求转换为搜索筛选
每项需求对应一个字段:
- 12,000 的预算写成
price_max: 12000,单位是广告自身的币种;请检查每一行的price_currency,并设置only_with_price: true来跳过没有报价的广告。 - 马力限制要先换算成千瓦,再填入
power_kw_min或power_kw_max。 - 四门或五门写成
doors: "5",必须是字符串。 - 多种燃料放进同一个
fuel数组,命中任意一种即可;但排放等级只接受一个值,所以欧 5 和欧 6 车辆需要分两次搜索。
search 契约没有为配置项声明字段;需要按配置筛选时,请改为在每条 listing 的 equipment 数组上自行筛选。
在 750 页以内分页读取结果
逐页读取结果的步骤如下:
- 从
page: 1和最大的每页行数page_size: 200开始。 - 每次响应后保存
cars中的行;top_ads是付费推广而不是搜索命中,应单独存放。 - 只要
has_more为 true 且下一页页码在reachable_pages以内,就继续读取。
页码止于 750,请求第 751 页会被拒绝,不收费。当 total_results 大于 reachable_results 时,把搜索拆成范围更窄的多次搜索,例如按 year_min 与 year_max 划分年份段,或按燃料划分,再按 ad_id 合并结果行。每一页都是一次单独计费的调用,所以按每页 200 行读取 3,000 行的结果需要 15 次调用,共 45 积分。
打开你需要的广告
从搜索结果中挑选行,把每个 ad_id 字符串按返回时的原样发给 listing。除非希望 slug 体现在返回的 URL 中,否则不要传入它。已删除的广告会返回不扣费的失败,记录下来并继续处理即可,不必重试。
各次 listing 调用彼此独立:为每次调用分配单独的 Idempotency-Key 并控制节奏:你的账户允许突发 10 个请求,之后每 0.2 秒恢复 1 个;此外还有所有客户共享的限额,所以即使按这个节奏也可能收到 RATE_LIMITED 或 CONCURRENCY_LIMIT(429)。等待 Retry-After 给出的秒数后,用同一个 key 重发。
超时与重试:不重复付费
每个意图创建一个 Idempotency-Key,并在发送前把它与确切的操作和 JSON 一起保存。如果调用以 OPERATION_TIMEOUT(504)、OUTCOME_UNKNOWN 或 RESULT_INVALID 结束,说明操作可能已经执行:价格被预留而非扣除,15 分钟后释放。不要换新的 key 再次发送这个意图。
使用同一 key 原样重发不会第二次执行请求;预留期间返回 REQUEST_PENDING(409),释放后返回 OUTCOME_UNKNOWN_RELEASED(504)且不扣费,超时之后才到达的结果也永远不会交付。直到这时再决定是否值得用新 key 发起新请求,并清楚它成功后会扣费。REQUEST_REJECTED 这类明确的失败,需要用新 key 发送修正后的请求。
示例 2:用 JavaScript 实现循环
第二个示例针对桩响应执行同一计划,所以不需要密钥,也不发起网络请求。post() 为每个请求组装操作路径、新的 Idempotency-Key 和放在 body 下的输入;send() 代替网络,并像网关一样按 key 保存每次响应。代码依次:
- 调用 brands 取得品牌标签
- 选出
ads_seen最多的车型 - 在
has_more为 true 时逐页搜索并收集 260 行 - 用 listing 打开前两行
第二次 listing 超时;代码用同一个 key 重发一次,得到 REQUEST_PENDING(409)后就此停止。它会打印选定的车型、行数、已打开的广告、待定的请求以及共花费的 16.5 积分,因为超时的那次调用没有扣费。
[
{
"body": {
"brand": "Volkswagen",
"sample_pages": 5
}
},
{
"body": {
"brand": "Volkswagen",
"model": [
"Golf"
],
"fuel": [
"diesel"
],
"year_min": 2015,
"mileage_max": 150000,
"price_max": 12000,
"page": 1,
"page_size": 200
}
},
{
"body": {
"brand": "Volkswagen",
"model": [
"Golf"
],
"fuel": [
"diesel"
],
"year_min": 2015,
"mileage_max": 150000,
"price_max": 12000,
"page": 2,
"page_size": 200
}
},
{
"body": {
"ad_id": "9182736405"
}
}
]// Brands → models → search pages → listing, run against stubbed replies: no API key and no network calls.
// 品牌 → 车型 → 分页搜索 → 广告详情;响应为内存中的桩数据,不需要密钥,也不发起网络请求。
const PRICE = { 'polovniautomobili-models': '450' }; // Every other operation costs '300' credit units.
const row = (i) => ({ ad_id: String(9182736000 + i), brand: 'Volkswagen', model: 'Golf',
year: 2016, price: 9900 + i, price_currency: 'EUR', mileage_km: 140000 - i, fuel: 'diesel' });
const stub = {
'polovniautomobili-brands': () => ({ count: 2, total_ads: 2400, brands: [
{ brand: 'Volkswagen', label: 'Volkswagen', slug: 'volkswagen' },
{ brand: 'Škoda', label: 'Škoda', slug: 'skoda' }] }),
'polovniautomobili-models': (body) => ({ brand: body.brand, brand_ads: 1800, ads_sampled: 1000,
sample_pages: body.sample_pages, sample_coverage_pct: 55.6, count: 2,
models: [{ model: 'Passat', ads_seen: 310 }, { model: 'Golf', ads_seen: 420 }] }),
'polovniautomobili-search': (body) => ({ total_results: 260, page: body.page,
page_size: body.page_size, pages: 2, has_more: body.page < 2,
cars: Array.from({ length: body.page === 1 ? 200 : 60 }, (_, i) => row((body.page - 1) * 200 + i)),
top_ads: [] }),
// The second advertisement times out, so the code below shows the same-key check.
'polovniautomobili-listing': (body) => body.ad_id === '9182736001' ? 'timeout'
: { car: { ...row(Number(body.ad_id) - 9182736000), equipment: ['ABS'], images: [] } },
};
const stored = new Map(); // What the gateway keeps per Idempotency-Key.
let requestNumber = 0;
function send(request) { // Stands in for fetch(); returns { status, json }.
const key = request.headers['Idempotency-Key'];
if (stored.has(key)) return stored.get(key); // Same key: the recorded state, never a second run.
const action = request.path.split('/').pop();
const { body } = JSON.parse(request.body);
const out = stub[action](body), requestId = `req-${++requestNumber}`;
if (out === 'timeout') {
stored.set(key, { status: 409, json: { ok: false, error: { code: 'REQUEST_PENDING',
message: 'This request was already dispatched.' },
meta: { requestId, chargedCreditUnits: '0', status: 'uncertain' } } });
return { status: 504, json: { ok: false, error: { code: 'OPERATION_TIMEOUT',
message: 'The operation did not finish in time and may still have run.' },
meta: { requestId, chargedCreditUnits: '0', status: 'uncertain' } } };
}
const reply = { status: 200, json: { ok: true, data: out,
meta: { requestId, chargedCreditUnits: PRICE[action] ?? '300' } } };
stored.set(key, reply);
return reply;
}
let spentUnits = 0;
function post(action, body, key = crypto.randomUUID()) { // One new key per intent.
const request = { method: 'POST', path: `/api/v1/polovniautomobili/${action}`,
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify({ body }) }; // Every input sits under body.
const { status, json } = send(request);
spentUnits += Number(json.meta.chargedCreditUnits);
return { status, json, key };
}
// 1. Brand label (never the slug), then the model with the most ads_seen.
const brand = post('polovniautomobili-brands', {}).json.data.brands
.find((entry) => entry.label === 'Volkswagen').label;
const sampled = post('polovniautomobili-models', { brand, sample_pages: 5 }).json.data;
const model = [...sampled.models].sort((a, b) => b.ads_seen - a.ads_seen)[0].model;
// 2. Search with filters, 200 rows per page, while has_more is true (page numbers stop at 750).
const filters = { brand, model: [model], fuel: ['diesel'], year_min: 2015,
mileage_max: 150000, price_max: 12000 };
const rows = [];
for (let page = 1; page <= 750; page++) {
const { data } = post('polovniautomobili-search', { ...filters, page, page_size: 200 }).json;
rows.push(...data.cars);
if (!data.has_more) break;
}
// 3. Open the first two rows; an uncertain outcome is checked with the SAME key, never retried with a new one.
const opened = [], pending = [];
for (const { ad_id } of rows.slice(0, 2)) {
const first = post('polovniautomobili-listing', { ad_id });
if (first.json.ok) { opened.push(first.json.data.car.ad_id); continue; }
if (first.json.meta.status !== 'uncertain') continue; // A definite failure: nothing charged, move on.
const check = post('polovniautomobili-listing', { ad_id }, first.key);
pending.push({ ad_id, first: first.json.error.code, check: check.json.error.code, status: check.status });
}
console.log({ brand, model, rows: rows.length, opened, pending, spentCredits: spentUnits / 100 });
服务端请求模板
以下服务端模板以此 API 的第一个操作为例,演示认证与请求标识。请根据场景选择操作,并在 API 页面查看其当前可用状态与价格。超时后,使用同一个 Idempotency-Key 重发未改变的请求。
网关请求始终使用 POST。
使用 JSON 对象,按文档将参数放入 path、query、headers 和 body,省略未使用的位置。input.headers 是供操作使用的 JSON 数据,不是浏览器请求头。请勿在此填写凭证。按文档保留 body 的数组、标量或 null;省略与 null 含义不同。
# Server-side only. Set KAKIAPI_API_KEY in your secret manager.
# Every gateway operation is called with POST.
# Only operations shown as enabled on the API page can be called.
# Generate once per intent; retain the same value on status checks.
REQUEST_ID="$(uuidgen)"
curl --request POST 'https://kakiapi.com/api/v1/polovniautomobili/polovniautomobili-brands' \
--header "Content-Type: application/json" \
--header "x-api-key: $KAKIAPI_API_KEY" \
--header "Idempotency-Key: $REQUEST_ID" \
--data '{"body":{}}'接入检查清单
- API 密钥保存在服务端密钥管理器中,从不发送到浏览器。
- 每个请求携带自己的 Idempotency-Key,并保留到请求得到最终结果为止。
- 集成读取 ok 与 error.code,并按错误码表处理每个错误码。
- 使用原标识检查结果不确定的 POST,绝不盲目更换标识重试。
- 已在 API 页面查看该操作的当前可用状态与价格。