Skip to main content

Scripting with JSON output

Every command can print JSON with --output json (or --json). Data goes to stdout and messages to stderr, so stdout can go straight into jq.

To make JSON the default for a whole script:

export SKRYBE_OUTPUT=json

For CI, set the credentials as environment variables; no config file is needed:

export SKRYBE_API_KEY=...   # from your CI secret store

Lists and IDs​

# Every list ID
skrybe lists --json | jq -r '.[].id'

# The ID of the list called "Newsletter"
LIST=$(skrybe lists --json | jq -r '.[] | select(.name == "Newsletter") | .id')

# Lists with their active counts, largest first
skrybe lists --counts --json | jq -r 'sort_by(-.active_subscribers) | .[] | "\(.active_subscribers)\t\(.name)"'

Exporting subscribers​

subscribers ls --all pages through the whole list for you:

# Active subscribers as CSV
skrybe subscribers ls --list "$LIST" --status active --all --json \
| jq -r '.[] | [.email, .name] | @csv' > active.csv

# Email and a custom field
skrybe subscribers ls --list "$LIST" --all --json \
| jq -r '.[] | [.email, (.custom_fields.City // "")] | @tsv'

For simple column output --output text is often enough:

skrybe subscribers ls --list "$LIST" --all --output text | cut -f1

Campaigns​

# Drafts, as "id<TAB>title"
skrybe campaigns --status draft --all --json | jq -r '.[] | "\(.id)\t\(.title)"'

# Open and click rates for the last 10 sent campaigns
skrybe campaigns --status sent --json | jq -r '.[].id' | while read -r id; do
skrybe campaigns stats "$id" --json | jq -r '[.id, .opens.rate, .clicks.rate] | @tsv'
done

Results of actions​

Actions print a result record under json:

skrybe subscribers add ada@example.com --list "$LIST" --json | jq -r .outcome
# subscribed, or already_subscribed

skrybe campaigns send 42 --list "$LIST" --dry-run --json | jq .recipients

Handling errors​

Under --output json, errors are JSON on stderr:

{ "error": { "code": "campaign_not_draft", "message": "Campaign has already been sent", "hint": "..." } }

Branch on the exit code, and read the error code when you need detail:

if ! out=$(skrybe campaigns send 42 --list "$LIST" --yes --json 2>err.json); then
code=$(jq -r .error.code err.json)
case "$code" in
campaign_not_draft) echo "already sent, skipping" ;;
quota_exceeded) echo "out of quota" >&2; exit 1 ;;
*) jq -r .error.message err.json >&2; exit 1 ;;
esac
fi

The exit codes are 0 success, 1 API error, 2 usage error, 3 authentication failure and 4 quota or rate limit. See Exit codes.

Things to remember in scripts​

  • Commands that send, schedule or delete need --yes when stdin is not a terminal. Without it they exit 2.
  • An empty collection is a success: [] and exit 0.
  • lists create, templates create and campaigns duplicate print the new ID on stdout even under table, so $(...) captures it directly.
  • lists count and subscribers status print a bare value under table and text.