---
title: "API Error Patterns"
description: "Stable API error contracts, HTTP status codes, and implementation patterns for ZeyOS services."
canonical_url: "https://www.zeyos.com/ixml/ixml-guide/error-handling/api-error-patterns"
markdown_url: "https://www.zeyos.com/ai/guide/ixml/ixml-guide/error-handling/api-error-patterns.md"
section: "ixml-guide"
authority: "guide"
language: "en"
source_repository: "zeyos/guide"
source_path: "docs/ixml/07-error-handling/api-error-patterns.md"
source_revision: "cce886a8da98cd124ee3644711085bbdcf1a87ce"
---

# API Error Patterns

## Stable API error contract

When building ZeyOS services that expose APIs, establish a consistent response envelope that clients can rely on. Every endpoint should return the same top-level structure regardless of whether the operation succeeded or failed. This reduces client-side complexity and makes services easier to monitor and debug.

### Recommended response shapes

**Success response:**

```json
{
    "result": 1,
    "data": { ... }
}
```

**Error response:**

```json
{
    "error": "Human-readable error message",
    "details": "Technical details for debugging"
}
```

### Implementation pattern

```xml
<array var="RES" />

<try>
    <!-- Business logic here -->
    <set var="RES.result">1</set>

    <catch var="err">
        <set var="RES.error">Operation failed</set>
        <set var="RES.details">$err</set>
    </catch>
</try>

<header>Content-Type: application/json</header>
<output><encode:json var="RES" /></output>
```

This pattern ensures that:

- The client always receives valid JSON, never a raw error dump
- The top-level key (`result` vs. `error`) immediately signals success or failure
- Technical error details are available for debugging without leaking sensitive internals
- The HTTP `Content-Type` header is always set correctly, even on error

### HTTP status codes

Use the `status` attribute of the `<header>` command to set appropriate HTTP status codes in error scenarios:

```xml
<catch var="err">
    <header status="400" />
    <set var="RES.error">Bad request: $err</set>
</catch>
```

Common status codes for API services:

| Code | Meaning | When to use |
|---|---|---|
| `200` | OK | Successful operations (default) |
| `201` | Created | Successful resource creation |
| `400` | Bad Request | Invalid input, malformed JSON, missing required fields |
| `401` | Unauthorized | Missing or invalid authentication |
| `403` | Forbidden | Authenticated but insufficient permissions |
| `404` | Not Found | Requested resource does not exist |
| `500` | Internal Server Error | Unexpected failures, database errors |

A `401` or `403` check inside `rest:resource` must [bind `AUTH` with `use`](https://www.zeyos.com/ixml/ixml-guide/development-environment/execution-contexts#bind-globals-inside-restresource), or a query argument can forge it.
