cURL 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("");
}
}
{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"account": {
"shop_display_name": "Al Noor Shop",
"status": "active",
"orders_enabled": true,
"card_enabled": false,
"price_override_allowed": true,
"free_shipping_allowed": false,
"rate_limits": {
"per_minute": 120,
"per_day": 20000
},
"payout_method_saved": false,
"withdrawals": {
"enabled": false,
"minimum": null,
"max_open_requests": null
},
"money": {
"available": true
}
}
},
"meta": null,
"error": null
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}Your account
Your own account in one read: the shop name, whether it is active, paused or closed, what your key may do, your request limits, whether a payout method is saved, the withdrawal rules and whether the money endpoints can be read right now. The shape is the same for every partner. It always answers 200 once you are authenticated: a paused or closed account still reads it, and when the ledger cannot be read only money.available is false (the money endpoints answer 503 ledger_unavailable for that). orders_enabled is the effective value, your key’s flag and the account being active. Withdrawal numbers are null when withdrawals are off or no number has been set. Full behaviour: https://mart.ps/api/docs#account/account.
GET
/
api
/
v1
/
account
cURL 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("");
}
}
{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"account": {
"shop_display_name": "Al Noor Shop",
"status": "active",
"orders_enabled": true,
"card_enabled": false,
"price_override_allowed": true,
"free_shipping_allowed": false,
"rate_limits": {
"per_minute": 120,
"per_day": 20000
},
"payout_method_saved": false,
"withdrawals": {
"enabled": false,
"minimum": null,
"max_open_requests": null
},
"money": {
"available": true
}
}
},
"meta": null,
"error": null
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}Response
Your account.
