> ## 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)).

# Recipe: make your first authenticated call

> Make your first authenticated call to the Mart Partner API in cURL, TypeScript, Python, PHP, Go or Java, with a timeout and the key read from the environment.

This recipe reads your account with `GET /api/v1/account` and prints which environment answered, the account status and whether your key may place orders. Run it whenever you set up a new key or server.

## Prerequisites

* **`MART_API_KEY`**: your API key, any scope.
* **`MART_API_BASE`**: `https://sandbox.mart.ps` while you build, `https://mart.ps` when you go live.

**One runtime:** cURL 7.84 or later with `jq`; Node 22.18 or later, which runs the `.ts` file as it is; Python 3.9 or later with `httpx`; PHP 7.4 or later with its curl extension; Go 1.22 or later; or Java 17 or later with Jackson (`jackson-databind`). Each file reads its variables from the environment and sets a timeout on every call. Run it on your own server: a browser or an app never holds the key.

## Run the recipe

```bash cURL theme={null}
#!/usr/bin/env bash
# Make your first call: read your own account.
# Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.
set -euo pipefail

# The key goes to curl through a file descriptor, so it never shows in the process list.
response=$(curl --silent --show-error --max-time 30 \
  --header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") \
  --write-out '\n%{http_code} %header{x-mart-environment} %header{retry-after}' \
  "$MART_API_BASE/api/v1/account") || { echo "error: no answer" >&2; exit 1; }
body=${response%$'\n'*}
read -r status environment retry_after <<<"${response##*$'\n'}"

if [ "$status" != 200 ]; then
  echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}" >&2
  exit 1
fi

# Every answer names the installation that served it: check it before anything else.
echo "environment: $environment"
jq -r '.data.account | "account status: \(.status)\norders enabled: \(.orders_enabled)"' <<<"$body"
```

```typescript TypeScript theme={null}
// Make your first call: read your own account. Node 22.18 or later runs this .ts file as it is.
// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
if (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');

const response = await fetch(`${base}/api/v1/account`, {
  headers: { Authorization: `Bearer ${key}` },
  signal: AbortSignal.timeout(30_000),
});
const body = await response.json().catch(() => null); // an edge error page is not JSON
if (!response.ok || body === null) {
  const retryAfter = response.headers.get('retry-after');
  console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);
  process.exit(1);
}

// Every answer names the installation that served it: check it before anything else.
console.log(`environment: ${response.headers.get('x-mart-environment')}`);
console.log(`account status: ${body.data.account.status}`);
console.log(`orders enabled: ${body.data.account.orders_enabled}`);
```

```python Python theme={null}
"""Make your first call: read your own account. Python 3.9 or later, with httpx.

Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.
"""
import os
import sys

import httpx

base = os.environ["MART_API_BASE"]
key = os.environ["MART_API_KEY"]

response = httpx.get(f"{base}/api/v1/account", headers={"Authorization": f"Bearer {key}"}, timeout=30)
try:
    body = response.json()
except ValueError:  # an edge error page is not JSON
    body = None
if response.is_error or body is None:
    retry_after = response.headers.get("Retry-After")
    sys.exit(f"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}"
             + (f", try again after {retry_after} s" if retry_after else ""))

# Every answer names the installation that served it: check it before anything else.
print(f"environment: {response.headers['X-Mart-Environment']}")
account = body["data"]["account"]
print(f"account status: {account['status']}")
print(f"orders enabled: {str(account['orders_enabled']).lower()}")
```

```php PHP theme={null}
<?php
// Make your first call: read your own account. PHP 7.4 or later, with the curl extension.
// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.
$base = getenv('MART_API_BASE');
$key = getenv('MART_API_KEY');

/**
 * 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" : '';
}

[$status, $headers, $raw] = request('GET', "$base/api/v1/account", $key);
$body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)
if ($status !== 200 || !is_array($body)) {
    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)')) . when($headers) . "\n");
    exit(1);
}

// Every answer names the installation that served it: check it before anything else.
echo "environment: {$headers['x-mart-environment']}\n";
$account = $body['data']['account'];
echo "account status: {$account['status']}\n";
echo 'orders enabled: ' . ($account['orders_enabled'] ? 'true' : 'false') . "\n";
```

```go Go theme={null}
//go:build ignore

// Make your first call: read your own account. Go 1.22 or later, standard library only.
// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.
// Run it with: go run first-call.go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

var client = &http.Client{Timeout: 30 * time.Second}

func main() {
	req, err := http.NewRequest(http.MethodGet, os.Getenv("MART_API_BASE")+"/api/v1/account", nil)
	if err != nil {
		fail(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
	resp, err := client.Do(req)
	if err != nil {
		fail(fmt.Errorf("no answer: %v", err))
	}
	environment := resp.Header.Get("X-Mart-Environment")

	var body struct {
		Data struct {
			Account struct {
				Status        string `json:"status"`
				OrdersEnabled bool   `json:"orders_enabled"`
			} `json:"account"`
		} `json:"data"`
	}
	decode(resp, &body)

	// Every answer names the installation that served it: check it before anything else.
	fmt.Println("environment:", environment)
	fmt.Println("account status:", body.Data.Account.Status)
	fmt.Println("orders enabled:", body.Data.Account.OrdersEnabled)
}

// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),
// stops with its status and error code.
func decode(resp *http.Response, out any) {
	defer resp.Body.Close()
	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		fail(err)
	}
	var envelope struct {
		Error *struct {
			Code string `json:"code"`
		} `json:"error"`
	}
	if resp.StatusCode >= 300 {
		code := "(not JSON)"
		if json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {
			code = envelope.Error.Code
		}
		wait := ""
		if after := resp.Header.Get("Retry-After"); after != "" {
			wait = ", try again after " + after + " s"
		}
		fail(fmt.Errorf("%d %s%s", resp.StatusCode, code, wait))
	}
	if err := json.Unmarshal(raw, out); err != nil {
		fail(fmt.Errorf("%d (not JSON)", resp.StatusCode))
	}
}

func fail(err error) {
	fmt.Fprintln(os.Stderr, "error:", err)
	os.Exit(1)
}
```

```java Java theme={null}
// Make your first call: read your own account. Java 17 or later, with Jackson (jackson-databind).
// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.
// Run it as a single file: java -cp <the Jackson jars> first-call.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;

class FirstCall {
    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 {
        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/account"))
                .header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
                .timeout(Duration.ofSeconds(30))
                .GET()
                .build();
        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
        JsonNode body = parse(response.body());
        if (response.statusCode() >= 300 || body == null) {
            fail(response.statusCode() + " " + code(body) + when(response));
        }

        // Every answer names the installation that served it: check it before anything else.
        System.out.println("environment: " + response.headers().firstValue("X-Mart-Environment").orElse(""));
        JsonNode account = body.path("data").path("account");
        System.out.println("account status: " + account.path("status").asText());
        System.out.println("orders enabled: " + account.path("orders_enabled").asBoolean());
    }

    /** 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("");
    }
}
```

## Verify the result

```text theme={null}
environment: sandbox
account status: active
orders enabled: true
```

* **`environment`** is the `X-Mart-Environment` header. If it is not the one you meant, fix `MART_API_BASE` first.
* **`account status`** is `active`, `paused` (reads work, no new orders) or `closed`.
* **`orders enabled`** is `true` when your key may create orders.

## Troubleshooting

| Any recipe | What to do |
| - | - |
| `401` `missing_api_key` or `invalid_api_key` | Check that `MART_API_KEY` holds the whole key. A key still refused needs a replacement from Mart. |
| `401` `key_environment_mismatch` | Point `MART_API_BASE` at the environment that issued the key. |
| `403` `insufficient_scope` | Ask Mart to add the scope in `details.required_scope`. |
| `429` `rate_limit_exceeded` | Wait the `Retry-After` the error line shows, then run it again. |
| `error: no answer`, or a timeout | Check `MART_API_BASE` and your network. |
| `error:` with `(not JSON)` | A proxy or firewall answered, not the API. Check `MART_API_BASE` and your network. |

Every other code is in the [error catalog](https://docs.mart.ps/developers/operate/error-catalog.md).


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