Skip to the content
YallaRoute

Guide · Systems and measurement

Delivery API integration for a web shop: a primer

A primer for the developer connecting a web shop to a delivery company's API: the four calls that matter, keys, idempotent booking, errors, rate limits, signed webhooks and a test plan, with YallaRoute's API as the worked example.

13 min readUpdated 11 sections

In short

  • There are four touchpoints: a quote at checkout, a booking when payment succeeds, a label for the parcel, and status updates back to the order.
  • Send an idempotency key with every booking, so that a retry after a timeout cannot create a second delivery.
  • Take status from webhooks. Verify the signature on the raw body, answer fast, and treat every event as possibly duplicated or out of order.
  • Keep the API key on your server. Nothing in the browser or a mobile app should ever hold it.

The four touchpoints

A delivery integration looks large and is mostly four moments in the life of an order. Get these right and the rest is error handling.

The four touchpoints between a web shop and a delivery API
TouchpointWhenCallWhat you store
QuoteAt checkout, once the address is knownPOST /rates/quoteThe price and window you showed. Nothing is stored on the delivery side
BookWhen payment is confirmedPOST /shipments with an Idempotency-KeyThe tracking number, tracking link and status, against your order
Label and collectionWhen the order is packedGET /shipments/{id}/labelThe printed label, or the barcode on your own packing slip
Tracking and statusFrom booking to deliveryWebhooks, with GET /shipments/{id} as a fallbackOrder status, times and proof of delivery details

The examples use the API that every YallaRoute workspace exposes, which a delivery company running on YallaRoute gives to its business customers. Paths are relative to a base such as https://YOUR-DELIVERY-COMPANY.example/api/v1. Other delivery APIs differ in names and agree on the ideas.

Every booking carries an address object: lines, city, region, postal code where the country uses one, country, or coordinates. Field names differ between APIs and versions, so the samples below mark that part with a comment.

Authentication and keys

Requests are authenticated with a secret key sent as a bearer token.

Authentication headerhttp
Authorization: Bearer ks_live_...

In YallaRoute a web shop creates its own keys on the Developers page of the customer portal. A key made there belongs to one sender account: it books for that account and sees only that account's deliveries. A key has a scope. Reading shipments, labels and quotes needs read. Booking and cancelling need write. The delivery company's plan switches the API on: it is included in the Growth, Scale and Enterprise plans.

Key handling

  • The key lives in a server-side secret store or environment variable. Never in front-end code, a mobile app or a repository
  • One key per system and environment, so that one can be revoked without stopping the others
  • The lowest scope that does the job. A reporting tool needs read only
  • Revoke and replace a key when someone who had access leaves, or the moment it appears in a log or a ticket

Quote at checkout

The quote call returns the price a booking with these details would get right now, the window it would be promised, and whether the address is in the delivery area. It stores nothing, so it is safe to call as the customer edits the basket.

  1. Call it from your server once the delivery address is complete, not on every keystroke.
  2. Send the order as the carrier will see it: service, packed weight, and dimensions if you have them.
  3. Show the total with its currency, and the promised window, straight from the response. Do not recompute tax yourself.
  4. Give the call a short timeout of two or three seconds. If it fails, show a fallback you have agreed with the delivery company, such as a flat rate.
  5. Cache by address, weight and service for a few minutes, so that a page reload is not a new call.

If the response says the address is not covered, say so at checkout and offer what you can. Finding out after payment costs a refund and a customer. And because a price can change between checkout and booking, store the price the booking returns, not the quote.

Book on payment, with an idempotency key

Book when payment is confirmed, from the same server-side job that marks the order paid. Do not book from the page the customer returns to: customers close tabs.

The risk in booking is the retry. Your request times out, you do not know whether the delivery was created, you send it again, and now two drivers are coming. An idempotency key removes the risk. You send a unique value with the request. If the server has already handled that value, it returns the first answer and creates nothing.

Booking with an idempotency keyjavascript
// Runs on your server when payment is confirmed.
const BASE = "https://YOUR-DELIVERY-COMPANY.example/api/v1";

async function bookDelivery(order) {
  // Build the body once. A retry must send exactly the same bytes.
  const body = JSON.stringify({
    service: order.deliveryService,
    order_ref: order.number,
    recipient: { name: order.customerName, phone: order.phone, email: order.email },
    address: order.deliveryAddress, // the address object, as your delivery company's reference describes it
    parcel: { weight_kg: order.packedWeightKg },
  });

  for (let attempt = 1; attempt <= 4; attempt++) {
    const res = await fetch(BASE + "/shipments", {
      method: "POST",
      headers: {
        Authorization: "Bearer " + process.env.DELIVERY_API_KEY,
        "Content-Type": "application/json",
        "Idempotency-Key": "order-" + order.id,
      },
      body,
      signal: AbortSignal.timeout(10000),
    }).catch(() => null); // network error or timeout

    if (res && res.status === 201) return (await res.json()).data;
    if (res && res.status < 500 && res.status !== 409 && res.status !== 429) {
      throw new BookingRejected((await res.json()).error); // fix the data, do not retry
    }
    await sleep(waitFor(res, attempt)); // defined under rate limits below
  }
  throw new Error("Booking not confirmed. Queue it and retry with the same key.");
}
  • The header is Idempotency-Key: 1 to 120 printable characters with no spaces. Your order id is the natural choice.
  • A key is remembered for 24 hours. A repeat with the same key and the same body returns the first answer, with the response header Idempotent-Replayed: true.
  • The same key with a different body answers 422 idempotency_key_reused. That is a bug on your side: a key must mean one request.
  • A repeat that arrives while the first is still being handled answers 409 request_in_progress. Wait and retry.
  • A request that failed is forgotten, so you can correct the data and send it again under the same key.

The response is the shipment. Store its id, which is the tracking number, with tracking_url, status and price, against your order. If the consignment has several parcels, each has its own tracking number in piece_ids.

Errors, rate limits and pagination

Every response is JSON in one of two envelopes: data with meta on success, or error with a code, a message and, for validation, a list of fields.

HTTP status, example error codes and what the client should do
StatusExample codesWhat to do
400invalid_json, invalid_parameter, invalid_cursorA bug in the request. Fix the code. Do not retry
401, 403invalid_key, insufficient_scope, forbiddenStop and alert a person. Retrying will not help
404not_foundThe tracking number is wrong, or belongs to another sender
409request_in_progress, not_cancellableRetry the first after a pause. The second is final
413payload_too_largeThe body is over 64 KB
422validation_failed, idempotency_key_reusedShow error.fields to someone who can correct the order. Do not retry unchanged
429rate_limitedWait the number of seconds in Retry-After, then retry
500server_errorRetry with backoff, under the same idempotency key

Validation errors are about your customers' data. Each entry in error.fields names a field, such as recipient.name, and says what is wrong in a sentence you can show to staff. Put the order in a queue that a person works: an order that fails validation silently is a parcel that never ships.

A YallaRoute key may make 120 requests in any 60 seconds, and every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset. Over the limit, the answer is 429 with Retry-After in seconds. Honour it, and back off on server errors and timeouts with growing, randomised waits.

Backoffjavascript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// How long to wait before the next attempt, in milliseconds.
function waitFor(res, attempt) {
  const retryAfter = res ? Number(res.headers.get("Retry-After")) : 0;
  if (retryAfter > 0) return retryAfter * 1000;
  const base = 500 * 2 ** attempt;              // 1s, 2s, 4s, 8s
  return base / 2 + Math.random() * (base / 2); // jitter, so retries do not arrive together
}

List calls return a page at a time. GET /shipments takes limit, up to 100, and returns meta.has_more and meta.next_cursor. Pass the cursor back as cursor and stop when has_more is false. A cursor is valid for 15 minutes, so run a reconciliation through in one go. Lists are for reconciliation, not for status.

Labels and collection

Every parcel needs something a driver can scan. Some APIs return a finished label as a file. Others, YallaRoute among them, return label data for you to draw: GET /shipments/{id}/label answers with the tracking number, a Code 128 barcode value, a QR value that opens the tracking page, carrier and service names, delivery details, handling words such as fragile, any cash to collect and your order reference.

  • Print the barcode at a size and contrast a phone camera can read, and test it with the delivery company's scanner before go-live.
  • Print one label per parcel. A consignment of three boxes has three tracking numbers.
  • Fetch the label when the order is packed, not when it is booked, so that a cancelled order never gets one.
  • If packing changes the weight or the number of parcels, cancel and rebook before the parcel leaves.

Collection is the other half. Agree how parcels reach the delivery company: a daily collection at a fixed time, a collection per booking, or your own drop at their depot. Agree the cut-off too, and show customers a promise that matches it.

Cancelling is POST /shipments/{id}/cancel. It is safe to repeat. Once the parcel is out for delivery or finished it answers 409 not_cancellable, and a person has to phone dispatch.

Webhooks: subscribe, verify, answer fast

A webhook is the delivery system calling you when something happens, so that you never have to ask.

Subscribe. Register an https address and choose the events. In YallaRoute's customer portal a sender can add up to 5 endpoints. The signing secret is shown when the endpoint is created, and can be shown again or replaced there. A shop usually wants shipment.created, shipment.out_for_delivery, shipment.delivered, shipment.failed, shipment.rescheduled, shipment.returned and shipment.cancelled.

Verify the signature. Anyone can post to your address, so check that each request came from the delivery system. YallaRoute sends the header X-YallaRoute-Signature: t=<unix ms>,v1=<hex>. The v1 value is an HMAC-SHA256, keyed with the endpoint's secret, of the timestamp, a full stop and the raw request body.

Verify a webhook signaturejavascript
import { createHmac, timingSafeEqual } from "node:crypto";

// rawBody: the request body exactly as received, before any JSON parsing.
// header:  the value of the signature header, "t=<unix ms>,v1=<hex>".
export function verify(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const expected = createHmac("sha256", secret).update(parts.t + "." + rawBody).digest("hex");
  const fresh = Math.abs(Date.now() - Number(parts.t)) < 5 * 60 * 1000;
  return fresh && expected.length === (parts.v1 || "").length
    && timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
}

Use the raw body: parsing and re-serialising the JSON changes the bytes. Check the timestamp, which is in milliseconds, and reject anything more than a few minutes old so that a captured request cannot be replayed. Compare in constant time, as above.

Respond fast, process afterwards. Your endpoint has one job: verify, store and answer 200. YallaRoute waits 6 seconds, treats any 2xx as delivered and does not follow redirects. Anything else is retried after 30 seconds, 2 minutes, 10 minutes and 1 hour, five attempts in all, and then marked failed. So write the event to a queue and return. Update the order and email the customer from a worker.

Expect duplicates and disorder. Retries mean the same event can arrive twice, and two events for one parcel can arrive in either order. Each delivery has an id in its body that stays the same across retries, and the X-YallaRoute-Delivery header carries the same number. Store the ids you have processed and skip repeats. For order, compare the event's created time with the last one applied to that order.

A webhook body, trimmedjson
{
  "id": "evt_48213",
  "type": "shipment.delivered",
  "created": 1796212800000,
  "data": {
    "id": "KS-TEST-0001",
    "status": "delivered",
    "orderRef": "ORDER-1001",
    "attempt": 1,
    "deliveredAt": 1796212800000,
    "receivedBy": "Alex Morgan",
    "trackingPath": "/track/KS-TEST-0001"
  }
}

Note the two conventions. Webhook bodies use camelCase names and Unix milliseconds. The REST responses use snake_case names and ISO 8601 times. Convert both on the way in.

Map delivery statuses to order statuses

Your customers read your shop's order statuses, not the carrier's. Map them once, in one place. These are the statuses of a YallaRoute shipment with a sensible mapping. Each has an event of the same name, such as shipment.delivered, except loaded.

Delivery statuses mapped to web shop order statuses
Delivery statusMeaningOrder status in the shopMessage the customer?
createdBooked, not yet collectedProcessingNo
collectedPicked up from youShippedYes, with the tracking link
at_hubAt the delivery company's depotShippedNo
loadedOn a vehicleShippedNo
out_for_deliveryThe driver has started the runOut for deliveryOnly if the delivery company does not
deliveredProof of delivery recordedDeliveredYes, unless the delivery company does
failedAn attempt was made and failedDelivery attemptedYes, with what happens next
returnedComing back to youReturnedYes. Start your refund or resend process
cancelledCancelled before going outCancelledDepends on who cancelled

Two rules keep the mapping safe. Treat delivered, returned and cancelled as final: once an order is there, ignore older events that arrive late. And agree with the delivery company who messages the recipient, or the customer hears the same news twice. See delivery notifications that reduce contacts.

A testing plan

Test real behaviour, not only the happy path. Ask the delivery company how they want test bookings made. In YallaRoute a booking through the API is a real booking, so use references that dispatch will recognise as tests, and cancel what you create.

Integration tests and expected results
TestExpect
Quote an address inside the area, then one outsideA price and a window, then a response marked not covered
Book once201, a tracking number, and a shipment.created event
Send the same booking again with the same keyThe same shipment, Idempotent-Replayed: true, and no second delivery
Same key, different body422 idempotency_key_reused
Book with the recipient's name missing422 validation_failed, with the field named
Send requests faster than the limit429 with Retry-After. Your client waits and recovers
Post a webhook with a wrong signatureRejected, and nothing processed
Replay a genuine webhookProcessed once
Deliver the delivered event before out for deliveryThe order ends as delivered
Make your endpoint fail for a minuteThe event arrives on a later retry
Cancel a booking, then cancel it againCancelled both times, with no error

YallaRoute's portal can send a signed test event to an endpoint, which is the quick way to prove your signature check before real parcels move.

Going live checklist

  • The key is in the production secret store with the right scope, and is in no repository or log
  • Every booking sends an idempotency key derived from the order
  • Every call has a timeout, and retries back off
  • Validation failures land in a queue that a named person checks daily
  • The webhook endpoint verifies signatures, answers within a second and processes from a queue
  • Processed event ids are stored, repeats are skipped and final statuses are protected
  • A nightly job lists recent shipments and compares them with orders, to catch anything a webhook missed
  • Alerts fire on repeated 401, 403 and 500 responses, and on a webhook queue that keeps growing
  • The delivery company knows your go-live date, your collection arrangements and who to call
  • The first ten live orders are checked by hand, end to end

Failure modes and defences

Integration failure modes, symptoms and defences
FailureWhat you seeDefence
Double bookingTwo deliveries for one orderAn idempotency key on every booking
Lost bookingAn order paid and nothing bookedBook from a retried server-side job. Reconcile nightly
Leaked keyBookings you did not makeServer-side keys, lowest scope, revoke at once
Silent validation failureOrders stuck with no deliveryAn error queue with a person behind it
Webhook endpoint downStatuses stop movingRetries cover short outages. Reconciliation covers long ones
Forged webhookAn order marked delivered that was notSignature and timestamp check
Duplicate or late eventsA customer told twice, or an order moving backwardsStore event ids. Protect final statuses
Address rejected after paymentA paid order that cannot be deliveredQuote and check coverage before payment

Questions

Common questions

What is an idempotency key in a delivery API?

It is a unique value you send with a booking request, usually your order id. If the same request arrives again with the same key, the server returns the first answer and does not create a second delivery, which makes retrying after a timeout safe. In YallaRoute the header is Idempotency-Key and a key is remembered for 24 hours.

Should a web shop poll for delivery status or use webhooks?

Use webhooks for status and a scheduled list call for reconciliation. Polling every order every few minutes uses up your rate limit and still tells the customer late. A nightly comparison of recent shipments against your orders catches the rare event a webhook missed.

How do I verify a webhook signature?

Take the raw request body exactly as it arrived, combine it with the timestamp from the signature header in the way the delivery system documents, compute an HMAC with the endpoint's secret, and compare the result with the signature in constant time. Reject requests whose timestamp is more than a few minutes old. Never parse and re-serialise the body before checking.

Can I call the delivery API from the browser?

Not with a secret key. Anything in front-end code can be read by anyone, and a key with write scope lets its holder book and cancel deliveries on your account. Call your own server from the browser and let the server call the delivery API. Public tracking by tracking number is the usual exception, because it needs no key.

What happens if my server is down when a webhook is sent?

A well-built sender retries. YallaRoute retries after 30 seconds, 2 minutes, 10 minutes and 1 hour, five attempts in all, and then marks that event's delivery as failed. Short outages are covered by the retries. For longer ones, run a reconciliation job that lists recent shipments and corrects any order whose status is behind.

When should the shop book the delivery?

When payment is confirmed, from a server-side job that can retry, and not from the page the customer returns to after paying. Quote before payment so that the customer sees the price and you know the address is covered, then book once the money is taken.

Keep reading

Related guides, product pages and help

Put it into practice

YallaRoute is delivery management software: booking, dispatch, a driver app, tracking, proof of delivery and invoicing in one workspace. Open one and try it with your own jobs.