Build it into your product

What an integration gets wrong when it is written like a demo, and a backend that gets it right. Every method is in the SDK reference.

Use the SDK for your language

  • TypeScript and JavaScript: @r4mai/sdk. Go: github.com/r4m-ai/sdk-go. They poll with backoff, wait out "busy" answers and verify webhooks, and their types follow the API exactly.
  • Other languages call the REST API: treat any 2xx as success, and on a 429 wait the seconds in Retry-After before trying again.

SDK reference

One key per environment, read from the environment

  • Read the key from R4M_API_KEY. Never write it into source, committed config or logs.
  • Give each environment and each service its own key (local, staging, production): one can then be rotated or revoked without taking the others down. GET /api/v1/account says how many keys the account may hold.
  • For local development an agent can ask for a key through the device flow and write it straight into .env (see Authentication in Concepts).

Authentication

Never hold a request open for the solve

  • A script, CLI or batch job that can wait: createOptimizationAndWaitForRoutes submits, waits out busy answers, polls and returns the finished plan.
  • A backend serving users: submit with submitOptimization and a webhookUrl, store the returned id with your own record, answer the user at once, and finish the work when the webhook arrives.
  • No public URL for a webhook: poll from a background job with waitForRoutes(id) instead of from a web request.

Waiting for the result

Webhooks: verify, acknowledge, deduplicate

  • Keep the signing secret in R4M_WEBHOOK_SECRET. Code can fetch it from GET /api/v1/webhook-secret straight into the environment, or a person copies it from Settings.
  • Verify every delivery against the raw body (verifyWebhook / VerifyWebhookRequest in the SDKs) and answer a bad signature with 401.
  • Handle optimization.completed and optimization.failed; acknowledge every other type with a 2xx (optimization.cancelled, and types added later).
  • Answer quickly and do slow work afterwards. Key your processing on optimizationId, so a repeated delivery does no harm.
  • The URL must be public https. To test against a local server, expose it with ngrok http <port>.

Webhooks

Retries are safe

  • The same request sent again — same addresses, parameters, webhookUrl and geocoding options — while the first is in flight, or within a day after it finished, returns that optimization (200 instead of 202) and is not charged again. Retry a create after a network error or a timeout without deduplicating it yourself.
  • The same stops in another order get an optimization of their own, its indices in the order they were sent.

Geocode once, keep the coordinates

  • Send lat/lng whenever you have them, and store the coordinates of addresses you geocoded: every lookup is paid.
  • Stops typed by people: geocode them first (POST /api/v1/geocoding/bulk) and let the person confirm ambiguous ones, or send them without coordinates and handle 422 GEOCODING_UNRESOLVED by showing the candidates. Never pick one for them.

When geocoding is unresolved

Read limits, never assume them

  • Limits differ per account. Read them from GET /api/v1/account when the app needs them (to cap a form, say), and pass the message of ADDRESS_LIMIT_EXCEEDED or PLAN_LIMIT_EXCEEDED on to the user; never drop or split their stops silently.
  • 402 INSUFFICIENT_FUNDS means the balance needs a top-up: surface it to whoever runs the app rather than retrying.

Error codes

Read the whole result

  • result.routes is always an array, one entry per vehicle: iterate it. Each waypoint's index points back at the request's addresses.
  • Check result.unroutedStops: a stop listed there is not in the plan at all, and the user needs to know.
  • cancelOptimization(id) stops waiting for one nobody needs any more and frees its slot at once; it is not refunded and never delivers a result.

Test it once for real

  • Before calling it done, run the integration end to end against the API with a handful of stops — webhook included, through ngrok if the server is local.

A backend, end to end

Submit when the user asks, store the id, and finish the work when the signed webhook arrives.

import { createClient, verifyWebhook, WebhookSignatureError } from "@r4mai/sdk"; const r4m = createClient({ apiKey: process.env.R4M_API_KEY! }); // When the user asks for a route: submit, remember the id, answer at once. export async function requestRoute( addresses: { address: string; lat: number; lng: number; isDepot?: boolean }[], ) { // Waits out "busy" answers; resolves to the receipt (status "pending"). const { data: receipt, error } = await r4m.submitOptimization({ body: { addresses, webhookUrl: "https://your-app.example.com/hooks/r4m" }, }); if (error) throw error; // refused: error.code and error.message say why return receipt.id; // store it with your own record } // The webhook route (a Fetch-API handler, e.g. a Next.js route). export async function POST(request: Request) { try { const event = await verifyWebhook(request, process.env.R4M_WEBHOOK_SECRET!); if (event.type === "optimization.completed") { // event.optimizationId, event.result.routes, event.result.unroutedStops } else if (event.type === "optimization.failed") { // event.error.code, event.error.message } // optimization.cancelled, and any type added later: acknowledge. return new Response(null, { status: 204 }); } catch (err) { if (err instanceof WebhookSignatureError) { return new Response("Invalid signature", { status: 401 }); } throw err; } }