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:
GET /v1/me: print the principal and its workspaces with theirabilities.GET /v1/workspaces/{ws}/connections: print each connected channel's id,readyflag andproblems. Use the channels inOUTBOXER_CHANNEL_IDS(each must be ready), or else the ready X and LinkedIn channels, or else the first ready channel.GET /v1/billing: print the credit balance. A key withoutbilling:readgets403, which the samples report without failing.POST /v1/workspaces/{ws}/validate: dry-run an empty draft and the real one, printing each issue'spath,codeandhint. Nothing is saved.POST /v1/workspaces/{ws}/postswith anIdempotency-Key,schedule: {mode: "exact", at: …}(the proposed time) andsubmit_for_review: true, then the identical request again, which comes back withIdempotent-Replayed: trueand the same post.- If
/melistsposts.approveandposts.publishfor the workspace:POST /v1/posts/{id}/approvewith{"schedule": {"mode": "proposed"}}, which leaves the postscheduledfor the proposed time. Otherwise the sample says a person must approve the post (agents can't approve their own posts). - 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, callsPOST /v1/posts/{id}/publish-nowand pollsGET /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)async request<T>(method: string, path: string, body?: unknown, idempotencyKey?: string): Promise<ApiResponse<T>> {
const headers: Record<string, string> = { Authorization: `Bearer ${this.apiKey}`, Accept: 'application/json' };
const payload = body === undefined ? undefined : JSON.stringify(body);
if (payload !== undefined) headers['Content-Type'] = 'application/json';
if (method === 'POST') headers['Idempotency-Key'] = idempotencyKey ?? randomUUID();
for (let attempt = 0; ; attempt++) {
let res: Response;
try {
res = await fetch(this.baseUrl + path, { method, headers, body: payload });
} catch (err) {
if (attempt >= this.maxRetries) throw err; // network error: safe to retry, the key is unchanged
await sleep(backoff(attempt));
continue;
}
const text = await res.text();
if (res.ok) return { status: res.status, headers: res.headers, data: (text ? JSON.parse(text) : null) as T };
const err = new OutboxerError(res.status, parseProblem(text, res));
const retryable = res.status === 429 || res.status >= 500 || err.code === 'idempotency_request_in_progress';
if (!retryable || attempt >= this.maxRetries) throw err;
const retryAfter = Number(res.headers.get('Retry-After') ?? err.problem.retry_after);
await sleep(Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter * 1000 : backoff(attempt));
}
}
const ob = new OutboxerClient(process.env.OUTBOXER_API_URL ?? 'https://api.outboxer.dev', apiKey);
const me = await ob.get<Me>('/me');def request(self, method, path, body=None, idempotency_key=None) -> Response:
headers = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body).encode() # serialize once: retries must send the same bytes
headers["Content-Type"] = "application/json"
if method == "POST":
headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
for attempt in range(self.max_retries + 1):
req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=self.timeout) as res:
raw = res.read()
return Response(res.status, {k.lower(): v for k, v in res.headers.items()},
json.loads(raw) if raw else None)
except urllib.error.HTTPError as e:
raw = e.read()
try:
problem = json.loads(raw) if raw else {}
except json.JSONDecodeError:
problem = {"detail": raw.decode(errors="replace")}
err = OutboxerError(e.code, problem)
retryable = e.code == 429 or e.code >= 500 or err.code in self.RETRYABLE_CONFLICTS
if not retryable or attempt == self.max_retries:
raise err from None
time.sleep(self._delay(attempt, e.headers.get("Retry-After") or problem.get("retry_after")))
except urllib.error.URLError:
if attempt == self.max_retries: # network error: safe to retry, the key is unchanged
raise
time.sleep(self._delay(attempt, None))
ob = Client(os.environ.get("OUTBOXER_API_URL", "https://api.outboxer.dev"), os.environ["OUTBOXER_API_KEY"])
me = ob.get("/me")public function request(string $method, string $path, mixed $body = null, ?string $idempotencyKey = null): OutboxerResponse
{
$headers = ['Authorization: Bearer '.$this->apiKey, 'Accept: application/json'];
$payload = $body === null ? null : json_encode($body, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($payload !== null) {
$headers[] = 'Content-Type: application/json';
}
if ($method === 'POST') {
$headers[] = 'Idempotency-Key: '.($idempotencyKey ?? self::uuid());
}
for ($attempt = 0; ; $attempt++) {
[$status, $responseHeaders, $raw, $networkError] = $this->send($method, $path, $headers, $payload); // curl_exec
if ($networkError !== null) {
if ($attempt >= $this->maxRetries) {
throw new RuntimeException("Network error: {$networkError}");
}
usleep(self::backoff($attempt, null)); // safe to retry: the key is unchanged
continue;
}
$data = $raw === '' ? null : json_decode($raw, true);
if ($status >= 200 && $status < 300) {
return new OutboxerResponse($status, $responseHeaders, $data);
}
$error = new OutboxerError($status, is_array($data) ? $data : ['detail' => (string) $raw]);
$retryable = $status === 429 || $status >= 500 || $error->errorCode === 'idempotency_request_in_progress';
if (! $retryable || $attempt >= $this->maxRetries) {
throw $error;
}
usleep(self::backoff($attempt, $responseHeaders['retry-after'] ?? $data['retry_after'] ?? null));
}
}
$ob = new OutboxerClient(getenv('OUTBOXER_API_URL') ?: 'https://api.outboxer.dev', getenv('OUTBOXER_API_KEY'));
$me = $ob->get('/me');func (c *Client) Do(method, path string, body any, idempotencyKey string, out any) (http.Header, error) {
var payload []byte
if body != nil {
var err error
if payload, err = json.Marshal(body); err != nil { // marshal once: retries send the same bytes
return nil, err
}
}
if method == http.MethodPost && idempotencyKey == "" {
idempotencyKey = NewUUID()
}
for attempt := 0; ; attempt++ {
req, _ := http.NewRequest(method, c.BaseURL+path, bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+c.APIKey)
req.Header.Set("Accept", "application/json")
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
if method == http.MethodPost {
req.Header.Set("Idempotency-Key", idempotencyKey)
}
res, err := c.HTTP.Do(req)
if err != nil { // network error: safe to retry, the key is unchanged
if attempt >= c.MaxRetries {
return nil, err
}
time.Sleep(backoff(attempt, ""))
continue
}
raw, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode < 300 {
if out != nil && len(raw) > 0 {
return res.Header, json.Unmarshal(raw, out)
}
return res.Header, nil
}
apiErr := &Error{Status: res.StatusCode, Code: "http_error", Detail: string(raw)}
_ = json.Unmarshal(raw, apiErr)
retryable := res.StatusCode == 429 || res.StatusCode >= 500 || apiErr.Code == "idempotency_request_in_progress"
if !retryable || attempt >= c.MaxRetries {
return res.Header, apiErr
}
time.Sleep(backoff(attempt, res.Header.Get("Retry-After")))
}
}
ob := NewClient(envOr("OUTBOXER_API_URL", "https://api.outboxer.dev"), os.Getenv("OUTBOXER_API_KEY"))
var me Me
err := ob.Get("/me", &me)def request(method, path, body = nil, idempotency_key: nil)
uri = URI("#{@base}#{path}")
payload = body.nil? ? nil : JSON.generate(body) # serialize once: retries send the same bytes
headers = { 'Authorization' => "Bearer #{@api_key}", 'Accept' => 'application/json' }
headers['Content-Type'] = 'application/json' if payload
headers['Idempotency-Key'] = idempotency_key || SecureRandom.uuid if method == 'POST'
attempt = 0
loop do
begin
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', read_timeout: 30) do |http|
http.send_request(method, uri.request_uri, payload, headers)
end
rescue *RETRYABLE_NETWORK
raise if attempt >= @max_retries # network error: safe to retry, the key is unchanged
sleep backoff(attempt, nil)
attempt += 1
next
end
data = res.body.to_s.empty? ? nil : JSON.parse(res.body)
status = res.code.to_i
return Response.new(status, res.to_hash.transform_values(&:first), data) if status.between?(200, 299)
err = Error.new(status, data.is_a?(Hash) ? data : { 'detail' => res.body.to_s })
retryable = status == 429 || status >= 500 || err.code == 'idempotency_request_in_progress'
raise err if !retryable || attempt >= @max_retries
sleep backoff(attempt, res['Retry-After'] || err.problem['retry_after'])
attempt += 1
end
end
ob = Outboxer::Client.new(ENV.fetch('OUTBOXER_API_URL', 'https://api.outboxer.dev'), ENV.fetch('OUTBOXER_API_KEY'))
me = ob.get('/me')public ApiResponse request(String method, String path, Object body, String idempotencyKey) {
String payload = body == null ? null : Json.stringify(body); // serialize once: retries send the same bytes
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(baseUrl + path))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "Bearer " + apiKey)
.header("Accept", "application/json")
.method(method, payload == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(payload, StandardCharsets.UTF_8));
if (payload != null) b.header("Content-Type", "application/json");
if (method.equals("POST")) b.header("Idempotency-Key", idempotencyKey != null ? idempotencyKey : UUID.randomUUID().toString());
HttpRequest req = b.build();
for (int attempt = 0; ; attempt++) {
HttpResponse<String> res;
try {
res = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch (ConnectException | HttpTimeoutException e) {
if (attempt >= maxRetries) throw new RuntimeException("Network error: " + e.getMessage(), e);
sleep(backoff(attempt, null)); // safe to retry: the key is unchanged
continue;
} catch (java.io.IOException | InterruptedException e) {
throw new RuntimeException(e);
}
Object data = res.body().isEmpty() ? null : parseOrText(res.body());
if (res.statusCode() >= 200 && res.statusCode() < 300) return new ApiResponse(res.statusCode(), res, data);
Map<String, Object> problem = data instanceof Map<?, ?> ? Json.obj(data) : new HashMap<>(Map.of("detail", res.body()));
OutboxerException err = new OutboxerException(res.statusCode(), problem);
boolean retryable = res.statusCode() == 429 || res.statusCode() >= 500
|| err.code().equals("idempotency_request_in_progress");
if (!retryable || attempt >= maxRetries) throw err;
sleep(backoff(attempt, res.headers().firstValue("Retry-After").orElse(null)));
}
}
var ob = new OutboxerClient(System.getenv().getOrDefault("OUTBOXER_API_URL", "https://api.outboxer.dev"), System.getenv("OUTBOXER_API_KEY"));
var me = ob.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")"const draft: PostInput = {
base: { text: "Autumn roast is here: Guji pour-over at 1:16 and 93°C. What's your ratio?" },
variants: chosen.map((ch) => ({ channel_id: ch.channel_id })),
schedule: { mode: 'exact', at: scheduleAt }, // e.g. 'tomorrow 10am' (workspace timezone) or ISO-8601
submit_for_review: true,
};
const key = randomUUID();
const first = await ob.request<Post>('POST', `/workspaces/${ws.slug}/posts`, draft, key);
console.log(`Created ${first.data.id}: status=${first.data.status}, ETag ${first.headers.get('etag')}`);
const again = await ob.request<Post>('POST', `/workspaces/${ws.slug}/posts`, draft, key);
console.log(`Replayed: ${again.headers.get('idempotent-replayed')}, same post: ${again.data.id === first.data.id}`);draft = {
"base": {"text": "Autumn roast is here: Guji pour-over at 1:16 and 93°C. What's your ratio?"},
"variants": [{"channel_id": ch["channel_id"]} for ch in chosen],
"schedule": {"mode": "exact", "at": schedule_at}, # e.g. "tomorrow 10am" (workspace timezone) or ISO-8601
"submit_for_review": True,
}
key = str(uuid.uuid4())
first = ob.request("POST", f"/workspaces/{ws['slug']}/posts", draft, idempotency_key=key)
print(f"Created {first.data['id']}: status={first.data['status']}, ETag {first.headers.get('etag')}")
again = ob.request("POST", f"/workspaces/{ws['slug']}/posts", draft, idempotency_key=key)
print(f"Replayed: {again.headers.get('idempotent-replayed')}, same post: {again.data['id'] == first.data['id']}")$draft = [
'base' => ['text' => "Autumn roast is here: Guji pour-over at 1:16 and 93°C. What's your ratio?"],
'variants' => array_map(fn ($ch) => ['channel_id' => $ch['channel_id']], $chosen),
'schedule' => ['mode' => 'exact', 'at' => $scheduleAt], // e.g. 'tomorrow 10am' (workspace timezone) or ISO-8601
'submit_for_review' => true,
];
$key = OutboxerClient::uuid();
$first = $ob->request('POST', "/workspaces/{$ws['slug']}/posts", $draft, $key);
echo "Created {$first->data['id']}: status={$first->data['status']}, ETag {$first->headers['etag']}\n";
$again = $ob->request('POST', "/workspaces/{$ws['slug']}/posts", $draft, $key);
echo 'Replayed: '.($again->headers['idempotent-replayed'] ?? 'false').', same post: '
.var_export($again->data['id'] === $first->data['id'], true)."\n";draft := PostInput{Variants: variants, SubmitForReview: true,
Schedule: &Schedule{Mode: "exact", At: scheduleAt}} // e.g. "tomorrow 10am" (workspace timezone) or ISO-8601
draft.Base.Text = "Autumn roast is here: Guji pour-over at 1:16 and 93°C. What's your ratio?"
key := NewUUID()
var post, again Post
h1, err := ob.Do(http.MethodPost, "/workspaces/"+ws.Slug+"/posts", draft, key, &post)
if err != nil {
return err
}
fmt.Printf("Created %s: status=%s, ETag %s\n", post.ID, post.Status, h1.Get("ETag"))
h2, err := ob.Do(http.MethodPost, "/workspaces/"+ws.Slug+"/posts", draft, key, &again)
if err != nil {
return err
}
fmt.Printf("Replayed: %s, same post: %t\n", h2.Get("Idempotent-Replayed"), again.ID == post.ID)draft = {
base: { text: "Autumn roast is here: Guji pour-over at 1:16 and 93°C. What's your ratio?" },
variants: chosen.map { { channel_id: _1['channel_id'] } },
schedule: { mode: 'exact', at: schedule_at }, # e.g. 'tomorrow 10am' (workspace timezone) or ISO-8601
submit_for_review: true
}
key = SecureRandom.uuid
first = ob.request('POST', "/workspaces/#{ws['slug']}/posts", draft, idempotency_key: key)
puts "Created #{first.data['id']}: status=#{first.data['status']}, ETag #{first.headers['etag']}"
again = ob.request('POST', "/workspaces/#{ws['slug']}/posts", draft, idempotency_key: key)
puts "Replayed: #{again.headers['idempotent-replayed']}, same post: #{again.data['id'] == first.data['id']}"Map<String, Object> draft = new LinkedHashMap<>();
draft.put("base", Map.of("text", "Autumn roast is here: Guji pour-over at 1:16 and 93°C. What's your ratio?"));
draft.put("variants", variants);
draft.put("schedule", Map.of("mode", "exact", "at", scheduleAt)); // e.g. "tomorrow 10am" or ISO-8601
draft.put("submit_for_review", true);
String key = UUID.randomUUID().toString();
var first = ob.request("POST", "/workspaces/" + slug + "/posts", draft, key);
var post = Json.obj(first.data());
System.out.printf("Created %s: status=%s, ETag %s%n", post.get("id"), post.get("status"), first.header("ETag").orElse("-"));
var again = ob.request("POST", "/workspaces/" + slug + "/posts", draft, key);
System.out.printf("Replayed: %s, same post: %s%n", again.header("Idempotent-Replayed").orElse("false"),
post.get("id").equals(Json.obj(again.data()).get("id")));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."
fiif (ws.abilities.includes('posts.approve') && ws.abilities.includes('posts.publish')) {
post = await ob.post<Post>(`/posts/${post.id}/approve`, { schedule: { mode: 'proposed' } });
console.log(`Approved: status=${post.status}, scheduled_at=${post.scheduled_at}`);
} else {
console.log(`A human reviewer must approve ${post.id}.`);
}if {"posts.approve", "posts.publish"} <= set(ws["abilities"]):
post = ob.post(f"/posts/{post['id']}/approve", {"schedule": {"mode": "proposed"}})
print(f"Approved: status={post['status']}, scheduled_at={post['scheduled_at']}")
else:
print(f"A human reviewer must approve {post['id']}.")if (! array_diff(['posts.approve', 'posts.publish'], $ws['abilities'])) {
$post = $ob->post("/posts/{$post['id']}/approve", ['schedule' => ['mode' => 'proposed']]);
echo "Approved: status={$post['status']}, scheduled_at={$post['scheduled_at']}\n";
} else {
echo "A human reviewer must approve {$post['id']}.\n";
}if slices.Contains(ws.Abilities, "posts.approve") && slices.Contains(ws.Abilities, "posts.publish") {
if err := ob.Post("/posts/"+post.ID+"/approve", map[string]any{"schedule": Schedule{Mode: "proposed"}}, &post); err != nil {
return err
}
fmt.Printf("Approved: status=%s, scheduled_at=%s\n", post.Status, deref(post.ScheduledAt))
} else {
fmt.Printf("A human reviewer must approve %s.\n", post.ID)
}if (%w[posts.approve posts.publish] - ws['abilities']).empty?
post = ob.post("/posts/#{post['id']}/approve", { schedule: { mode: 'proposed' } })
puts "Approved: status=#{post['status']}, scheduled_at=#{post['scheduled_at']}"
else
puts "A human reviewer must approve #{post['id']}."
endList<Object> abilities = Json.arr(ws.get("abilities"));
if (abilities.contains("posts.approve") && abilities.contains("posts.publish")) {
post = ob.post("/posts/" + id + "/approve", Map.of("schedule", Map.of("mode", "proposed")));
System.out.printf("Approved: status=%s, scheduled_at=%s%n", post.get("status"), post.get("scheduled_at"));
} else {
System.out.println("A human reviewer must approve " + id + ".");
}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"))"
fiexport class OutboxerError extends Error {
readonly status: number;
readonly code: string;
readonly detail: string;
readonly errors: FieldError[]; // {code, path, message, rule?, limit?, hint?}
readonly requestId?: string;
readonly problem: Problem;
constructor(status: number, problem: Problem) {
super(`${status} ${problem.code}: ${problem.detail ?? problem.title}`);
this.name = 'OutboxerError';
this.status = status;
this.code = problem.code ?? 'http_error';
this.detail = problem.detail ?? '';
this.errors = problem.errors ?? [];
this.requestId = problem.request_id;
this.problem = problem;
}
}
try {
await ob.post(`/workspaces/${ws.slug}/validate`, { variants: 'not-a-list' });
} catch (e) {
if (!(e instanceof OutboxerError)) throw e;
console.log(`Typed error: ${e.status} ${e.code} (request ${e.requestId})`);
for (const fe of e.errors) console.log(` ${fe.path}: ${fe.code} - ${fe.hint ?? fe.message}`);
}class OutboxerError(Exception):
def __init__(self, status: int, problem: dict):
self.status = status
self.problem = problem
self.code = problem.get("code") or "http_error"
self.detail = problem.get("detail") or ""
self.errors = problem.get("errors") or [] # [{code, path, message, rule, hint}]
self.request_id = problem.get("request_id")
super().__init__(f"{status} {self.code}: {self.detail}")
try:
ob.post(f"/workspaces/{ws['slug']}/validate", {"variants": "not-a-list"})
except OutboxerError as e:
print(f"Typed error: {e.status} {e.code} (request {e.request_id})")
for err in e.errors:
print(f" {err['path']}: {err['code']} - {err.get('hint') or err['message']}")
try:
billing = ob.get("/billing")
except OutboxerError as e:
if e.status != 403:
raise
print(f"Balance: not visible to this key ({e.code})")final class OutboxerError extends RuntimeException
{
public readonly string $errorCode; // Exception already has $code
public readonly string $detail;
public readonly array $errors; // [['code' => …, 'path' => …, 'message' => …, 'hint' => …]]
public readonly ?string $requestId;
public function __construct(public readonly int $status, public readonly array $problem)
{
$this->errorCode = $problem['code'] ?? 'http_error';
$this->detail = $problem['detail'] ?? '';
$this->errors = $problem['errors'] ?? [];
$this->requestId = $problem['request_id'] ?? null;
parent::__construct("{$status} {$this->errorCode}: {$this->detail}");
}
}
try {
$ob->post("/workspaces/{$ws['slug']}/validate", ['variants' => 'not-a-list']);
} catch (OutboxerError $e) {
echo "Typed error: {$e->status} {$e->errorCode} (request {$e->requestId})\n";
foreach ($e->errors as $fe) {
echo " {$fe['path']}: {$fe['code']} - ".($fe['hint'] ?? $fe['message'])."\n";
}
}type Error struct {
Status int `json:"status"`
Code string `json:"code"`
Title string `json:"title"`
Detail string `json:"detail"`
Errors []FieldError `json:"errors"` // {code, path, message, hint}
RequestID string `json:"request_id"`
RetryAfter *float64 `json:"retry_after"`
}
func (e *Error) Error() string { return fmt.Sprintf("%d %s: %s", e.Status, e.Code, e.Detail) }
err = ob.Post("/workspaces/"+ws.Slug+"/validate", map[string]any{"variants": "not-a-list"}, nil)
var apiErr *Error
if errors.As(err, &apiErr) {
fmt.Printf("Typed error: %d %s (request %s)\n", apiErr.Status, apiErr.Code, apiErr.RequestID)
for _, fe := range apiErr.Errors {
fmt.Printf(" %s: %s - %s\n", fe.Path, fe.Code, fe.Hint)
}
}class Error < StandardError
attr_reader :status, :code, :detail, :errors, :request_id, :problem
def initialize(status, problem)
@status = status
@problem = problem
@code = problem['code'] || 'http_error'
@detail = problem['detail'].to_s
@errors = problem['errors'] || [] # [{code, path, message, hint}]
@request_id = problem['request_id']
super("#{status} #{@code}: #{@detail}")
end
end
begin
ob.post("/workspaces/#{ws['slug']}/validate", { variants: 'not-a-list' })
rescue Outboxer::Error => e
puts "Typed error: #{e.status} #{e.code} (request #{e.request_id})"
e.errors.each { |fe| puts " #{fe['path']}: #{fe['code']} - #{fe['hint'] || fe['message']}" }
endpublic static final class OutboxerException extends RuntimeException {
public final int status;
public final Map<String, Object> problem;
OutboxerException(int status, Map<String, Object> problem) {
super(status + " " + problem.getOrDefault("code", "http_error") + ": " + problem.getOrDefault("detail", ""));
this.status = status;
this.problem = problem;
}
public String code() { return (String) problem.getOrDefault("code", "http_error"); }
public String detail() { return (String) problem.getOrDefault("detail", ""); }
public String requestId() { return (String) problem.get("request_id"); }
@SuppressWarnings("unchecked")
public List<Map<String, Object>> errors() { return (List<Map<String, Object>>) problem.getOrDefault("errors", List.of()); }
}
try {
ob.post("/workspaces/" + slug + "/validate", Map.of("variants", "not-a-list"));
} catch (OutboxerException e) {
System.out.printf("Typed error: %d %s (request %s)%n", e.status, e.code(), e.requestId());
for (var fe : e.errors()) System.out.printf(" %s: %s - %s%n", fe.get("path"), fe.get("code"), fe.get("hint"));
}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:
- Use the raw body bytes, never re-serialized JSON.
- Reject a
tmore than 5 minutes from now. - Compare signatures in constant time.
- 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"
}import { createHmac, timingSafeEqual } from 'node:crypto';
export function verifyWebhook(rawBody: string, header: string | undefined, secret: string, now = Math.floor(Date.now() / 1000)): WebhookEvent {
const parts = Object.fromEntries(String(header ?? '').split(',').map((p) => {
const i = p.indexOf('=');
return [p.slice(0, i).trim(), p.slice(i + 1).trim()];
}));
const t = Number(parts.t);
if (!Number.isInteger(t) || !/^[0-9a-f]{64}$/.test(parts.v1 ?? '')) throw new Error('malformed signature header');
if (Math.abs(now - t) > 300) throw new Error('timestamp outside tolerance');
const expected = Buffer.from(createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex'), 'hex');
const given = Buffer.from(parts.v1, 'hex');
if (expected.length !== given.length || !timingSafeEqual(expected, given)) throw new Error('signature mismatch');
return JSON.parse(rawBody) as WebhookEvent;
}
// http.createServer: collect the chunks, then verifyWebhook(raw, req.headers['outboxer-signature'], secret)import hashlib, hmac, json, time
def verify_webhook(raw_body: bytes, header: str | None, secret: str, now: int | None = None) -> dict:
try:
parts = dict(p.strip().split("=", 1) for p in (header or "").split(","))
t = int(parts["t"])
sig = parts["v1"]
except (KeyError, ValueError):
raise ValueError("malformed signature header") from None
if abs((now if now is not None else int(time.time())) - t) > 300:
raise ValueError("timestamp outside tolerance")
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sig):
raise ValueError("signature mismatch")
return json.loads(raw_body)
# Flask: verify_webhook(request.get_data(), request.headers.get("Outboxer-Signature"), secret)function verify_webhook(string $rawBody, ?string $header, string $secret, ?int $now = null): array
{
$parts = [];
foreach (explode(',', (string) $header) as $pair) {
[$k, $v] = array_pad(explode('=', trim($pair), 2), 2, '');
$parts[$k] = $v;
}
if (! ctype_digit($parts['t'] ?? '') || ! preg_match('/^[0-9a-f]{64}$/', $parts['v1'] ?? '')) {
throw new UnexpectedValueException('malformed signature header');
}
$t = (int) $parts['t'];
if (abs(($now ?? time()) - $t) > 300) {
throw new UnexpectedValueException('timestamp outside tolerance');
}
if (! hash_equals(hash_hmac('sha256', "{$t}.{$rawBody}", $secret), $parts['v1'])) {
throw new UnexpectedValueException('signature mismatch');
}
return json_decode($rawBody, true, flags: JSON_THROW_ON_ERROR);
}
// $event = verify_webhook(file_get_contents('php://input'), $_SERVER['HTTP_OUTBOXER_SIGNATURE'] ?? null, $secret);func VerifyWebhook(rawBody []byte, header, secret string, now time.Time) (*WebhookEvent, error) {
var t int64 = -1
var sig []byte
for _, part := range strings.Split(header, ",") {
k, v, _ := strings.Cut(strings.TrimSpace(part), "=")
switch k {
case "t":
t, _ = strconv.ParseInt(v, 10, 64)
case "v1":
sig, _ = hex.DecodeString(v)
}
}
if t <= 0 || len(sig) != sha256.Size {
return nil, errors.New("malformed signature header")
}
if d := now.Unix() - t; d > 300 || d < -300 {
return nil, errors.New("timestamp outside tolerance")
}
mac := hmac.New(sha256.New, []byte(secret))
fmt.Fprintf(mac, "%d.", t)
mac.Write(rawBody)
if !hmac.Equal(mac.Sum(nil), sig) {
return nil, errors.New("signature mismatch")
}
var ev WebhookEvent
if err := json.Unmarshal(rawBody, &ev); err != nil {
return nil, err
}
return &ev, nil
}
// In a handler: raw, _ := io.ReadAll(r.Body); ev, err := VerifyWebhook(raw, r.Header.Get("Outboxer-Signature"), secret, time.Now())def self.verify(raw_body, header, secret, now: Time.now.to_i)
parts = header.to_s.split(',').to_h { |p| k, v = p.strip.split('=', 2); [k, v.to_s] }
t = parts['t']
sig = parts['v1'].to_s
raise InvalidSignature, 'malformed signature header' unless t&.match?(/\A\d+\z/) && sig.match?(/\A\h{64}\z/)
raise InvalidSignature, 'timestamp outside tolerance' if (now - t.to_i).abs > 300
expected = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{t}.#{raw_body}")
raise InvalidSignature, 'signature mismatch' unless OpenSSL.fixed_length_secure_compare(expected, sig)
JSON.parse(raw_body)
end
# Rails: Outboxer::Webhook.verify(request.raw_post, request.headers['Outboxer-Signature'], secret)static Map<String, Object> verifyWebhook(String rawBody, String header, String secret, long now) {
Map<String, String> parts = new HashMap<>();
for (String p : String.valueOf(header).split(",")) {
String[] kv = p.trim().split("=", 2);
if (kv.length == 2) parts.put(kv[0], kv[1]);
}
String t = parts.getOrDefault("t", ""), sig = parts.getOrDefault("v1", "");
if (!t.matches("\\d{1,12}") || !sig.matches("[0-9a-f]{64}")) throw new SecurityException("malformed signature header");
if (Math.abs(now - Long.parseLong(t)) > 300) throw new SecurityException("timestamp outside tolerance");
byte[] expected = hmacHex(secret, t + "." + rawBody).getBytes(StandardCharsets.US_ASCII);
if (!MessageDigest.isEqual(expected, sig.getBytes(StandardCharsets.US_ASCII))) {
throw new SecurityException("signature mismatch");
}
return Json.obj(Json.parse(rawBody));
}Every sample's webhook-selftest checks this test vector, which was produced by Outboxer's webhook signer. Use
it to test your own verifier:
secret: whsec_test_secret
t: 1791218168
body: {"id":"evt_test","type":"post.published","data":{"post_id":"post_test"}}
header: t=1791218168,v1=ebdb6cc1d18f88c25853b9ed1c12443f0ea1adaee11b3512744ac3764e1e56e6Run 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.
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):
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 exampleneeds_reconnectortoken_expired), then run again. - With
--publish-now, step 6 printspublish-now: status=publishingand then each channel'spublish_statusandpermalinkonce publishing finishes (the samples poll for up to 60 seconds).
