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
2xxas success, and on a429wait the seconds inRetry-Afterbefore trying again.
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/accountsays 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).
Never hold a request open for the solve
- A script, CLI or batch job that can wait:
createOptimizationAndWaitForRoutessubmits, waits out busy answers, polls and returns the finished plan. - A backend serving users: submit with
submitOptimizationand awebhookUrl, store the returnedidwith 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.
Webhooks: verify, acknowledge, deduplicate
- Keep the signing secret in
R4M_WEBHOOK_SECRET. Code can fetch it fromGET /api/v1/webhook-secretstraight into the environment, or a person copies it from Settings. - Verify every delivery against the raw body (
verifyWebhook/VerifyWebhookRequestin the SDKs) and answer a bad signature with401. - Handle
optimization.completedandoptimization.failed; acknowledge every other type with a2xx(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 withngrok http <port>.
Retries are safe
- The same request sent again — same addresses, parameters,
webhookUrland geocoding options — while the first is in flight, or within a day after it finished, returns that optimization (200instead of202) 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/lngwhenever 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 handle422 GEOCODING_UNRESOLVEDby showing the candidates. Never pick one for them.
Read limits, never assume them
- Limits differ per account. Read them from
GET /api/v1/accountwhen the app needs them (to cap a form, say), and pass the message ofADDRESS_LIMIT_EXCEEDEDorPLAN_LIMIT_EXCEEDEDon to the user; never drop or split their stops silently. 402 INSUFFICIENT_FUNDSmeans the balance needs a top-up: surface it to whoever runs the app rather than retrying.
Read the whole result
result.routesis always an array, one entry per vehicle: iterate it. Each waypoint'sindexpoints back at the request'saddresses.- 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;
}
}