Code samples

Code samples

Runnable, tested examples of the Outboxer REST API (https://api.outboxer.dev/v1) in seven languages. Each one runs the same end-to-end flow, uses only its language's standard library (plus jq for the shell version), and reads its settings from the environment:

Variable Default
OUTBOXER_API_KEY (required) Your API key, obx_live_…, created in the Outboxer app
OUTBOXER_WORKSPACE the key's first workspace Workspace slug or ws_ id
OUTBOXER_CHANNEL_IDS ready X and LinkedIn channels Comma-separated ch_ ids of connected channels to post to
OUTBOXER_SCHEDULE_AT tomorrow 10am When the post goes out: ISO-8601 or a phrase like fri 17:30, in the workspace timezone
OUTBOXER_API_URL https://api.outboxer.dev API origin, without /v1

Every request is live: the samples post to the social accounts you connected in the Outboxer app. They can't connect accounts themselves (connecting needs the account owner's OAuth sign-in), so connect at least one channel in the app first. To stay safe, the default flow schedules the post for later instead of publishing it.

The flow:

  1. GET /v1/me: print the principal and its workspaces with their abilities.
  2. GET /v1/workspaces/{ws}/connections: print each connected channel's id, ready flag and problems. Use the channels in OUTBOXER_CHANNEL_IDS (each must be ready), or else the ready X and LinkedIn channels, or else the first ready channel.
  3. GET /v1/billing: print the credit balance. A key without billing:read gets 403, which the samples report without failing.
  4. POST /v1/workspaces/{ws}/validate: dry-run an empty draft and the real one, printing each issue's path, code and hint. Nothing is saved.
  5. POST /v1/workspaces/{ws}/posts with an Idempotency-Key, schedule: {mode: "exact", at: …} (the proposed time) and submit_for_review: true, then the identical request again, which comes back with Idempotent-Replayed: true and the same post.
  6. If /me lists posts.approve and posts.publish for the workspace: POST /v1/posts/{id}/approve with {"schedule": {"mode": "proposed"}}, which leaves the post scheduled for the proposed time. Otherwise the sample says a person must approve the post (agents can't approve their own posts).
  7. Send a deliberately invalid body to show the typed RFC 9457 error with errors[].

Warning: with --publish-now, step 6 approves the post without a time, calls POST /v1/posts/{id}/publish-now and polls GET /v1/posts/{id} until every channel is done. That publishes immediately, for real, on the selected accounts. Leave it off unless that's what you want.

Each sample also has a webhook-selftest mode, which signs a sample event and verifies it, including a known-answer vector produced by Outboxer's webhook signer.

Language Runnable files Run
curl + jq examples/curl/flow.sh ./flow.sh
TypeScript (Node 22) examples/node/flow.ts, client.ts node --experimental-strip-types flow.ts
Python 3.11 examples/python/flow.py, outboxer_client.py python3 flow.py
PHP 8.3 examples/php/flow.php php flow.php
Go 1.24 examples/go/main.go, go.mod go run .
Ruby 3.3 examples/ruby/flow.rb ruby flow.rb
Java 21 examples/java/Flow.java java Flow.java

Each folder has a README with details. The Python and PHP READMEs also show requests, Guzzle and Laravel Http versions. The snippets below are excerpts from these files, lightly trimmed (some error checks and printing are left out). For the rules behind them, see conventions and webhooks.

Authenticated request helper#

One function sends every request. It adds Authorization: Bearer <key>, sends and parses JSON, and gives every POST an Idempotency-Key. It retries 429 (waiting Retry-After seconds), 5xx, network errors and 409 idempotency_request_in_progress with exponential backoff. Every retry uses the same key and the same body bytes, so a retried create can't make a second post.

OB="${OUTBOXER_API_URL:-https://api.outboxer.dev}/v1"

# api METHOD PATH [JSON_BODY] [IDEMPOTENCY_KEY]  -> prints the body; headers in $TMP/headers
api() {
  local method=$1 path=$2 body=${3:-} key=${4:-} attempt=0 status delay
  local -a args=(-sS -X "$method" "$OB$path" -H "Authorization: Bearer $OUTBOXER_API_KEY"
                 -H 'Accept: application/json' -o "$TMP/body" -D "$TMP/headers" -w '%{http_code}')
  [[ -n $body ]] && args+=(-H 'Content-Type: application/json' --data-binary "$body")
  if [[ $method == POST ]]; then args+=(-H "Idempotency-Key: ${key:-$(uuid)}"); fi

  while :; do
    status=$(curl "${args[@]}" 2>/dev/null) || status=000          # 000 = network error
    if [[ $status == 2* ]]; then cat "$TMP/body"; return 0; fi
    local code=""
    [[ $status != 000 ]] && code=$(jq -r '.code // empty' "$TMP/body" 2>/dev/null || true)
    if (( attempt < MAX_RETRIES )) && [[ $status == 000 || $status == 429 || $status == 5* || $code == idempotency_request_in_progress ]]; then
      delay=$(grep -i '^retry-after:' "$TMP/headers" 2>/dev/null | tr -dc '0-9' || true)
      [[ -z $delay ]] && delay=$(( 1 << attempt ))                  # backoff: 1 s, 2 s, 4 s, 8 s
      sleep "$delay"; attempt=$((attempt + 1)); continue
    fi
    cp "$TMP/body" "$TMP/problem.json"                               # see "Error handling"
    return 1
  done
}

me=$(api GET /me)

Create a post with idempotency#

The draft goes to channels picked from GET /v1/workspaces/{ws}/connections and carries a proposed time in schedule. Generate one key per logical action and keep it for every retry of that action. The server stores the first final response for 24 hours. Sending the same key with the same method, path and body replays that response with Idempotent-Replayed: true, so nothing runs twice. Sending the same key with a different body returns 422 idempotency_key_reused. Transient outcomes (409, 412, 423, 425, 428, 429, 5xx) aren't stored, so a retry with the same key gets a fresh attempt. See conventions → Idempotency-Key.

draft=$(jq -nc --argjson v "$variants" --arg at "$SCHEDULE_AT" '{
  base: {text: "Autumn roast is here: Guji pour-over at 1:16 and 93°C. What’s your ratio?"},
  variants: $v, schedule: {mode: "exact", at: $at}, submit_for_review: true}')

key=$(uuid)
post=$(api POST "/workspaces/$slug/posts" "$draft" "$key")
id=$(jq -r .id <<<"$post")
echo "Created $id: status=$(jq -r .status <<<"$post"), ETag $(header etag)"

again=$(api POST "/workspaces/$slug/posts" "$draft" "$key")           # same key, same body
echo "Replayed: $(header idempotent-replayed), same post: $(jq -r .id <<<"$again")"

The post comes back in_review with proposed_at set and ETag: "<post_id>:<version>". (If the workspace has an auto-approve policy that matches, it may come back already scheduled.)

Approve and schedule#

Approving and scheduling need the posts:approve and posts:publish scopes and a role that allows them. Agents don't get these by default and can never approve their own posts, so the samples check workspaces[].abilities from /me first. schedule.mode: "proposed" keeps the time the draft proposed; the post becomes scheduled and goes out then. Until it does, POST /v1/posts/{id}/unschedule (back to approved) or POST /v1/posts/{id}/archive stops it.

if [[ $(jq '.abilities | index("posts.approve") != null and index("posts.publish") != null' <<<"$ws") == true ]]; then
  post=$(api POST "/posts/$id/approve" '{"schedule":{"mode":"proposed"}}')
  echo "Approved: status=$(jq -r .status <<<"$post"), scheduled_at=$(jq -r .scheduled_at <<<"$post")"
else
  echo "A human reviewer must approve $id."
fi

To publish right away instead, approve with {"schedule": {"mode": "none"}} and then call POST /v1/posts/{id}/publish-now. Publishing runs on a queue, so poll GET /v1/posts/{id} (or wait for the post.published webhook) until the status is published, partially_published or failed. The samples only do this with --publish-now, because it posts for real straight away.

Error handling#

Every error is application/problem+json (RFC 9457) with a stable code. Branch on code, not on detail or type. Request-shape errors (422 invalid_request) carry errors[], each with code, path in bracket notation, message and hint. The samples turn a problem into a typed error and only retry the transient cases:

Status / code What the samples do
429 rate_limited, 429 quota_exceeded Wait Retry-After seconds, then retry with the same Idempotency-Key.
5xx (internal_error, provider_error, …) and network errors Exponential backoff with jitter (0.5 s, 1 s, 2 s, 4 s), same key.
409 idempotency_request_in_progress The first request with this key is still running. Back off, then retry with the same key.
403 missing_scope on GET /v1/billing Report "not visible to this key" and carry on.
403 self_approval_forbidden, missing_scope, role_forbidden on approve Hand off to a human reviewer.
Anything else (401, 404, 409 invalid_transition, 422 …) Raise. Fix the request, and send it with a new key, because final outcomes are replayed.
# On failure, api() leaves the problem in $TMP/problem.json and returns 1.
if ! api POST "/workspaces/$slug/validate" '{"variants":"not-a-list"}' >/dev/null 2>&1; then
  jq -r '"Typed error: \(.status) \(.code) (request \(.request_id))",
    (.errors[]? | "   \(.path): \(.code) - \(.hint // .message)")' "$TMP/problem.json"
fi

if billing=$(api GET /billing 2>/dev/null); then
  jq -r '"Balance: \(.balance_formatted)"' <<<"$billing"
elif [[ $(jq -r .status "$TMP/problem.json") == 403 ]]; then
  echo "Balance: not visible to this key ($(jq -r .code "$TMP/problem.json"))"
fi

Validation issues are different from errors. POST /v1/workspaces/{ws}/validate returns 200 with valid, error_count, warning_count and issues[] (severity, code, path, message, hint, channel_id). Fix every severity: "error" before creating the post: errors block approval with 422 validation_failed.

Webhook verification#

Each delivery is a POST whose Outboxer-Signature header is t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>. To verify a delivery:

  1. Use the raw body bytes, never re-serialized JSON.
  2. Reject a t more than 5 minutes from now.
  3. Compare signatures in constant time.
  4. Deduplicate on the envelope id, because retries and redeliveries resend the same event.

Answer 2xx within 10 seconds. The full event list is in webhooks.

# verify_webhook SECRET SIGNATURE_HEADER RAW_BODY_FILE [NOW] -> prints the event JSON, or returns 1
verify_webhook() {
  local secret=$1 header=$2 file=$3 now=${4:-$(date +%s)} t v1 expected nonce
  t=$(tr ',' '\n' <<<"$header" | sed -n 's/^ *t=//p')
  v1=$(tr ',' '\n' <<<"$header" | sed -n 's/^ *v1=//p')
  [[ $t =~ ^[0-9]+$ && $v1 =~ ^[0-9a-f]{64}$ ]] || { echo "malformed signature header" >&2; return 1; }
  (( now - t <= 300 && t - now <= 300 )) || { echo "timestamp outside tolerance" >&2; return 1; }
  expected=$( { printf '%s.' "$t"; cat "$file"; } | openssl dgst -sha256 -hmac "$secret" -r | cut -d' ' -f1)
  # Bash has no constant-time compare: compare HMACs of both values under a random key instead.
  nonce=$(openssl rand -hex 32)
  [[ $(printf '%s' "$expected" | openssl dgst -sha256 -hmac "$nonce" -r) == \
     $(printf '%s' "$v1" | openssl dgst -sha256 -hmac "$nonce" -r) ]] || { echo "signature mismatch" >&2; return 1; }
  jq . "$file"
}

Every sample's webhook-selftest checks this test vector, which was produced by Outboxer's webhook signer. Use it to test your own verifier:

Text
secret:  whsec_test_secret
t:       1791218168
body:    {"id":"evt_test","type":"post.published","data":{"post_id":"post_test"}}
header:  t=1791218168,v1=ebdb6cc1d18f88c25853b9ed1c12443f0ea1adaee11b3512744ac3764e1e56e6

Run the samples#

Connect your accounts in the Outboxer app first, then create an API key there. A person's key with the approve and publish permissions runs the whole flow; an agent key stops after submitting for review.

Shell
export OUTBOXER_API_KEY=obx_live_…
export OUTBOXER_WORKSPACE=acme                      # optional
export OUTBOXER_CHANNEL_IDS=ch_…                    # optional: copy ids from step 2 of a first run

(cd examples/curl   && ./flow.sh)
(cd examples/node   && node --experimental-strip-types flow.ts)
(cd examples/python && python3 flow.py)
(cd examples/php    && php flow.php)
(cd examples/go     && go run .)
(cd examples/ruby   && ruby flow.rb)
(cd examples/java   && java Flow.java)

# Webhook self-tests need no API: append webhook-selftest to any of the commands above, e.g.
(cd examples/python && python3 flow.py webhook-selftest)

Sample output with an owner key (Python):

Text
1. Principal: user Maya Chen (usr_01m4rryex9effrmta2h5qjrvca), key obx_live_HtNy…
   workspace acme: role=owner, 25 abilities
2. Channels in acme: 3/4 ready
   ch_01m4rryeyqb2pe6hc07y6v8422  instagram  ready=false problems=needs_reconnect Acme Coffee · Instagram
   ch_01m4rryey7yyrr5zgqdkf9czbn  linkedin   ready=true  problems=-            Acme Coffee · LinkedIn
   ch_01m4rryeyxhqrfhy2qvbmftdr9  threads    ready=true  problems=-            Acme Coffee · Threads
   ch_01m4rryexzz0gby3vtavt2wbq6  x          ready=true  problems=-            Acme Coffee · X (Twitter)
   using: linkedin (Acme Coffee · LinkedIn), x (Acme Coffee · X (Twitter))
3. Balance: $42.00 (low_balance=false)
4. Validate an empty draft: valid=false, 2 errors
   [error] linkedin: base.text empty_post - The post has no text and no media.
   [error] x: base.text empty_post - The post has no text and no media.
   Validate the real draft: valid=true, 0 warnings
5. Created post_01m4rs0wykp2xw65m30071b3c1: status=in_review, proposed_at=2026-10-13T14:00:00Z, ETag "post_01m4rs0wykp2xw65m30071b3c1:1"
   Retry with the same key -> post_01m4rs0wykp2xw65m30071b3c1 (Idempotent-Replayed: true, same post: True)
6. Approved: status=scheduled, scheduled_at=2026-10-13T14:00:00Z
   It goes live at that time. To stop it, POST /v1/posts/post_01m4rs0wykp2xw65m30071b3c1/unschedule or /archive.
7. Typed error: 422 invalid_request (request req_01m4rs0x3fa0rjk8jat1gyf396)
   variants: invalid_field - `variants` must be a JSON array/object.

Notes:

  • The post really goes out at scheduled_at. Unschedule or archive it before then if you only wanted to try the flow.
  • Later runs warn near_duplicate_content, because the sample proposes similar copy every time. A warning doesn't block approval. An error would.
  • If no channel is ready, the samples stop at step 2. Reconnect the channel in the Outboxer app (the problems[] codes say why, for example needs_reconnect or token_expired), then run again.
  • With --publish-now, step 6 prints publish-now: status=publishing and then each channel's publish_status and permalink once publishing finishes (the samples poll for up to 60 seconds).