TrackMe API Docs
Getting started

Response Envelope & Errors

The two response shapes every TrackMe endpoint returns, the requestId, the canonical error code set, how to map codes to user-facing copy, and the validation error body.

This guide is for Flutter engineers. Every JSON endpoint under /api/v1 returns exactly one of two envelope shapes. Build your network layer to unwrap the envelope once, in one place, and route on error.code — never on error.message (the message is localised copy, it changes by Accept-Language and is not stable). Get this layer right and every other guide in this docs site becomes a thin mapping over it.

Do not parse error.message to decide what to do. It is human copy meant for display and flips to Arabic when you send Accept-Language: ar. Branch on error.code only — those values are stable and machine-readable. Show error.message to the user as-is.

The flow at a glance

Step 1 — Send the request

Hit any /api/v1/* endpoint. Add Authorization: Bearer <oat_...> for authenticated calls, Accept-Language: ar if you want Arabic copy, and X-Timezone: Asia/Riyadh (IANA) for server-rendered display strings.

Step 2 — Read the HTTP status first

2xx → success envelope ({ data, meta }). 4xx/5xx → error envelope ({ error, meta }). The status and the envelope shape always agree, so you can switch on the status code.

Step 3 — Unwrap once

On success, read body.data (the only place the payload lives). On error, read body.error.code (machine) and body.error.message (display).

Step 4 — Always capture meta.requestId

Present on both shapes. Log it on every response, success or failure. It is the one identifier that lets the backend team trace your exact request.

Step 5 — Map the code to your UI

Resolve error.code against the table below. Treat unknown codes as a generic failure (INTERNAL_ERROR copy) so new server codes do not break the client.

The two shapes

Every response is one of these — there is no third shape.

Success (2xx):

{
  "data": { "...": "module-specific payload" },
  "meta": { "requestId": "req_01jq8z1mxc0e0v6r3xj0a8h9k7" }
}

Error (4xx / 5xx):

{
  "error": {
    "code": "AUTH_REQUIRED",
    "message": "Authentication is required to access this resource."
  },
  "meta": { "requestId": "req_01jq8z1mxc0e0v6r3xj0a8h9k7" }
}

Rules that hold for every endpoint:

  • data and error are mutually exclusive. A 2xx always has data; a non-2xx always has error.
  • meta is always present, on both shapes, and always carries requestId.
  • The payload always lives under data — never at the top level. body.data.items, not body.items.
  • error.code and error.message are always present on an error. error may carry extra fields (see below) — your parser must tolerate unknown keys.

requestId

meta.requestId is a req_-prefixed ID (e.g. req_01jq8z1mxc0e0v6r3xj0a8h9k7) stamped on every request and echoed back in two places:

  • In the response body at meta.requestId.
  • In the X-Request-Id response header.

It is the correlation key the backend uses to find your request in the logs.

Log requestId on every response and surface it on error screens. When investigating a failed call with the backend team, the requestId identifies the exact request in server logs. If you send your own X-Request-Id request header, the server honours it (up to 64 chars); otherwise it generates one for you.

Canonical error codes

error.code comes from a fixed, canonical set. Branch your app logic on these. The "Status" column is the HTTP status that ships with each code; the "Default copy" is the English message (Arabic when Accept-Language: ar).

CodeStatusMeaningWhat to do
VALIDATION_ERROR422 (also 400)Request body / query failed validationShow per-field errors from error.fields (see below). Fix and resend.
AUTH_REQUIRED401No token, expired token, or bad credentialsSend the user to sign-in. Clear the stored token.
FORBIDDEN403Authenticated, but not allowed to do thisHide/disable the action. Do not retry.
NOT_FOUND404The target resource does not exist (or was deleted)Show an empty/not-found state. May carry targetType / targetId.
CONFLICT409Action conflicts with current stateRefresh the resource and re-read its state before retrying.
RATE_LIMITED429Too many requestsBack off. Honour error.retryAfterSeconds (and the Retry-After header) before retrying.
SOCIAL_TOKEN_INVALID401A Google/Apple sign-in token could not be verifiedRestart the social sign-in flow.
INTERNAL_ERROR500Unhandled server-side errorGeneric "try again" message. Log the requestId.

Some endpoints return a more specific code that still maps to one of the statuses above — for example INVALID_CREDENTIALS (409) on a bad login, or SERVICE_EXPIRED / RESOURCE_DELETED. These are spec extensions, not new shapes. Always handle the canonical set above, and treat any code you do not recognise as its HTTP-status default (e.g. an unknown 401 code → behave like AUTH_REQUIRED). That way a new server code never breaks the app.

Extra fields on the error object

error carries code + message always, plus optional context fields depending on the code. Your decoder must ignore unknown keys, but these are the ones worth reading:

FieldAppears onUse
fieldsVALIDATION_ERRORPer-field validation failures (see next section).
retryAfterSecondsRATE_LIMITEDSeconds to wait before retrying.
targetType, targetIdNOT_FOUND, CONFLICTWhich resource the error is about.

Example NOT_FOUND with context:

{
  "error": {
    "code": "NOT_FOUND",
    "message": "Resource not found.",
    "targetType": "food_truck",
    "targetId": "trk_01jq8z2hf5t8z4w9d8x4mzg2p3"
  },
  "meta": { "requestId": "req_01jq8z1mxc0e0v6r3xj0a8h9k7" }
}

Mapping codes to user-facing copy

The server already resolves error.message into the request locale. You have two valid strategies:

  1. Display the server message directly. error.message is localised (English by default, Arabic when you send Accept-Language: ar). This is the simplest correct approach — show it in a toast/snackbar.
  2. Map error.code to your own localised strings. If you want app-controlled copy or richer UI per code, key your own translation table off error.code (stable) and fall back to error.message for codes you have not localised yet.
// Pseudocode for the network layer
final body = decode(response.body);
if (response.statusCode >= 200 && response.statusCode < 300) {
  return body['data'];            // unwrap success
}
final err = body['error'];
log('request ${body['meta']['requestId']} failed: ${err['code']}');
switch (err['code']) {
  case 'AUTH_REQUIRED': signOut(); break;
  case 'RATE_LIMITED':  backOff(err['retryAfterSeconds']); break;
  case 'VALIDATION_ERROR': showFieldErrors(err['fields']); break;
  default: showToast(err['message']);   // server copy, already localised
}

Do not hardcode English error strings for comparisons. Send Accept-Language: ar and error.message comes back Arabic, so string comparisons are unsafe. Compare error.code, display error.message.

Validation error shape

A VALIDATION_ERROR (HTTP 422) is the only error whose body you should parse for structured detail. It carries a fields array — one entry per failed field — so you can highlight inputs inline:

POST /api/v1/auth/register
Content-Type: application/json
Accept-Language: en

{ "email": "not-an-email", "password": "x" }
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request payload.",
    "fields": [
      { "path": "email", "message": "The email field must be a valid email address.", "rule": "email" },
      { "path": "password", "message": "The password field must have at least 8 characters.", "rule": "minLength" }
    ]
  },
  "meta": { "requestId": "req_01jq8z1mxc0e0v6r3xj0a8h9k7" }
}

Each entry in fields:

KeyMeaning
pathThe field that failed. Nested fields use dot notation (e.g. address.city).
messageLocalised, human-readable reason — safe to show under the input.
ruleThe validation rule that failed (required, email, minLength, …). Optional; use it for custom per-rule copy.

To attach errors to your form fields, index by path. Read message for display; rule only if you want app-controlled copy per rule.

Some endpoints also raise a 422 (or 400) VALIDATION_ERROR for semantic failures that are not a missing field — e.g. a malformed cursor or an out-of-range value. Always render the fields array if it is present; fall back to error.message if it is empty or absent.

Success meta — pagination

On list endpoints, pagination metadata rides in meta alongside requestId — never inside data. Customer-facing lists use cursor pagination:

GET /api/v1/trucks/search?limit=20
Authorization: Bearer oat_...
{
  "data": { "items": [ { "id": "trk_..." } ] },
  "meta": {
    "requestId": "req_01jq8z1mxc0e0v6r3xj0a8h9k7",
    "pagination": { "nextCursor": "eyJpZCI6Li4ufQ", "hasMore": true, "limit": 20 }
  }
}

To page forward: if hasMore is true, resend the same request with ?cursor=<nextCursor>. When hasMore is false, nextCursor is null and you are at the end. Treat nextCursor as an opaque token — do not decode or construct it yourself.

FieldMeaning
nextCursorOpaque token for the next page, or null at the end.
hasMoretrue when another page exists.
limitThe page size that was applied.

Implementation Notes

  • Top-level data only. The payload is always under data. If you find yourself reading body.someField directly, you skipped the envelope.
  • meta is on errors too. Do not gate requestId logging behind the success path — capture it on every response.
  • Tolerate unknown error keys and unknown codes. New context fields and more-specific codes get added over time. Default-handle anything you do not recognise so the client remains stable.
  • Wire timestamps are UTC. Every timestamp in data is ISO-8601 with a Z suffix. X-Timezone only affects server-rendered display strings (push copy, email subjects), not the JSON payload — format times client-side.
  • Localise by header, not by parsing. Accept-Language: ar localises every message. It is also persisted as the user's preferred language on the first authenticated request.
  • Authentication & Tokens — how to get the oat_ Bearer token that AUTH_REQUIRED is asking for.
  • Payments — where CONFLICT / SERVICE_EXPIRED show up around paid services.
  • API reference — per-endpoint request/response schemas and the full error catalogue.

On this page