交互式示例
通过多语言的分步代码示例,边做边学
入门
5 分钟
买下你的第一张面单
报价、建草稿、购买 —— 拿到一张真实面单的三次调用
进阶
10 分钟
查询运输状态
读取一票货的当前状态,并注册 webhook,省掉轮询消耗的请求额度
高级
15 分钟
批量买面单
一次请求最多 25 张 —— 限额只扣 1 次而不是 75 次
买下你的第一张面单
报价、建草稿、购买 —— 拿到一张真实面单的三次调用
入门
5 分钟
node >= 18 — fetch is built in, no SDK neededconst API = 'https://atoship.com/api/v1';
const KEY = process.env.ATOSHIP_API_KEY;
async function call(path, body) {
const res = await fetch(API + path, {
method: 'POST',
headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body ?? {})
});
const data = await res.json();
// Every error carries error.code (UPPER_SNAKE_CASE). Branch on that —
// never on the message text, which is free to change.
if (!res.ok) throw new Error(`${data.error?.code}: ${data.error?.message}`);
return data;
}
const shipment = {
from_address: {
name: 'Warehouse', street1: '417 Montgomery St',
city: 'San Francisco', state: 'CA', zip: '94104', country: 'US'
},
to_address: {
name: 'Ada Lovelace', street1: '1355 Market St',
city: 'San Francisco', state: 'CA', zip: '94103', country: 'US'
},
parcel: {
length: 10, width: 8, height: 6,
weight: 32, weight_unit: 'oz', dimension_unit: 'in'
}
};
async function buyLabel() {
// 1. Quote. Rating is free — it spends nothing and commits to nothing.
const { data: rates } = await call('/rates', shipment);
if (!rates.length) throw new Error('No rates for this shipment');
const cheapest = rates.reduce((a, b) => (a.rate <= b.rate ? a : b));
console.log(`${cheapest.carrier} ${cheapest.service} $${cheapest.rate}`);
// 2. Create the label as a DRAFT. Still nothing charged.
const draft = await call('/labels', { ...shipment, rate_id: cheapest.id });
console.log(draft.id, draft.status); // 'draft', label_url still null
// 3. Purchase. THIS is the call that spends money.
const label = await call(`/labels/${draft.id}/purchase`);
console.log(label.status, label.tracking_number, label.label_url);
return label;
}
buyLabel().catch((err) => console.error(err.message));实用技巧:
- 报价是免费的,想查多少次都行 —— 只有购买那一步才花钱。
- 购买时带上报价返回的 rate_id。不带,服务端会自己挑服务,通常不是你刚才比过价的那个。
- 面单先以草稿创建,所以地址有问题会在扣款之前就失败。