# Runnable examples

Download an example, set the documented environment variables, and run it from a trusted server or local shell.

Read [Quickstart](/docs/quickstart) first. These scripts can send a real message. Set `PIJON_API_KEY` privately, plus `PIJON_APPLICATION_ID`, `PIJON_RECIPIENT_ID`, and `PIJON_IDEMPOTENCY_KEY`. The API base defaults to `https://api.pijon.fyi/api/v1`; override `PIJON_API_BASE_URL` only for a trusted environment. Keep the same key and payload for retries; use a new key for a new event.

There is no public npm SDK to install. The examples below are the source of their downloadable files.

## cURL

Requires Bash and cURL 7.76 or newer. [Download send.sh](/docs/examples/send.sh), then run `bash send.sh`. This is a single request with a 20-second timeout.

```bash file=send.sh
#!/usr/bin/env bash
set -euo pipefail
: "${PIJON_API_KEY:?Set PIJON_API_KEY privately}"
: "${PIJON_APPLICATION_ID:?Set PIJON_APPLICATION_ID}"
: "${PIJON_RECIPIENT_ID:?Set PIJON_RECIPIENT_ID}"
: "${PIJON_IDEMPOTENCY_KEY:?Set one stable key for this event}"
base="${PIJON_API_BASE_URL:-https://api.pijon.fyi/api/v1}"
result="$(curl --fail-with-body --silent --show-error --max-time 20 \
  --write-out '\n%{http_code}' \
  "${base%/}/notifications" \
  -H "Authorization: Bearer $PIJON_API_KEY" \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $PIJON_IDEMPOTENCY_KEY" \
  --data "{\"application_id\":\"$PIJON_APPLICATION_ID\",\"recipient_id\":\"$PIJON_RECIPIENT_ID\",\"body\":\"Hello from Pijon docs\"}")"
status="${result##*$'\n'}"
case "$status" in
  200|202) printf '%s\n' "${result%$'\n'*}" ;;
  *) printf 'Unexpected HTTP %s. Preserve this event key.\n' "$status" >&2; exit 1 ;;
esac
```

## Node.js / TypeScript projects

Requires Node.js 22 or newer. [Download send.mjs](/docs/examples/send.mjs), then run `node send.mjs`. Uses built-in fetch; adapt this server-side function to a TypeScript project without adding a client SDK. It makes at most three attempts, preserves body/key, and respects bounded Retry-After waits.

```javascript file=send.mjs
import { setTimeout as sleep } from 'node:timers/promises';

function required(name) {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name} before sending.`);
  return value;
}

async function main() {
  const key = required('PIJON_API_KEY');
  const idempotency = required('PIJON_IDEMPOTENCY_KEY');
  const base = (process.env.PIJON_API_BASE_URL || 'https://api.pijon.fyi/api/v1').replace(/\/$/, '');
  const body = JSON.stringify({
    application_id: required('PIJON_APPLICATION_ID'),
    recipient_id: required('PIJON_RECIPIENT_ID'),
    body: 'Hello from Pijon docs',
  });
  for (let attempt = 0; attempt < 3; attempt++) {
    let response;
    try {
      response = await fetch(`${base}/notifications`, {
        method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
        headers: { Authorization: `Bearer ${key}`, Accept: 'application/json',
          'Content-Type': 'application/json', 'Idempotency-Key': idempotency },
        body,
      });
    } catch {
      if (attempt === 2) throw new Error('Transport failed; acceptance is unknown. Preserve this key and body.');
      await sleep(500 * 2 ** attempt + Math.random() * 200);
      continue;
    }
    if ([408, 429, 500, 502, 503, 504].includes(response.status) && attempt < 2) {
      const hint = response.headers.get('Retry-After');
      const delay = hint === null ? 500 * 2 ** attempt + Math.random() * 200
        : /^\d+$/.test(hint) ? Number(hint) * 1000 : Math.max(0, Date.parse(hint) - Date.now());
      await response.body?.cancel();
      if (!Number.isFinite(delay) || delay > 30000)
        throw new Error('Retry-After exceeds this task budget. Preserve this key and retry later.');
      await sleep(delay);
      continue;
    }
    if (![200, 202].includes(response.status)) {
      await response.body?.cancel();
      throw new Error(`Send rejected (HTTP ${response.status}). See Pijon troubleshooting.`);
    }
    const result = (await response.json()).data;
    if (typeof result?.notification?.id !== 'string' || typeof result.replayed !== 'boolean')
      throw new Error('Unexpected response; acceptance is unknown. Preserve this key.');
    console.log(JSON.stringify({ id: result.notification.id, replayed: result.replayed,
      status: result.notification.status, endpoint_count: result.notification.endpoint_count }));
    return;
  }
}
main().catch(error => { console.error(error.message); process.exitCode = 1; });
```

## Python

Requires Python 3.10 or newer, with standard-library modules only. [Download send.py](/docs/examples/send.py), then run `python3 send.py`. This sends once; after an ambiguous timeout, follow [retry guidance](/docs/reliability) using the same environment/key.

```python file=send.py
import json
import os
import sys
import urllib.error
import urllib.request


def main():
    names = ['PIJON_API_KEY', 'PIJON_APPLICATION_ID', 'PIJON_RECIPIENT_ID', 'PIJON_IDEMPOTENCY_KEY']
    for name in names:
        if not os.environ.get(name):
            raise ValueError('Set ' + name + ' before sending.')
    base = os.environ.get('PIJON_API_BASE_URL', 'https://api.pijon.fyi/api/v1').rstrip('/')
    body = json.dumps({'application_id': os.environ['PIJON_APPLICATION_ID'],
                       'recipient_id': os.environ['PIJON_RECIPIENT_ID'],
                       'body': 'Hello from Pijon docs'}).encode()
    request = urllib.request.Request(base + '/notifications', data=body, headers={
        'Authorization': 'Bearer ' + os.environ['PIJON_API_KEY'],
        'Accept': 'application/json', 'Content-Type': 'application/json',
        'Idempotency-Key': os.environ['PIJON_IDEMPOTENCY_KEY']}, method='POST')
    # Refuse redirects rather than forwarding the credential to another origin.
    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, headers, newurl):
            return None
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=20) as response:
            if response.status not in (200, 202):
                raise ValueError('Unexpected HTTP status.')
            result = json.load(response)['data']
            if not isinstance(result['notification']['id'], str) or not isinstance(result['replayed'], bool):
                raise ValueError('Unexpected response.')
            print(json.dumps({'id': result['notification']['id'], 'replayed': result['replayed'],
                              'status': result['notification']['status'],
                              'endpoint_count': result['notification']['endpoint_count']}))
    except urllib.error.HTTPError as error:
        raise ValueError('Send rejected (HTTP ' + str(error.code) + '). See Pijon troubleshooting.') from None
    except (urllib.error.URLError, TimeoutError):
        raise ValueError('Transport failed; acceptance is unknown. Preserve this key and body.') from None


if __name__ == '__main__':
    try:
        main()
    except (ValueError, KeyError, TypeError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
```

## PHP / Laravel projects

Requires PHP 8.3 or newer with cURL. [Download send.php](/docs/examples/send.php), then run `php send.php`. A Laravel service can use the same payload/headers through its HTTP client. Keep the key in backend configuration. This example sends once.

```php file=send.php
<?php
function requiredEnv(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException('Set '.$name.' before sending.');
    }
    return $value;
}
try {
    $key = requiredEnv('PIJON_API_KEY');
    $idempotency = requiredEnv('PIJON_IDEMPOTENCY_KEY');
    $body = json_encode([
        'application_id' => requiredEnv('PIJON_APPLICATION_ID'),
        'recipient_id' => requiredEnv('PIJON_RECIPIENT_ID'),
        'body' => 'Hello from Pijon docs',
    ], JSON_THROW_ON_ERROR);
    $base = rtrim(getenv('PIJON_API_BASE_URL') ?: 'https://api.pijon.fyi/api/v1', '/');
    $curl = curl_init($base.'/notifications');
    curl_setopt_array($curl, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body,
        CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20, CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer '.$key, 'Accept: application/json',
            'Content-Type: application/json', 'Idempotency-Key: '.$idempotency]]);
    $raw = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    if ($raw === false) {
        throw new RuntimeException('Transport failed; acceptance is unknown. Preserve this key and body.');
    }
    if (!in_array($status, [200, 202], true)) {
        throw new RuntimeException('Send rejected (HTTP '.$status.'). See Pijon troubleshooting.');
    }
    $result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR)['data'];
    if (!is_string($result['notification']['id'] ?? null) || !is_bool($result['replayed'] ?? null)) {
        throw new RuntimeException('Unexpected response; preserve this key.');
    }
    echo json_encode(['id' => $result['notification']['id'], 'replayed' => $result['replayed'],
        'status' => $result['notification']['status'], 'endpoint_count' => $result['notification']['endpoint_count']], JSON_THROW_ON_ERROR).PHP_EOL;
} catch (Throwable $error) {
    fwrite(STDERR, $error->getMessage().PHP_EOL);
    exit(1);
}
```

## Check before shipping

Run the example with an authorized recipient. Inspect the notification ID in History/Inbox and confirm device display separately. Run it again with the same body/key to verify replay. Store configuration in your deployment's secret manager and add application-specific tests with a fake HTTP transport. Local mock success does not verify live credentials, subscriptions, delivery, or billing.
