11. Appendix
============

The Appendix provides **reference materials, reserved conventions and developer tools** for teams implementing or
integrating JsonDispatch.

It’s meant as a **quick lookup section** — not something you memorize, but something you check when building middleware,
validation tools or test clients.


11.1 Reserved Headers (Response Only)
-------------------------------------

These headers are **core to JsonDispatch** and reserved for server responses.
They should **never** be redefined for other purposes.

.. list-table::
   :header-rows: 1
   :widths: 26 12 10 52

   * - Header
     - Direction
     - Required
     - Description
   * - **Content-Type**
     - Response
     - ✅
     - Media type of the response payload (``application/json; charset=utf-8`` for JsonDispatch envelopes; native media types for files/streams)
   * - **X-Api-Version-Selected**
     - Response
     - ✅
     - Full semantic version of the server’s JsonDispatch implementation
   * - **X-Request-Id**
     - Response
     - ✅
     - Unique identifier generated by the server for this specific request/response
   * - **X-Correlation-Id**
     - Response
     - ⚪
     - Optional; groups multiple related requests under one workflow
   * - **X-RateLimit-Limit**
     - Response
     - ⚪
     - Optional; maximum requests allowed in the current window
   * - **X-RateLimit-Remaining**
     - Response
     - ⚪
     - Optional; requests remaining in the current window
   * - **X-RateLimit-Reset**
     - Response
     - ⚪
     - Optional; Unix timestamp when the rate limit resets
   * - **RateLimit-Limit**
     - Response
     - ⚪
     - Optional; IETF Draft alternative for maximum requests allowed
   * - **RateLimit-Remaining**
     - Response
     - ⚪
     - Optional; IETF Draft alternative for requests remaining
   * - **RateLimit-Reset**
     - Response
     - ⚪
     - Optional; IETF Draft alternative (seconds until reset, not timestamp)
   * - **RateLimit-Policy**
     - Response
     - ⚪
     - Optional; IETF Draft policy format (e.g., ``1000;w=3600``)
   * - **Retry-After**
     - Response
     - ⚪
     - Optional; seconds to wait before retrying (for 429 and 503 responses)
   * - **Deprecation**
     - Response
     - ⚪
     - Optional; indicates the endpoint is deprecated (``true`` or RFC 8594 date)
   * - **Sunset**
     - Response
     - ⚪
     - Optional; RFC 8594 date when the endpoint will be removed
   * - **WWW-Authenticate**
     - Response
     - ⚪
     - Optional; authentication scheme for 401 responses
   * - **traceparent / tracestate**
     - Response
     - ⚪
     - Optional; W3C Trace Context headers if distributed tracing is enabled

.. important::
   Clients **should** send ``X-Api-Version`` to declare the desired API version.
   Clients **should not** send ``X-Request-Id`` or ``X-Api-Version-Selected`` — these are server-assigned identifiers
   for traceability and audit purposes.

**Example (Response Headers)**

**Response**

.. code-block:: http

   Content-Type: application/json; charset=utf-8
   X-Api-Version-Selected: 1.3.1
   X-Request-Id: aabbccdd-1122-3344-5566-77889900aabb
   X-Correlation-Id: order-2025-09-30-777

If you also use `W3C Trace Context <https://www.w3.org/TR/trace-context/>`_:

**Response**

.. code-block:: http

   traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
   tracestate: infocyph=api-2025


11.2 Reserved Keywords (Top-Level JSON Keys)
--------------------------------------------

JsonDispatch reserves certain top-level fields in the response body.
Avoid reusing them for other meanings.

.. list-table::
   :header-rows: 1
   :widths: 22 78

   * - Reserved Key
     - Purpose
   * - ``status``
     - Overall outcome (``success``, ``fail``, ``error``)
   * - ``message``
     - Human-readable message
   * - ``data``
     - Primary content (object, array or list of errors)
   * - ``code``
     - Business-level error code (only in ``error`` responses)
   * - ``_references``
     - Lookup tables for IDs → labels
   * - ``_properties``
     - Metadata describing structure or pagination
   * - ``_links``
     - Navigational or relational links

.. tip::
   If you need more top-level fields, group them under a ``meta`` object or use prefixed names
   (e.g. ``app_status``).


11.3 Middleware & Utility Patterns
----------------------------------

JsonDispatch is language-agnostic.
Here’s what a typical implementation might include:

**Middleware responsibilities**

- Attach ``Content-Type`` and ``X-Api-Version-Selected``.
- Generate ``X-Request-Id`` for each request.
- Optionally include ``X-Correlation-Id`` if workflow-aware.
- Enrich logs and tracing context automatically.

**Response builders**

- Provide helper methods like:

  - ``JsonDispatch::success($data, $message)``
  - ``JsonDispatch::fail($errors, $message)``
  - ``JsonDispatch::error($code, $errors, $message)``

- Automatically append ``_links``, ``_properties`` and ``_references`` if provided.

**Logging integration**

- Every log entry should carry ``X-Request-Id``.
- Distributed logs can also use ``X-Correlation-Id`` for multi-service correlation.


11.4 Minimal JSON Schema for the Envelope (Dev Tooling)
-------------------------------------------------------

A lightweight JSON Schema to validate **response envelopes**.
This helps test suites and monitoring agents verify that your API always returns valid JsonDispatch shapes.

.. code-block:: json

   {
     "$schema": "https://json-schema.org/draft/2020-12/schema",
     "$id": "https://spec.infocyph.com/jsondispatch/v1/envelope.schema.json",
     "title": "JsonDispatch v1 Envelope",
     "type": "object",
     "additionalProperties": false,
     "properties": {
       "status": {
         "type": "string",
         "enum": ["success", "fail", "error"]
       },
       "message": { "type": "string" },
       "code": { "type": "string" },
       "data": {},
       "_references": { "type": "object" },
       "_properties": { "type": "object" },
       "_links": { "type": "object" }
     },
     "required": ["status"]
   }

This schema validates:

- ``status`` must always exist.
- Reserved fields must use correct types.
- No unexpected top-level keys.


11.5 Example cURL Requests (Version & Headers)
----------------------------------------------

**Basic request (client → server)**

.. code-block:: bash

   curl -H 'Accept: application/vnd.infocyph.jd.v1+json' \
     -H 'X-Api-Version: 1.3.1' \
     https://api.example.com/articles/42

**Server response (JsonDispatch-compliant)**

**Response**

.. code-block:: http

   HTTP/1.1 200 OK
   Content-Type: application/json; charset=utf-8
   X-Api-Version-Selected: 1.3.1
   X-Request-Id: 60c1bbca-b1c8-49d0-b3ea-fe41d23290bd

**Body**

.. code-block:: json

   {
     "status": "success",
     "message": "Article fetched successfully",
     "data": {
       "id": 42,
       "title": "JsonDispatch in Action"
     }
   }

**Request with correlation (for multi-step workflows)**

.. code-block:: bash

   curl -H 'Accept: application/vnd.infocyph.jd.v1+json' \
     -H 'X-Api-Version: 1.3.1' \
     -H 'X-Correlation-Id: order-2025-10-05-xyz' \
     https://api.example.com/checkout

**Server response**

**Response**

.. code-block:: http

   HTTP/1.1 201 Created
   Content-Type: application/json; charset=utf-8
   X-Api-Version-Selected: 1.3.1
   X-Request-Id: 8d4e2a1b-c821-4b97-8430-44c7b9651d79
   X-Correlation-Id: order-2025-10-05-xyz

**Body**

.. code-block:: json

   {
     "status": "success",
     "message": "Checkout initiated successfully",
     "data": {
       "order_id": "ORD-2391A",
       "state": "processing"
     }
   }


11.6 Developer Notes
--------------------

- The server is the **only authority** for JsonDispatch headers.
  Clients may provide ``X-Correlation-Id`` (optional), but never ``X-Request-Id``.
- Clients should send ``X-Api-Version`` on requests; the server responds with ``X-Api-Version-Selected``.
- For JsonDispatch envelope responses, use ``Content-Type: application/json; charset=utf-8`` (vendor media type on responses is optional).
- Always include ``X-Api-Version-Selected`` in responses — even for errors.
- JsonDispatch responses remain **valid JSON** even for plain ``application/json`` clients.


11.7 Response Body Conventions
------------------------------

To keep payloads portable across SDKs and languages, use these conventions consistently:

.. list-table::
   :header-rows: 1
   :widths: 34 66

   * - Convention
     - Recommendation
   * - Timestamp fields
     - Use UTC with ISO 8601 / RFC 3339 format (example: ``2026-05-13T09:45:00Z``).
   * - Nullable fields
     - Use explicit ``null`` only when the field is still part of the contract; omit fields only when optional and undocumented as always-present.
   * - Numeric identifiers
     - Keep identifier types stable across versions (don’t switch ``id`` between integer and string).
   * - Boolean semantics
     - Use ``true``/``false`` only for binary state; avoid encoding booleans as ``0/1`` or ``"yes"/"no"``.
   * - Error detail objects
     - Keep ``field``, ``code`` and ``message`` stable so clients can automate retries and UX messaging.
