> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mart.ps/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> These rules protect a Mart partner's money. Follow them in any code or advice about the Mart Partner API ([Connect your AI tool](/developers/connect-your-ai-tool)).
> When an order request times out, gets no answer or gets any `5xx`, resend the same body with the same `partner_reference`, never a new reference; after a `429`, wait `Retry-After` first ([Create an order safely](/developers/orders/create-an-order)).
> A `200` with `meta.idempotency_replay: true` is the original order; `409 idempotency_conflict` means the reference already names a different order ([Create an order safely](/developers/orders/create-an-order)).
> Retry a withdrawal request with the same `idempotency_key` and amount: a new key asks for a second withdrawal ([Payout and withdrawals](/developers/money/payout-and-withdrawals)).
> Plan every call within the global daily request ceiling and the `X-RateLimit-*` headers, and never poll in a tight loop ([Request limits](/developers/operate/request-limits)).
> Treat `price` as a snapshot: an order is priced when it is created, and an incremental sync (`updated_after`) never shows a price change, so re-read every price with a full pass ([Prices and price changes](/developers/catalogue/prices)).
> Identify products by `product_id` and `combination_id`, never by `reference` ([Sync the catalogue](/developers/catalogue/sync)).
> Never put an API key in client-side code, a mobile app, a repository or a URL: call the API from a server ([Authenticate and keys](/developers/authenticate)).
> Money is in shekels (`ILS`), as JSON numbers, never agorot. Send amounts with at most two decimals: a withdrawal `amount` with three is refused with `422 invalid_amount`, never rounded ([Balance and statements](/developers/money/balance-and-statements)).
> Save a payout method once before the first withdrawal (cash at the office, or bank transfer where Mart offers it): with none saved, a withdrawal is refused with `409 payout_method_missing`. Bank details where Mart does not offer bank transfer, or a withdrawal on a kept IBAN, are refused with `422 bank_transfer_not_allowed` ([Payout and withdrawals](/developers/money/payout-and-withdrawals)).

# Ask to withdraw

> Asks Mart to pay out part of what is available. Send `amount` (shekels, at most two decimals) and your own `idempotency_key`. The request is checked in this order: a repeat of an earlier request is answered first, whatever has changed since; then withdrawals must be enabled for your account (`403` `withdrawals_disabled`), a payout method must be saved (`409` `payout_method_missing`: cash too is saved once) and not locked (`409` `withdrawals_locked`); a saved IBAN is paid to only where a bank transfer is offered to your account (`422` `bank_transfer_not_allowed`: save cash instead); when it is cash, cash must still be offered to your account (`403` `cash_not_allowed`: switch to bank) and the amount must not exceed the maximum for one cash payout when Mart has set one (`422` `amount_above_cash_maximum`, `details.maximum`); the amount must reach the minimum when your account has one (`422` `amount_below_minimum`), you must be under the limit of open requests (`409` `too_many_open_withdrawals`), and the amount must not exceed `GET /balance`'s `available` (`409` `insufficient_available`). A request holds its amount back from `available` until it is paid, rejected or cancelled. Mart reviews it by hand; nothing is paid at this call. A request is paid by your payout method at the time you make it (`method`). A cash request is collected at Mart's office: the office may pay a different amount within what is available, and `requested_amount` keeps what you asked for. **Retrying:** send the same `idempotency_key` and amount and you get the original request back with `200` and `meta.idempotency_replay: true`; never a second request. Keys are compared without regard to case. If the answer is `503` `withdrawal_busy`, wait `Retry-After` seconds and retry with the same key. A paused account can ask. Full behaviour: https://mart.ps/api/docs#money/withdrawal-create.



## OpenAPI

````yaml /openapi.json post /api/v1/withdrawals
openapi: 3.0.3
info:
  title: Mart Partner API
  version: 1.1.0
  description: >-
    REST API for Mart reseller partners: the product catalog (with per-product
    and per-combination stock), delivery destinations, and order creation — cash
    on delivery or card.


    Every response, success or failure, uses the envelope `{status, status_code,
    message, data, meta, error}`; branch on `error.code`, never on `message`.
    Response keys are structurally stable: absent objects are `null`, absent
    collections are `[]`; the only caller-controlled structural variance is the
    products listing's `include=` parameter.


    Authenticate with `Authorization: Bearer <key>` (preferred) or `X-Api-Key`.
    A key holds scopes, each operation names the one it needs in
    `x-required-scope`, and a key without it is answered `403`
    `insufficient_scope` (`details.required_scope` names it) without using any
    quota; keys made before scopes existed keep exactly the access they had.
    Rate limits are per key on fixed minute/day windows; the `X-RateLimit-*`
    headers are authoritative.


    **Environments** — build against the sandbox first.
    `https://sandbox.mart.ps` is a separate installation with its own keys
    (`mk_test_…`), a periodically refreshed copy of the catalog, synthetic
    customers and orders, and Lahza's test gateway: nothing placed there is
    fulfilled or charged, and its data is reset on a published schedule.
    Production keys are `mk_live_…` and work only against `https://mart.ps`; a
    key sent to the wrong environment answers `401` `key_environment_mismatch`
    before anything else is checked. Every response carries `X-Mart-Environment:
    production|sandbox` — assert it in your client so a misconfigured base URL
    fails loudly.


    This document is the machine contract. The human documentation — onboarding,
    sync guidance, pricing semantics, idempotent retries, the full error
    catalogue with remedies — is at https://mart.ps/api/docs.
servers:
  - url: https://mart.ps
    description: Production
  - url: https://sandbox.mart.ps
    description: Sandbox
security:
  - bearerAuth: []
  - apiKeyHeader: []
tags:
  - name: Products
    description: 'Catalog: listing and product detail, with prices and stock.'
  - name: Categories
    description: Catalog category vocabulary for the products category_id filter.
  - name: Attributes
    description: Attribute-group vocabulary behind the products combination attributes.
  - name: Delivery
    description: Delivery destinations for order shipping addresses.
  - name: Orders
    description: >-
      Cash-on-delivery order creation, order list, dry-run validation, order
      read and cancellation.
  - name: Money
    description: >-
      Your balance, the ledger of movements, your statements, your payout
      method, your withdrawals and the feed of events on your account.
  - name: Reports
    description: Your own order totals by month, and your most ordered products.
  - name: Account
    description: 'Your own account: its state, limits and withdrawal rules.'
paths:
  /api/v1/withdrawals:
    post:
      tags:
        - Money
      summary: Ask to withdraw
      description: >-
        Asks Mart to pay out part of what is available. Send `amount` (shekels,
        at most two decimals) and your own `idempotency_key`. The request is
        checked in this order: a repeat of an earlier request is answered first,
        whatever has changed since; then withdrawals must be enabled for your
        account (`403` `withdrawals_disabled`), a payout method must be saved
        (`409` `payout_method_missing`: cash too is saved once) and not locked
        (`409` `withdrawals_locked`); a saved IBAN is paid to only where a bank
        transfer is offered to your account (`422` `bank_transfer_not_allowed`:
        save cash instead); when it is cash, cash must still be offered to your
        account (`403` `cash_not_allowed`: switch to bank) and the amount must
        not exceed the maximum for one cash payout when Mart has set one (`422`
        `amount_above_cash_maximum`, `details.maximum`); the amount must reach
        the minimum when your account has one (`422` `amount_below_minimum`),
        you must be under the limit of open requests (`409`
        `too_many_open_withdrawals`), and the amount must not exceed `GET
        /balance`'s `available` (`409` `insufficient_available`). A request
        holds its amount back from `available` until it is paid, rejected or
        cancelled. Mart reviews it by hand; nothing is paid at this call. A
        request is paid by your payout method at the time you make it
        (`method`). A cash request is collected at Mart's office: the office may
        pay a different amount within what is available, and `requested_amount`
        keeps what you asked for. **Retrying:** send the same `idempotency_key`
        and amount and you get the original request back with `200` and
        `meta.idempotency_replay: true`; never a second request. Keys are
        compared without regard to case. If the answer is `503`
        `withdrawal_busy`, wait `Retry-After` seconds and retry with the same
        key. A paused account can ask. Full behaviour:
        https://mart.ps/api/docs#money/withdrawal-create.
      operationId: createWithdrawal
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WithdrawalRequest'
      responses:
        '200':
          description: >-
            A repeat of an earlier request: the original, as it stands now
            (`meta.idempotency_replay` is true). Nothing new was recorded.
          headers:
            X-Mart-Environment:
              $ref: '#/components/headers/X-Mart-Environment'
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/SuccessEnvelope'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          withdrawal:
                            $ref: '#/components/schemas/Withdrawal'
                      meta:
                        type: object
                        properties:
                          idempotency_replay:
                            type: boolean
              example:
                status: success
                status_code: 200
                message: OK
                data:
                  withdrawal:
                    withdrawal_id: NDE
                    amount: 125
                    status: requested
                    iban: null
                    reject_reason: null
                    requested_at: '2026-11-01T08:30:00+00:00'
                    approved_at: null
                    paid_at: null
                    method: bank
                    requested_amount: 125
                meta:
                  idempotency_replay: true
                error: null
        '201':
          description: The request was recorded. `meta.idempotency_replay` is false.
          headers:
            X-Mart-Environment:
              $ref: '#/components/headers/X-Mart-Environment'
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/SuccessEnvelope'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          withdrawal:
                            $ref: '#/components/schemas/Withdrawal'
                      meta:
                        type: object
                        properties:
                          idempotency_replay:
                            type: boolean
              example:
                status: success
                status_code: 201
                message: Created
                data:
                  withdrawal:
                    withdrawal_id: NDE
                    amount: 125
                    status: requested
                    iban: null
                    reject_reason: null
                    requested_at: '2026-11-01T08:30:00+00:00'
                    approved_at: null
                    paid_at: null
                    method: bank
                    requested_amount: 125
                meta:
                  idempotency_replay: false
                error: null
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/WithdrawalsDisabled'
        '405':
          $ref: '#/components/responses/MethodNotAllowed'
        '409':
          $ref: '#/components/responses/WithdrawalRefused'
        '422':
          $ref: '#/components/responses/WithdrawalInvalid'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalError'
        '503':
          $ref: '#/components/responses/WithdrawalUnavailable'
      x-codeSamples:
        - lang: bash
          label: cURL recipe
          source: >
            #!/usr/bin/env bash

            # Ask Mart to pay out part of what is available, safely retried with
            the same idempotency key.

            # Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels,
            at most two decimals) and

            # MART_IDEMPOTENCY_KEY: your own name for this one request, kept
            until it is answered.

            set -euo pipefail

            export LC_NUMERIC=C # printf reads and writes amounts with a decimal
            point


            idempotency_key=${MART_IDEMPOTENCY_KEY:?set MART_IDEMPOTENCY_KEY to
            your own name for this request}

            # The amount as a decimal string, such as "125.50": exact, never
            rounded on the way.

            request=$(jq -n --arg key "$idempotency_key" --arg amount
            "$MART_WITHDRAW_AMOUNT" '{amount: $amount, idempotency_key: $key}')

            echo "idempotency key: $idempotency_key" # written down before the
            first attempt


            # Retries are your choice of numbers: at most 5 attempts; after no
            answer, a 429 or a 5xx, wait

            # what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30)
            with jitter. Any other answer

            # is final. The same key answers the original request, so a retry
            never asks twice.

            for attempt in 1 2 3 4 5; do
              response=$(curl --silent --show-error --max-time 30 --request POST \
                --header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") --header 'Content-Type: application/json' \
                --data "$request" --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE/api/v1/withdrawals") || response=$'\n000'
              read -r status retry_after <<<"${response##*$'\n'}"
              body=${response%$'\n'*}
              case $status in 000 | 429 | 500 | 502 | 503 | 504) ;; *) break ;; esac
              [ "$attempt" = 5 ] && break
              if [[ $retry_after =~ ^[0-9]+$ ]]; then
                if [ "$retry_after" -gt 60 ]; then
                  echo "error: $status, try again after $retry_after s with MART_IDEMPOTENCY_KEY=$idempotency_key" >&2
                  exit 1
                fi
                wait_ms=$((retry_after * 1000))
              else
                wait_ms=$((1000 << (attempt - 1)))
                [ "$wait_ms" -gt 30000 ] && wait_ms=30000
                wait_ms=$((wait_ms / 2 + RANDOM % (wait_ms / 2 + 1)))
              fi
              printf 'retry: attempt %d %s, waiting %d.%d s\n' "$attempt" \
                "$([ "$status" = 000 ] && echo 'got no answer' || echo "answered $status")" $((wait_ms / 1000)) $((wait_ms % 1000 / 100)) >&2
              sleep "$((wait_ms / 1000)).$(printf '%03d' $((wait_ms % 1000)))"
            done


            if [ "$status" = 000 ] || [ "$status" -ge 500 ] || [ "$status" = 429
            ]; then
              echo "error: ${status/000/no answer}${retry_after:+, try again after $retry_after s}; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=$idempotency_key" >&2
              exit 1
            fi

            if [ "$status" -ge 300 ]; then
              echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')" >&2
              exit 1
            fi

            jq -r '.data.withdrawal | "withdrawal: \(.withdrawal_id)\nstatus:
            \(.status)"' <<<"$body"

            printf 'amount: %.2f ILS\n' "$(jq -r '.data.withdrawal.amount'
            <<<"$body")"

            echo "replay: $(jq -r '.meta.idempotency_replay' <<<"$body")"
        - lang: typescript
          label: TypeScript recipe
          source: >
            // Ask Mart to pay out part of what is available, safely retried
            with the same idempotency key.

            // Node 22.18 or later runs this .ts file as it is. Needs
            MART_API_BASE, MART_API_KEY,

            // MART_WITHDRAW_AMOUNT (shekels, at most two decimals) and
            MART_IDEMPOTENCY_KEY: your own name for

            // this one request, kept until it is answered.

            const base = process.env.MART_API_BASE;

            const key = process.env.MART_API_KEY;

            const idempotencyKey = process.env.MART_IDEMPOTENCY_KEY;

            if (!base || !key || !idempotencyKey) throw new Error('Set
            MART_API_BASE, MART_API_KEY and MART_IDEMPOTENCY_KEY');


            const sleep = (ms: number) => new Promise((resolve) =>
            setTimeout(resolve, ms));

            const RETRYABLE = new Set([429, 500, 502, 503, 504]);


            // Retries are your choice of numbers: at most 5 attempts; after no
            answer, a 429 or a 5xx, wait

            // what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30)
            with jitter. Any other answer

            // is final. Every attempt sends the same bytes.

            async function send(path: string, payload: string, timeoutMs:
            number): Promise<Response | null> {
              for (let attempt = 1; ; attempt++) {
                let response: Response | null = null;
                try {
                  response = await fetch(`${base}${path}`, {
                    method: 'POST',
                    headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
                    body: payload,
                    signal: AbortSignal.timeout(timeoutMs),
                  });
                  if (!RETRYABLE.has(response.status) || attempt === 5) return response;
                } catch {
                  if (attempt === 5) return null; // no answer at all
                }
                let wait: number;
                const retryAfter = Number(response?.headers.get('retry-after'));
                if (response && Number.isInteger(retryAfter) && retryAfter > 0) {
                  if (retryAfter > 60) return response; // too long to wait here: the caller says when to come back
                  wait = retryAfter;
                } else {
                  const backoff = Math.min(30, 2 ** (attempt - 1));
                  wait = backoff / 2 + (Math.random() * backoff) / 2;
                }
                console.error(`retry: attempt ${attempt} ${response ? `answered ${response.status}` : 'got no answer'}, waiting ${wait.toFixed(1)} s`);
                await sleep(wait * 1000);
              }
            }


            // Decided once, before any attempt: the same key answers the
            original request. The amount is a

            // decimal string, such as "125.50": exact, never rounded on the
            way.

            const request = JSON.stringify({ amount:
            String(process.env.MART_WITHDRAW_AMOUNT), idempotency_key:
            idempotencyKey });

            console.log(`idempotency key: ${idempotencyKey}`); // written down
            before the first attempt


            const response = await send('/api/v1/withdrawals', request, 30_000);

            const body = response ? await response.json().catch(() => null) :
            null;

            if (response === null || response.status === 429 || response.status
            >= 500) {
              const when = response?.headers.get('retry-after');
              console.error(`error: ${response ? response.status : 'no answer'}${when ? `, try again after ${when} s` : ''}; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=${idempotencyKey}`);
              process.exit(1);
            }

            if (!response.ok || body === null) {
              console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}`);
              process.exit(1);
            }

            console.log(`withdrawal: ${body.data.withdrawal.withdrawal_id}`);

            console.log(`status: ${body.data.withdrawal.status}`);

            console.log(`amount: ${body.data.withdrawal.amount.toFixed(2)}
            ILS`);

            console.log(`replay: ${body.meta.idempotency_replay}`);
        - lang: python
          label: Python recipe
          source: >
            """Ask Mart to pay out part of what is available, safely retried
            with the same idempotency key.


            Python 3.9 or later, with httpx. Needs MART_API_BASE, MART_API_KEY,
            MART_WITHDRAW_AMOUNT (shekels,

            at most two decimals) and MART_IDEMPOTENCY_KEY: your own name for
            this one request, kept until it

            is answered.

            """

            import os

            import random

            import sys

            import time


            import httpx


            TIMEOUT = 30

            client = httpx.Client(
                base_url=os.environ["MART_API_BASE"],
                headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
                timeout=TIMEOUT,
            )

            idempotency_key = os.environ["MART_IDEMPOTENCY_KEY"]



            def body_of(response: httpx.Response):
                """The JSON body, or None for an answer that is not JSON (an edge error page)."""
                try:
                    return response.json()
                except ValueError:
                    return None

            RETRYABLE = {429, 500, 502, 503, 504}



            def send(path: str, payload: dict):
                """POST the same payload until it is answered for good.

                Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait
                what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer
                is final. Returns None when no attempt got an answer.
                """
                for attempt in range(1, 6):
                    response = None
                    try:
                        response = client.post(path, json=payload)
                        if response.status_code not in RETRYABLE or attempt == 5:
                            return response
                    except httpx.TransportError:
                        if attempt == 5:
                            return None
                    retry_after = response.headers.get("Retry-After", "") if response is not None else ""
                    if retry_after.isdigit() and int(retry_after) > 0:
                        if int(retry_after) > 60:
                            return response  # too long to wait here: the caller says when to come back
                        wait = float(retry_after)
                    else:
                        backoff = min(30, 2 ** (attempt - 1))
                        wait = backoff / 2 + random.uniform(0, backoff / 2)
                    what = f"answered {response.status_code}" if response is not None else "got no answer"
                    print(f"retry: attempt {attempt} {what}, waiting {wait:.1f} s", file=sys.stderr)
                    time.sleep(wait)


            def when(response) -> str:
                """", try again after N s" when the answer says how long to wait (Retry-After), else nothing."""
                retry_after = response.headers.get("Retry-After") if response is not None else None
                return f", try again after {retry_after} s" if retry_after else ""


            # Decided once, before any attempt: the same key answers the
            original request. The amount is a

            # decimal string, such as "125.50": exact, never rounded on the way.

            request = {"amount": os.environ["MART_WITHDRAW_AMOUNT"],
            "idempotency_key": idempotency_key}

            print(f"idempotency key: {idempotency_key}", flush=True)  # written
            down before the first attempt


            response = send("/api/v1/withdrawals", request)

            if response is None or response.status_code == 429 or
            response.status_code >= 500:
                status = response.status_code if response is not None else "no answer"
                sys.exit(f"error: {status}{when(response)}; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY={idempotency_key}")
            body = body_of(response)

            if response.is_error or body is None:
                sys.exit(f"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}{when(response)}")
            withdrawal = body["data"]["withdrawal"]

            print(f"withdrawal: {withdrawal['withdrawal_id']}")

            print(f"status: {withdrawal['status']}")

            print(f"amount: {withdrawal['amount']:.2f} ILS")

            print(f"replay: {str(body['meta']['idempotency_replay']).lower()}")
        - lang: php
          label: PHP recipe
          source: >
            <?php

            // Ask Mart to pay out part of what is available, safely retried
            with the same idempotency key.

            // PHP 7.4 or later, with the curl extension. Needs MART_API_BASE,
            MART_API_KEY, MART_WITHDRAW_AMOUNT

            // (shekels, at most two decimals) and MART_IDEMPOTENCY_KEY: your
            own name for this one request, kept

            // until it is answered.

            $base = getenv('MART_API_BASE');

            $key = getenv('MART_API_KEY');

            $idempotencyKey = (string) getenv('MART_IDEMPOTENCY_KEY');

            if ($idempotencyKey === '') {
                fwrite(STDERR, "error: set MART_IDEMPOTENCY_KEY to your own name for this request\n");
                exit(1);
            }


            /**
             * One request with the curl extension. Returns [status, headers (lower-case name => value), body];
             * status 0 when there was no answer at all.
             */
            function request(string $method, string $url, string $key, ?string
            $payload = null, int $timeout = 30): array

            {
                $headers = [];
                $curl = curl_init($url);
                curl_setopt_array($curl, [
                    CURLOPT_CUSTOMREQUEST => $method,
                    CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CONNECTTIMEOUT => 10,
                    CURLOPT_TIMEOUT => $timeout,
                    CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
                        $parts = explode(':', $line, 2);
                        if (count($parts) === 2) {
                            $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
                        }
                        return strlen($line);
                    },
                ]);
                if ($payload !== null) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
                }
                $body = curl_exec($curl);
                $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
                curl_close($curl);

                return [$status, $headers, (string) $body];
            }


            /** ", try again after N s" when the answer says how long to wait
            (Retry-After), else nothing. */

            function when(array $headers): string

            {
                return isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
            }


            /**
             * POST the same payload until it is answered for good. Retries are your choice of numbers: at most
             * 5 attempts; after no answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8
             * seconds (capped at 30) with jitter. Any other answer is final.
             */
            function send(string $url, string $key, string $payload, int
            $timeout): array

            {
                for ($attempt = 1; ; $attempt++) {
                    [$status, $headers, $raw] = request('POST', $url, $key, $payload, $timeout);
                    if (!in_array($status, [0, 429, 500, 502, 503, 504], true) || $attempt === 5) {
                        return [$status, $headers, $raw];
                    }
                    $retryAfter = $headers['retry-after'] ?? '';
                    if (ctype_digit($retryAfter) && (int) $retryAfter > 0) {
                        if ((int) $retryAfter > 60) {
                            return [$status, $headers, $raw]; // too long to wait here: the caller says when to come back
                        }
                        $wait = (float) $retryAfter;
                    } else {
                        $backoff = min(30, 2 ** ($attempt - 1));
                        $wait = $backoff / 2 + mt_rand() / mt_getrandmax() * $backoff / 2;
                    }
                    fwrite(STDERR, sprintf("retry: attempt %d %s, waiting %.1f s\n", $attempt, $status === 0 ? 'got no answer' : "answered $status", $wait));
                    usleep((int) ($wait * 1000000));
                }
            }


            // Decided once, before any attempt: the same key answers the
            original request. The amount is a

            // decimal string, such as "125.50": exact, never rounded on the
            way.

            $request = json_encode(['amount' => (string)
            getenv('MART_WITHDRAW_AMOUNT'), 'idempotency_key' =>
            $idempotencyKey]);

            echo "idempotency key: $idempotencyKey\n"; // written down before
            the first attempt


            [$status, $headers, $raw] = send("$base/api/v1/withdrawals", $key,
            $request, 30);

            if ($status === 0 || $status === 429 || $status >= 500) {
                fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status) . when($headers) . "; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=$idempotencyKey\n");
                exit(1);
            }

            $body = json_decode($raw, true);

            if ($status >= 300 || !is_array($body)) {
                fwrite(STDERR, "error: $status " . ($body['error']['code'] ?? '(not JSON)') . when($headers) . "\n");
                exit(1);
            }

            $withdrawal = $body['data']['withdrawal'];

            echo "withdrawal: {$withdrawal['withdrawal_id']}\n";

            echo "status: {$withdrawal['status']}\n";

            printf("amount: %.2f ILS\n", $withdrawal['amount']);

            echo 'replay: ' . ($body['meta']['idempotency_replay'] ? 'true' :
            'false') . "\n";
        - lang: go
          label: Go recipe
          source: "//go:build ignore\n\n// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.\n// Go 1.22 or later. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at most two\n// decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it is answered.\n// Run it with: go run request-a-withdrawal.go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\tidempotencyKey := os.Getenv(\"MART_IDEMPOTENCY_KEY\")\n\tif idempotencyKey == \"\" {\n\t\tfail(fmt.Errorf(\"set MART_IDEMPOTENCY_KEY to your own name for this request\"))\n\t}\n\n\t// Decided once, before any attempt: the same key answers the original request. The amount is a\n\t// decimal string, such as \"125.50\": exact, never rounded on the way.\n\trequest, err := json.Marshal(map[string]string{\n\t\t\"amount\":          os.Getenv(\"MART_WITHDRAW_AMOUNT\"),\n\t\t\"idempotency_key\": idempotencyKey,\n\t})\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tfmt.Println(\"idempotency key:\", idempotencyKey) // written down before the first attempt\n\n\tresp := send(\"/api/v1/withdrawals\", request)\n\tif resp == nil || resp.StatusCode == 429 || resp.StatusCode >= 500 {\n\t\tstatus := \"no answer\"\n\t\tif resp != nil {\n\t\t\tstatus = strconv.Itoa(resp.StatusCode)\n\t\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\t\tstatus += \", try again after \" + after + \" s\"\n\t\t\t}\n\t\t}\n\t\tfail(fmt.Errorf(\"%s; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=%s\", status, idempotencyKey))\n\t}\n\tvar answer struct {\n\t\tData struct {\n\t\t\tWithdrawal struct {\n\t\t\t\tID     string  `json:\"withdrawal_id\"`\n\t\t\t\tStatus string  `json:\"status\"`\n\t\t\t\tAmount float64 `json:\"amount\"`\n\t\t\t} `json:\"withdrawal\"`\n\t\t} `json:\"data\"`\n\t\tMeta struct {\n\t\t\tIdempotencyReplay bool `json:\"idempotency_replay\"`\n\t\t} `json:\"meta\"`\n\t}\n\tdecode(resp, &answer)\n\tfmt.Println(\"withdrawal:\", answer.Data.Withdrawal.ID)\n\tfmt.Println(\"status:\", answer.Data.Withdrawal.Status)\n\tfmt.Printf(\"amount: %.2f ILS\\n\", answer.Data.Withdrawal.Amount)\n\tfmt.Println(\"replay:\", answer.Meta.IdempotencyReplay)\n}\n\nvar retryable = map[int]bool{429: true, 500: true, 502: true, 503: true, 504: true}\n\n// send POSTs the same bytes until they are answered for good, and returns the last answer, or\n// nil when no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no\n// answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30)\n// with jitter. Any other answer is final.\nfunc send(path string, payload []byte) *http.Response {\n\tfor attempt := 1; ; attempt++ {\n\t\treq, err := http.NewRequest(http.MethodPost, os.Getenv(\"MART_API_BASE\")+path, bytes.NewReader(payload))\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tresp, err := client.Do(req)\n\t\tif err != nil && attempt == 5 {\n\t\t\treturn nil\n\t\t}\n\t\tif err == nil && (!retryable[resp.StatusCode] || attempt == 5) {\n\t\t\treturn resp\n\t\t}\n\t\twhat := \"got no answer\"\n\t\tbackoff := math.Min(30, math.Pow(2, float64(attempt-1)))\n\t\twait := backoff/2 + rand.Float64()*backoff/2\n\t\tif err == nil {\n\t\t\twhat = fmt.Sprintf(\"answered %d\", resp.StatusCode)\n\t\t\tif seconds, convErr := strconv.Atoi(resp.Header.Get(\"Retry-After\")); convErr == nil && seconds > 0 {\n\t\t\t\tif seconds > 60 {\n\t\t\t\t\treturn resp // too long to wait here: the caller says when to come back\n\t\t\t\t}\n\t\t\t\twait = float64(seconds)\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"retry: attempt %d %s, waiting %.1f s\\n\", attempt, what, wait)\n\t\ttime.Sleep(time.Duration(wait * float64(time.Second)))\n\t}\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
        - lang: java
          label: Java recipe
          source: >
            // Ask Mart to pay out part of what is available, safely retried
            with the same idempotency key.

            // Java 17 or later, with Jackson. Needs MART_API_BASE,
            MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at

            // most two decimals) and MART_IDEMPOTENCY_KEY: your own name for
            this one request, kept until it is

            // answered. Run it as a single file: java -cp <the Jackson jars>
            request-a-withdrawal.java

            import com.fasterxml.jackson.databind.JsonNode;

            import com.fasterxml.jackson.databind.ObjectMapper;

            import java.io.IOException;

            import java.net.URI;

            import java.net.http.HttpClient;

            import java.net.http.HttpRequest;

            import java.net.http.HttpResponse;

            import java.time.Duration;

            import java.util.Locale;

            import java.util.Map;

            import java.util.Set;

            import java.util.concurrent.ThreadLocalRandom;


            class RequestAWithdrawal {
                static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
                static final ObjectMapper JSON = new ObjectMapper();

                public static void main(String[] args) throws Exception {
                    String idempotencyKey = System.getenv("MART_IDEMPOTENCY_KEY");
                    if (idempotencyKey == null || idempotencyKey.isEmpty()) {
                        fail("set MART_IDEMPOTENCY_KEY to your own name for this request");
                    }

                    // Decided once, before any attempt: the same key answers the original request. The amount is a
                    // decimal string, such as "125.50": exact, never rounded on the way.
                    String payload = JSON.writeValueAsString(Map.of(
                            "amount", System.getenv("MART_WITHDRAW_AMOUNT"),
                            "idempotency_key", idempotencyKey));
                    HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/withdrawals"))
                            .header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
                            .header("Content-Type", "application/json")
                            .timeout(Duration.ofSeconds(30))
                            .POST(HttpRequest.BodyPublishers.ofString(payload))
                            .build();
                    System.out.println("idempotency key: " + idempotencyKey); // written down before the first attempt

                    HttpResponse<String> response = send(request);
                    if (response == null || response.statusCode() == 429 || response.statusCode() >= 500) {
                        String status = response == null ? "no answer" : response.statusCode() + when(response);
                        fail(status + "; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=" + idempotencyKey);
                    }
                    JsonNode body = parse(response.body());
                    if (response.statusCode() >= 300 || body == null) {
                        fail(response.statusCode() + " " + code(body) + when(response));
                    }
                    JsonNode withdrawal = body.path("data").path("withdrawal");
                    System.out.println("withdrawal: " + withdrawal.path("withdrawal_id").asText());
                    System.out.println("status: " + withdrawal.path("status").asText());
                    System.out.printf(Locale.ROOT, "amount: %.2f ILS%n", withdrawal.path("amount").asDouble());
                    System.out.println("replay: " + body.path("meta").path("idempotency_replay").asBoolean());
                }

                static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503, 504);

                /**
                 * Sends the same request until it is answered for good, and returns the last answer, or null when
                 * no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no answer, a
                 * 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter.
                 * Any other answer is final.
                 */
                static HttpResponse<String> send(HttpRequest request) throws InterruptedException {
                    for (int attempt = 1; ; attempt++) {
                        HttpResponse<String> response = null;
                        try {
                            response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
                            if (!RETRYABLE.contains(response.statusCode()) || attempt == 5) {
                                return response;
                            }
                        } catch (IOException e) {
                            if (attempt == 5) {
                                return null;
                            }
                        }
                        double backoff = Math.min(30, Math.pow(2, attempt - 1));
                        double wait = backoff / 2 + ThreadLocalRandom.current().nextDouble() * backoff / 2;
                        String what = "got no answer";
                        if (response != null) {
                            what = "answered " + response.statusCode();
                            String after = response.headers().firstValue("Retry-After").orElse("");
                            if (after.matches("[0-9]+") && Long.parseLong(after) > 0) {
                                if (Long.parseLong(after) > 60) {
                                    return response; // too long to wait here: the caller says when to come back
                                }
                                wait = Long.parseLong(after);
                            }
                        }
                        System.err.printf(Locale.ROOT, "retry: attempt %d %s, waiting %.1f s%n", attempt, what, wait);
                        Thread.sleep((long) (wait * 1000));
                    }
                }

                /** The JSON body, or null for an answer that is not JSON (an edge error page). */
                static JsonNode parse(String text) {
                    try {
                        return JSON.readTree(text);
                    } catch (IOException e) {
                        return null;
                    }
                }

                static void fail(String message) {
                    System.err.println("error: " + message);
                    System.exit(1);
                }

                static String code(JsonNode body) {
                    return body == null ? "(not JSON)" : body.path("error").path("code").asText();
                }

                /** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
                static String when(HttpResponse<String> response) {
                    return response.headers().firstValue("Retry-After").map(s -> ", try again after " + s + " s").orElse("");
                }
            }
components:
  schemas:
    WithdrawalRequest:
      type: object
      required:
        - amount
        - idempotency_key
      properties:
        amount:
          description: >-
            A positive amount in shekels: a JSON number or a decimal string,
            with at most two decimals. Anything else, including three decimals,
            answers `422` `invalid_amount`.
          oneOf:
            - type: number
            - type: string
              pattern: ^[0-9]+(\.[0-9]{1,2})?$
          example: 125
        idempotency_key:
          type: string
          pattern: ^[A-Za-z0-9._-]{1,64}$
          maxLength: 64
          description: >-
            Your key for this request, unique per request you mean to make.
            Sending the same key and amount again answers the original request
            with `200`; the same key with another amount answers `409`
            `idempotency_conflict`. **Keys are compared without regard to
            case**: `AB` and `ab` are the same key.
          example: wd-2026-11-01-001
    SuccessEnvelope:
      type: object
      required:
        - status
        - status_code
        - message
        - data
        - meta
        - error
      properties:
        status:
          type: string
          enum:
            - success
        status_code:
          type: integer
          example: 200
        message:
          type: string
          example: OK
        data:
          type: object
          description: >-
            One key named after the resource (products / product / states /
            categories / attributes / order / validation).
        meta:
          nullable: true
          type: object
        error:
          nullable: true
          type: object
          enum:
            - null
    Withdrawal:
      type: object
      required:
        - withdrawal_id
        - amount
        - status
        - iban
        - reject_reason
        - requested_at
        - approved_at
        - paid_at
        - method
        - requested_amount
      properties:
        withdrawal_id:
          type: string
          description: >-
            Opaque. Use it in `GET /withdrawals/{withdrawal_id}` and in the
            cancel path.
          example: NDE
        amount:
          type: number
          format: float
          description: >-
            What is paid: what you asked for, unless Mart paid a cash request at
            another amount at the office counter (then `requested_amount` keeps
            what you asked for).
          example: 125
        status:
          type: string
          enum:
            - requested
            - approved
            - paid
            - rejected
            - cancelled
          description: >-
            `requested` and `approved` are open: they hold their amount back
            from `available`. `paid` is final and shows in the ledger as a
            `payment`. `rejected` and `cancelled` release the amount.
        iban:
          type: string
          nullable: true
          description: >-
            The IBAN this request will be paid to, fixed when it was approved,
            so a later change of your payout method cannot redirect it. Null
            before approval, on a request that was never approved, and always
            for cash.
          example: PS92PALS000000000400123456702
        reject_reason:
          type: string
          nullable: true
          description: Why Mart rejected it, in one line. Null for any other status.
          example: null
        requested_at:
          type: string
          format: date-time
          example: '2026-11-01T08:30:00+00:00'
        approved_at:
          type: string
          format: date-time
          nullable: true
          example: '2026-11-02T09:00:00+00:00'
        paid_at:
          type: string
          format: date-time
          nullable: true
          example: null
        method:
          type: string
          enum:
            - bank
            - cash
          description: >-
            How this request is paid, fixed when you made it: `bank` (approved,
            then transferred) or `cash` (collected at the office: it goes from
            `requested` straight to `paid`, and `approved_at` stays null).
          example: bank
        requested_amount:
          type: number
          format: float
          description: >-
            What you asked for. The same as `amount`, unless the office paid a
            cash request at another amount.
          example: 125
    ErrorEnvelope:
      type: object
      required:
        - status
        - status_code
        - message
        - data
        - meta
        - error
      properties:
        status:
          type: string
          enum:
            - fail
        status_code:
          type: integer
          example: 422
        message:
          type: string
        data:
          nullable: true
          enum:
            - null
        meta:
          nullable: true
          enum:
            - null
        error:
          type: object
          required:
            - code
            - details
          properties:
            code:
              type: string
              enum:
                - missing_api_key
                - invalid_api_key
                - key_environment_mismatch
                - api_customer_not_configured
                - customer_group_not_allowed
                - insufficient_scope
                - product_not_found
                - order_not_found
                - route_not_found
                - method_not_allowed
                - invalid_parameter
                - invalid_state
                - rate_limit_exceeded
                - bad_request
                - orders_not_enabled
                - api_group_misconfigured
                - idempotency_conflict
                - unknown_product
                - product_not_offered
                - product_not_orderable
                - combination_required
                - combination_not_allowed
                - unknown_combination
                - combination_mismatch
                - duplicate_product
                - cart_minimum_not_met
                - price_below_minimum
                - price_override_not_allowed
                - insufficient_stock
                - free_shipping_not_covered
                - free_shipping_not_allowed
                - card_not_enabled
                - internal_error
                - order_not_cancellable
                - order_cancellation_not_configured
                - order_cancellation_in_progress
                - card_not_on_file
                - saved_card_invalid
                - card_price_not_allowed
                - card_free_shipping_not_allowed
                - card_declined
                - payment_gateway_unavailable
                - order_creation_in_progress
                - charge_amount_mismatch
                - invalid_cursor
                - cursor_expired
                - ledger_unavailable
                - statement_not_found
                - withdrawals_disabled
                - invalid_iban
                - invalid_account_holder_name
                - invalid_national_id
                - invalid_amount
                - amount_below_minimum
                - payout_method_missing
                - withdrawals_locked
                - too_many_open_withdrawals
                - insufficient_available
                - withdrawal_busy
                - withdrawal_not_found
                - withdrawal_not_cancellable
                - cash_not_allowed
                - payout_method_change_blocked
                - amount_above_cash_maximum
                - invalid_payout_method
                - bank_transfer_not_allowed
            details:
              description: >-
                Structured context (parameter name, supported values, retry
                hints). Empty array when none.
  headers:
    X-Mart-Environment:
      description: >-
        Which installation answered: `production` or `sandbox`. Present on every
        response; assert it once at startup.
      schema:
        type: string
        enum:
          - production
          - sandbox
    X-RateLimit-Limit:
      description: Limit of the tightest active window.
      schema:
        type: integer
    X-RateLimit-Remaining:
      description: Requests remaining in the tightest active window.
      schema:
        type: integer
    X-RateLimit-Reset:
      description: Epoch seconds when the tightest window resets.
      schema:
        type: integer
  responses:
    BadRequest:
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
      description: >-
        The request body is missing, is not valid JSON, or is not a JSON object
        (`bad_request`).
    Unauthorized:
      description: >-
        Missing or unusable API key (`missing_api_key`, `invalid_api_key`).
        Revoked and paused keys answer identically to unknown keys. A key issued
        for the other environment answers `key_environment_mismatch` before any
        lookup: `details.environment` names the environment you called
        (`production` or `sandbox`) — switch base URL or key. See the
        Environments note in the introduction.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    WithdrawalsDisabled:
      description: >-
        Withdrawals are not enabled for your account (`withdrawals_disabled`),
        cash at the office is not offered to your account (`cash_not_allowed`),
        the key does not have the scope this endpoint needs
        (`insufficient_scope`), or the key's customer is missing, inactive or
        outside the allowed groups (`api_customer_not_configured`,
        `customer_group_not_allowed`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    MethodNotAllowed:
      description: >-
        The method is not accepted on this endpoint (`method_not_allowed`). Read
        the `Allow` response header rather than assuming; `OPTIONS` is accepted
        everywhere and answered as a bodyless 204.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    WithdrawalRefused:
      description: >-
        The request is understood and refused, and nothing was written.
        `payout_method_missing` (save a payout method first, cash included),
        `withdrawals_locked` (`details.locked_until`: the payout method changed
        and its lock has not passed), `too_many_open_withdrawals`
        (`details.maximum`), `insufficient_available` (`details.available`: the
        amount is above what `GET /balance` calls available),
        `idempotency_conflict` (this `idempotency_key` was already used for
        another amount), `withdrawal_not_cancellable` (cancel only). What each
        means and how to clear it: https://mart.ps/api/docs#errors.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    WithdrawalInvalid:
      description: >-
        The request cannot be read as a withdrawal: `invalid_amount` (not a
        positive number with at most two decimals), `amount_below_minimum`
        (`details.minimum`), `amount_above_cash_maximum` (`details.maximum`, a
        cash request only), `bank_transfer_not_allowed` (your saved payout
        method is an IBAN, and a bank transfer is not offered to your account:
        save cash at the office to withdraw), or `invalid_parameter`
        (`details.parameter` is `idempotency_key`, or `status` or a page
        parameter on the list). Nothing was written.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    TooManyRequests:
      description: >-
        Rate limit exceeded (`rate_limit_exceeded`). Carries `Retry-After`
        (seconds) plus the X-RateLimit-* trio of the exceeded window; day-window
        breaches advertise the day reset, not a 60-second retry.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    InternalError:
      description: >-
        Opaque server failure (`internal_error`). Details are logged server-side
        and never exposed.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    WithdrawalUnavailable:
      description: >-
        The ledger cannot be answered right now (`ledger_unavailable`, no
        `Retry-After`), or, on a request, this account is being changed by
        another call (`withdrawal_busy`, with `Retry-After` in seconds: retry
        with the same `idempotency_key`). Nothing is created by a `503`, but a
        request that timed out may have been: retry with the same key and read
        the answer.
      headers:
        X-Mart-Environment:
          $ref: '#/components/headers/X-Mart-Environment'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 'Authorization: Bearer <key>'
    apiKeyHeader:
      type: apiKey
      in: header
      name: X-Api-Key

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.