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.pswhile you build,https://mart.pswhen you go live.
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
#!/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"
// 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}`);
"""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
// 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: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)
}
// 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
environment: sandbox
account status: active
orders enabled: true
environmentis theX-Mart-Environmentheader. If it is not the one you meant, fixMART_API_BASEfirst.account statusisactive,paused(reads work, no new orders) orclosed.orders enabledistruewhen 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. |
