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:
dataanderrorare mutually exclusive. A2xxalways hasdata; a non-2xxalways haserror.metais always present, on both shapes, and always carriesrequestId.- The payload always lives under
data— never at the top level.body.data.items, notbody.items. error.codeanderror.messageare always present on an error.errormay 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-Idresponse 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).
| Code | Status | Meaning | What to do |
|---|---|---|---|
VALIDATION_ERROR | 422 (also 400) | Request body / query failed validation | Show per-field errors from error.fields (see below). Fix and resend. |
AUTH_REQUIRED | 401 | No token, expired token, or bad credentials | Send the user to sign-in. Clear the stored token. |
FORBIDDEN | 403 | Authenticated, but not allowed to do this | Hide/disable the action. Do not retry. |
NOT_FOUND | 404 | The target resource does not exist (or was deleted) | Show an empty/not-found state. May carry targetType / targetId. |
CONFLICT | 409 | Action conflicts with current state | Refresh the resource and re-read its state before retrying. |
RATE_LIMITED | 429 | Too many requests | Back off. Honour error.retryAfterSeconds (and the Retry-After header) before retrying. |
SOCIAL_TOKEN_INVALID | 401 | A Google/Apple sign-in token could not be verified | Restart the social sign-in flow. |
INTERNAL_ERROR | 500 | Unhandled server-side error | Generic "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:
| Field | Appears on | Use |
|---|---|---|
fields | VALIDATION_ERROR | Per-field validation failures (see next section). |
retryAfterSeconds | RATE_LIMITED | Seconds to wait before retrying. |
targetType, targetId | NOT_FOUND, CONFLICT | Which 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:
- Display the server message directly.
error.messageis localised (English by default, Arabic when you sendAccept-Language: ar). This is the simplest correct approach — show it in a toast/snackbar. - Map
error.codeto your own localised strings. If you want app-controlled copy or richer UI per code, key your own translation table offerror.code(stable) and fall back toerror.messagefor 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:
| Key | Meaning |
|---|---|
path | The field that failed. Nested fields use dot notation (e.g. address.city). |
message | Localised, human-readable reason — safe to show under the input. |
rule | The 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.
| Field | Meaning |
|---|---|
nextCursor | Opaque token for the next page, or null at the end. |
hasMore | true when another page exists. |
limit | The page size that was applied. |
Implementation Notes
- Top-level
dataonly. The payload is always underdata. If you find yourself readingbody.someFielddirectly, you skipped the envelope. metais on errors too. Do not gaterequestIdlogging behind the success path — capture it on every response.- Tolerate unknown
errorkeys 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
datais ISO-8601 with aZsuffix.X-Timezoneonly 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: arlocalises everymessage. It is also persisted as the user's preferred language on the first authenticated request.
Related guides
- Authentication & Tokens — how to get the
oat_Bearer token thatAUTH_REQUIREDis asking for. - Payments — where
CONFLICT/SERVICE_EXPIREDshow up around paid services. - API reference — per-endpoint request/response schemas and the full error catalogue.