Skip to content
Peal
Esc
↑↓navigate↵open⌘Jpreview
On this page

SDKs

The API's clients in eight languages: install one, check the credential, publish a post and handle errors.

Peal’s SDKs call the API from eight languages. They’re generated from the same contract as the server, so each method is named after an API operation (posts.create, inbox.messages.send, media.importFromUrl) and each type after an API schema. Unlike the rest of Peal, they’re free software under the Apache License 2.0.

Install

Each SDK is published to its language’s registry. Each command installs one exact version:

Language Registry Install
TypeScript/JavaScript npm npm install --save-exact @peal-social/[email protected]
Python PyPI pip install peal-sdk==0.4.0b1 (imported as peal)
Go Go modules go get github.com/peal-social/peal/packages/peal-sdk/[email protected]
Ruby RubyGems gem install peal --version 0.4.0.beta.1
Java Maven Central social.peal:peal:0.4.0-beta.1
PHP Packagist composer require peal-social/peal:0.4.0-beta.1
.NET NuGet dotnet add package Peal --version 0.4.0-beta.1
Rust crates.io cargo add peal-sdk@=0.4.0-beta.1

Each package’s README shows how to use it, and its reference.md lists every method. You’ll find both in the repository.

The SDKs call every endpoint that takes a bearer token. That’s an API key (peal_…), a partner key (peal_partner_…) or an OAuth access token. What only a person does in their own session is left out: exporting or deleting an account, and connected applications.

Point it at your server

The SDKs send requests to https://app.peal.social. On a server of your own, give the client its address (Base URL) with this option:

Language Option
TypeScript and PHP baseUrl, in the options
Python, Ruby, Rust base_url
Go option.WithBaseURL
Java .url(…) on the builder
.NET BaseUrl in ClientOptions

Name the workspace

An API key acts in its own workspace, so a client made with one names none. A partner key or an OAuth token bound to no workspace belongs to none. Give its client the workspace it acts in, and the client sends that workspace’s id in the Peal-Workspace header on every request (The workspace of a request). No method takes a workspace, so make one client per workspace.

Language Option
TypeScript, Python, Ruby, PHP workspace
Go option.WithWorkspace
Java .workspace(…) on the builder
.NET workspace, after the token
Rust Peal-Workspace in custom_headers

The Rust SDK has no option of its own for it, so the header goes in the client’s custom_headers.

const peal = new PealClient({
  token: process.env.PEAL_PARTNER_KEY,
  workspace: "7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90",
});
peal = Peal(
    token=os.environ["PEAL_PARTNER_KEY"],
    workspace="7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90",
)
client := client.NewClient(
	option.WithToken(os.Getenv("PEAL_PARTNER_KEY")),
	option.WithWorkspace(peal.String("7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90")),
)
peal = Peal::Client.new(
  token: ENV.fetch("PEAL_PARTNER_KEY"),
  workspace: "7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90"
)
PealClient peal = PealClient.builder()
    .token(System.getenv("PEAL_PARTNER_KEY"))
    .workspace("7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90")
    .build();
$peal = new PealClient(
    token: getenv('PEAL_PARTNER_KEY'),
    workspace: '7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90',
);
var peal = new PealClient(
    Environment.GetEnvironmentVariable("PEAL_PARTNER_KEY")!,
    workspace: "7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90"
);
let peal = PealClient::new(ClientConfig {
    token: std::env::var("PEAL_PARTNER_KEY").ok(),
    custom_headers: HashMap::from([(
        "Peal-Workspace".to_string(),
        "7b1f6c1e-2d4a-4f0b-9c3e-5a8d2e6f1b90".to_string(),
    )]),
    ..Default::default()
})?;

Check the credential first

Start with GET /api/v1/credential. It tells you who the key or token is and what it may do, and it reads no data. A key that was revoked or has expired gets 401, so your program finds out whether its key works before it does anything.

What it answers depends on the credential:

Credential Answers With
An API key apiKey Its name, its workspace, its permissions and when it expires
A partner key partnerKey Its partner, scopes and permissions
A person’s token user

Build the client from your key, then ask who it is:

import { PealClient } from "@peal-social/sdk";

const peal = new PealClient({ token: process.env.PEAL_API_KEY });

const credential = await peal.credential.get();

if (credential._tag === "apiKey") {
  console.log(credential.workspace.id, credential.permissions);
}
import os

from peal import Peal

peal = Peal(token=os.environ["PEAL_API_KEY"])

credential = peal.credential.get()

if credential.type == "apiKey":
    print(credential.workspace.id, credential.permissions)
import (
	"context"
	"fmt"
	"os"

	peal "github.com/peal-social/peal/packages/peal-sdk/go"
	"github.com/peal-social/peal/packages/peal-sdk/go/client"
	"github.com/peal-social/peal/packages/peal-sdk/go/option"
)

// The client is named `client`, so that `peal` stays the package of the
// request types.
client := client.NewClient(option.WithToken(os.Getenv("PEAL_API_KEY")))
ctx := context.Background()

credential, err := client.Credential.Get(ctx)
if err != nil {
	return err
}

if credential.APIKey != nil {
	fmt.Println(credential.APIKey.Workspace.ID, credential.APIKey.Permissions)
}
require "peal"

peal = Peal::Client.new(token: ENV.fetch("PEAL_API_KEY"))

# Each kind of credential is a class of its own.
credential = peal.credential.get

puts credential.workspace.id if credential.is_a?(Peal::Types::CredentialAPIKey)
import social.peal.PealClient;
import social.peal.types.Credential;

PealClient peal = PealClient.builder()
    .token(System.getenv("PEAL_API_KEY"))
    .build();

Credential credential = peal.credential().get();

credential.getApiKey().ifPresent(key ->
    System.out.println(key.getWorkspace().getId() + " " + key.getPermissions()));
<?php
use Peal\PealClient;

$peal = new PealClient(token: getenv('PEAL_API_KEY'));

$credential = $peal->credential->get();

if ($credential->isApiKey()) {
    echo $credential->asApiKey()->workspace->id, PHP_EOL;
}
using Peal;

var peal = new PealClient(Environment.GetEnvironmentVariable("PEAL_API_KEY")!);

var credential = await peal.Credential.GetAsync();

if (credential.IsApiKey)
{
    var key = credential.AsApiKey();
    Console.WriteLine($"{key.Workspace.Id} {string.Join(", ", key.Permissions)}");
}
use peal_sdk::prelude::*;

let peal = PealClient::new(ClientConfig {
    token: std::env::var("PEAL_API_KEY").ok(),
    ..Default::default()
})?;

let credential = peal.credential.get(None).await?;

if let Credential::ApiKey { workspace, permissions, .. } = &credential {
    println!("{} {:?}", workspace.id, permissions);
}
curl https://app.peal.social/api/v1/credential \
  -H "Authorization: Bearer $PEAL_API_KEY"

The answer never holds the key itself, and it doesn’t list the workspaces a partner key reaches. GET /api/v1/partner/workspaces lists those.

Publish a post, start to finish

This program follows the steps of the Posting API. It finds the channels, brings an image in from its address, checks the post, sends it with an Idempotency-Key, then reads how it went. The key acts in its own workspace, so no call names one.

import { randomUUID } from "node:crypto";

import { PealClient } from "@peal-social/sdk";

const peal = new PealClient({ token: process.env.PEAL_API_KEY });

// 1. Where it can go: the channels that can post.
const channels = await peal.channels.list();
const channelIds = channels
  .filter(({ status }) => status._tag === "active")
  .map(({ id }) => id);

// 2. An image that's already online. The server fetches it itself.
const image = await peal.media.importFromUrl({
  url: "https://media.example.com/synthetic/launch.png",
  altText: "A synthetic launch picture",
});

const post = {
  channelIds,
  content: {
    text: "A synthetic post, sent with the SDK.",
    media: [{ mediaId: image.id, altText: "A synthetic launch picture" }],
    overrides: [],
  },
  when: { _tag: "now" as const },
};

// 3. Checked without being made, with every violation at once.
const check = await peal.posts.validate(post);

if (!check.valid) {
  throw new Error(JSON.stringify(check.violations));
}

// 4. Sent under a key: a retry with the same key within 24 hours
// answers this post and makes no second one.
const sent = await peal.posts.create({
  ...post,
  "idempotency-key": randomUUID(),
  wait: "30",
});

// 5. How it went on each channel, once every channel has its result.
const outcome = await peal.posts.outcome({ postId: sent.id });

for (const target of outcome.targets) {
  console.log(target.channelId, target.status, target.permalink);
}
import os
import uuid

from peal import MediaAttachment, Peal, PostContent, PostTiming_Now

peal = Peal(token=os.environ["PEAL_API_KEY"])

# 1. Where it can go: the channels that can post.
channels = peal.channels.list()
channel_ids = [channel.id for channel in channels if channel.status.type == "active"]

# 2. An image that's already online. The server fetches it itself.
image = peal.media.import_from_url(
    url="https://media.example.com/synthetic/launch.png",
    alt_text="A synthetic launch picture",
)

post = dict(
    channel_ids=channel_ids,
    content=PostContent(
        text="A synthetic post, sent with the SDK.",
        media=[MediaAttachment(media_id=image.id, alt_text="A synthetic launch picture")],
        overrides=[],
    ),
    when=PostTiming_Now(),
)

# 3. Checked without being made, with every violation at once.
check = peal.posts.validate(**post)

if not check.valid:
    raise RuntimeError(check.violations)

# 4. Sent under a key: a retry with the same key within 24 hours
# answers this post and makes no second one.
sent = peal.posts.create(**post, idempotency_key=str(uuid.uuid4()), wait="30")

# 5. How it went on each channel, once every channel has its result.
outcome = peal.posts.outcome(post_id=sent.id)

for target in outcome.targets:
    print(target.channel_id, target.status, target.permalink)
package main

import (
	"context"
	"crypto/rand"
	"fmt"
	"os"

	peal "github.com/peal-social/peal/packages/peal-sdk/go"
	"github.com/peal-social/peal/packages/peal-sdk/go/client"
	"github.com/peal-social/peal/packages/peal-sdk/go/option"
)

func main() {
	ctx := context.Background()
	client := client.NewClient(option.WithToken(os.Getenv("PEAL_API_KEY")))

	// 1. Where it can go: the channels that can post.
	channels, err := client.Channels.List(ctx)
	if err != nil {
		panic(err)
	}

	var channelIDs []string
	for _, channel := range channels {
		if channel.Status.Active != nil {
			channelIDs = append(channelIDs, channel.ID)
		}
	}

	// 2. An image that's already online. The server fetches it itself.
	image, err := client.Media.ImportFromURL(ctx, &peal.MediaImport{
		URL:     "https://media.example.com/synthetic/launch.png",
		AltText: peal.String("A synthetic launch picture"),
	})
	if err != nil {
		panic(err)
	}

	content := &peal.PostContent{
		Text: "A synthetic post, sent with the SDK.",
		Media: []*peal.MediaAttachment{
			{MediaID: image.ID, AltText: "A synthetic launch picture"},
		},
		Overrides: []*peal.TextOverride{},
	}
	now := &peal.PostTiming{Now: &peal.PostTimingNow{}}

	// 3. Checked without being made, with every violation at once.
	check, err := client.Posts.Validate(ctx, &peal.PostToValidate{
		ChannelIDs: channelIDs,
		Content:    content,
		When:       now,
	})
	if err != nil {
		panic(err)
	}
	if !check.Valid {
		panic(fmt.Sprint(check.Violations))
	}

	// 4. Sent under a key: a retry with the same key within 24 hours
	// answers this post and makes no second one.
	sent, err := client.Posts.Create(ctx, &peal.NewPost{
		ChannelIDs:     channelIDs,
		Content:        content,
		When:           now,
		IdempotencyKey: peal.String(rand.Text()),
		Wait:           peal.String("30"),
	})
	if err != nil {
		panic(err)
	}

	// 5. How it went on each channel, once every channel has its result.
	outcome, err := client.Posts.Outcome(ctx, &peal.OutcomePostsRequest{
		PostID: sent.ID,
	})
	if err != nil {
		panic(err)
	}

	for _, target := range outcome.Targets {
		permalink := ""
		if target.Permalink != nil {
			permalink = *target.Permalink
		}
		fmt.Println(target.ChannelID, target.Status, permalink)
	}
}
require "peal"
require "securerandom"

peal = Peal::Client.new(token: ENV.fetch("PEAL_API_KEY"))

# 1. Where it can go: the channels that can post.
channels = peal.channels.list
channel_ids = channels.select { |channel| channel.status.is_a?(Peal::Types::ChannelStatusActive) }.map(&:id)

# 2. An image that's already online. The server fetches it itself.
image = peal.media.import_from_url(
  url: "https://media.example.com/synthetic/launch.png",
  alt_text: "A synthetic launch picture"
)

post = {
  channel_ids: channel_ids,
  content: {
    text: "A synthetic post, sent with the SDK.",
    media: [{ mediaId: image.id, altText: "A synthetic launch picture" }],
    overrides: []
  },
  when: { _tag: "now" }
}

# 3. Checked without being made, with every violation at once.
check = peal.posts.validate(**post)

raise check.violations.inspect unless check.valid

# 4. Sent under a key: a retry with the same key within 24 hours
# answers this post and makes no second one.
sent = peal.posts.create(**post, idempotency_key: SecureRandom.uuid, wait: "30")

# 5. How it went on each channel, once every channel has its result.
outcome = peal.posts.outcome(post_id: sent.id)

outcome.targets.each do |target|
  puts [target.channel_id, target.status, target.permalink].join(" ")
end
import java.util.List;
import java.util.UUID;
import social.peal.PealClient;
import social.peal.resources.media.requests.MediaImport;
import social.peal.resources.posts.requests.NewPost;
import social.peal.resources.posts.requests.PostToValidate;
import social.peal.types.Channel;
import social.peal.types.Media;
import social.peal.types.MediaAttachment;
import social.peal.types.Post;
import social.peal.types.PostContent;
import social.peal.types.PostTarget;
import social.peal.types.PostTiming;
import social.peal.types.PostTimingNow;
import social.peal.types.PostValidation;

PealClient peal = PealClient.builder()
    .token(System.getenv("PEAL_API_KEY"))
    .build();

// 1. Where it can go: the channels that can post.
List<String> channelIds = peal.channels().list().stream()
    .filter(channel -> channel.getStatus().isActive())
    .map(Channel::getId)
    .toList();

// 2. An image that's already online. The server fetches it itself.
Media image = peal.media().importFromUrl(MediaImport.builder()
    .url("https://media.example.com/synthetic/launch.png")
    .altText("A synthetic launch picture")
    .build());

PostContent content = PostContent.builder()
    .text("A synthetic post, sent with the SDK.")
    .media(List.of(MediaAttachment.builder()
        .altText("A synthetic launch picture")
        .mediaId(image.getId())
        .build()))
    .build();
PostTiming now = PostTiming.now(PostTimingNow.builder().build());

// 3. Checked without being made, with every violation at once.
PostValidation check = peal.posts().validate(PostToValidate.builder()
    .content(content)
    .channelIds(channelIds)
    .when(now)
    .build());

if (!check.getValid()) {
    throw new IllegalStateException(check.getViolations().toString());
}

// 4. Sent under a key: a retry with the same key within 24 hours
// answers this post and makes no second one.
Post sent = peal.posts().create(NewPost.builder()
    .content(content)
    .when(now)
    .channelIds(channelIds)
    .idempotencyKey(UUID.randomUUID().toString())
    .wait("30")
    .build());

// 5. How it went on each channel, once every channel has its result.
Post outcome = peal.posts().outcome(sent.getId());

for (PostTarget target : outcome.getTargets()) {
    System.out.println(target.getChannelId() + " " + target.getStatus() + " "
        + target.getPermalink().orElse(""));
}
<?php
use Peal\Media\Requests\MediaImport;
use Peal\PealClient;
use Peal\Posts\Requests\NewPost;
use Peal\Posts\Requests\PostToValidate;
use Peal\Types\MediaAttachment;
use Peal\Types\PostContent;
use Peal\Types\PostTiming;
use Peal\Types\PostTimingNow;

$peal = new PealClient(token: getenv('PEAL_API_KEY'));

// 1. Where it can go: the channels that can post.
$channelIds = [];
foreach ($peal->channels->list() as $channel) {
    if ($channel->status->isActive()) {
        $channelIds[] = $channel->id;
    }
}

// 2. An image that's already online. The server fetches it itself.
$image = $peal->media->importFromUrl(new MediaImport([
    'url' => 'https://media.example.com/synthetic/launch.png',
    'altText' => 'A synthetic launch picture',
]));

$content = new PostContent([
    'text' => 'A synthetic post, sent with the SDK.',
    'media' => [
        new MediaAttachment(['mediaId' => $image->id, 'altText' => 'A synthetic launch picture']),
    ],
    'overrides' => [],
]);
$now = PostTiming::now(new PostTimingNow([]));

// 3. Checked without being made, with every violation at once.
$check = $peal->posts->validate(new PostToValidate([
    'channelIds' => $channelIds,
    'content' => $content,
    'when' => $now,
]));

if (!$check->valid) {
    throw new RuntimeException(json_encode($check->violations));
}

// 4. Sent under a key: a retry with the same key within 24 hours
// answers this post and makes no second one.
$sent = $peal->posts->create(new NewPost([
    'channelIds' => $channelIds,
    'content' => $content,
    'when' => $now,
    'idempotencyKey' => bin2hex(random_bytes(16)),
    'wait' => '30',
]));

// 5. How it went on each channel, once every channel has its result.
$outcome = $peal->posts->outcome($sent->id);

foreach ($outcome->targets as $target) {
    echo $target->channelId, ' ', $target->status, ' ', $target->permalink ?? '', PHP_EOL;
}
using Peal;

var peal = new PealClient(Environment.GetEnvironmentVariable("PEAL_API_KEY")!);

// 1. Where it can go: the channels that can post.
var channels = await peal.Channels.ListAsync();
var channelIds = channels.Where(channel => channel.Status.IsActive).Select(channel => channel.Id).ToList();

// 2. An image that's already online. The server fetches it itself.
var image = await peal.Media.ImportFromUrlAsync(new MediaImport
{
    Url = "https://media.example.com/synthetic/launch.png",
    AltText = "A synthetic launch picture",
});

var content = new PostContent
{
    Text = "A synthetic post, sent with the SDK.",
    Media = new List<MediaAttachment>
    {
        new MediaAttachment { MediaId = image.Id, AltText = "A synthetic launch picture" },
    },
    Overrides = new List<TextOverride>(),
};
var now = new PostTiming(new PostTiming.Now(new PostTimingNow()));

// 3. Checked without being made, with every violation at once.
var check = await peal.Posts.ValidateAsync(new PostToValidate
{
    ChannelIds = channelIds,
    Content = content,
    When = now,
});

if (!check.Valid)
{
    throw new InvalidOperationException(string.Join(", ", check.Violations));
}

// 4. Sent under a key: a retry with the same key within 24 hours
// answers this post and makes no second one.
var sent = await peal.Posts.CreateAsync(new NewPost
{
    ChannelIds = channelIds,
    Content = content,
    When = now,
    IdempotencyKey = Guid.NewGuid().ToString(),
    Wait = "30",
});

// 5. How it went on each channel, once every channel has its result.
var outcome = await peal.Posts.OutcomeAsync(new OutcomePostsRequest
{
    PostId = sent.Id,
});

foreach (var target in outcome.Targets)
{
    Console.WriteLine($"{target.ChannelId} {target.Status} {target.Permalink}");
}
// cargo add peal-sdk@=0.4.0-beta.1 tokio --features tokio/full
// cargo add uuid --features v4
use peal_sdk::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let peal = PealClient::new(ClientConfig {
        token: std::env::var("PEAL_API_KEY").ok(),
        ..Default::default()
    })?;

    // 1. Where it can go: the channels that can post.
    let channel_ids: Vec<String> = peal
        .channels
        .list(None)
        .await?
        .into_iter()
        .filter(|channel| matches!(channel.status, ChannelStatus::Active { .. }))
        .map(|channel| channel.id)
        .collect();

    // 2. An image that's already online. The server fetches it itself.
    let image = peal
        .media
        .import_from_url(
            &MediaImport {
                url: "https://media.example.com/synthetic/launch.png".to_string(),
                alt_text: Some("A synthetic launch picture".to_string()),
            },
            None,
        )
        .await?;

    let content = PostContent {
        text: "A synthetic post, sent with the SDK.".to_string(),
        media: vec![MediaAttachment {
            media_id: image.id.clone(),
            alt_text: "A synthetic launch picture".to_string(),
        }],
        ..Default::default()
    };

    // 3. Checked without being made, with every violation at once.
    let check = peal
        .posts
        .validate(
            &PostToValidate::builder()
                .channel_ids(channel_ids.clone())
                .content(content.clone())
                .when(PostTiming::now())
                .build()?,
            None,
        )
        .await?;

    if !check.valid {
        return Err(format!("{:?}", check.violations).into());
    }

    // 4. Sent under a key: a retry with the same key within 24 hours
    // answers this post and makes no second one. NewPost has no field
    // for the key, so it goes in the request's headers.
    let sent = peal
        .posts
        .create(
            &NewPost::builder()
                .channel_ids(channel_ids)
                .content(content)
                .when(PostTiming::now())
                .wait("30")
                .build()?,
            Some(RequestOptions::new().additional_header(
                "Idempotency-Key",
                uuid::Uuid::new_v4().to_string(),
            )),
        )
        .await?;

    // 5. How it went on each channel, once every channel has its result.
    let outcome = peal
        .posts
        .outcome(&sent.id, &OutcomeQueryRequest::default(), None)
        .await?;

    for target in outcome.targets {
        println!("{} {} {:?}", target.channel_id, target.status, target.permalink);
    }

    Ok(())
}

Each SDK names the steps its own way:

Step Python Go Ruby Java PHP .NET Rust
Check the credential credential.get Credential.Get credential.get credential().get credential->get Credential.GetAsync credential.get
List the channels channels.list Channels.List channels.list channels().list channels->list Channels.ListAsync channels.list
Import a media media.import_from_url Media.ImportFromURL media.import_from_url media().importFromUrl media->importFromUrl Media.ImportFromUrlAsync media.import_from_url
Validate posts.validate Posts.Validate posts.validate posts().validate posts->validate Posts.ValidateAsync posts.validate
Send, with a key posts.create(idempotency_key=…) Posts.Create (IdempotencyKey) posts.create(idempotency_key: …) posts().create (idempotencyKey) posts->create (idempotencyKey) Posts.CreateAsync (IdempotencyKey) posts.create, the header in RequestOptions::additional_header
Read the outcome posts.outcome Posts.Outcome posts.outcome posts().outcome posts->outcome Posts.OutcomeAsync posts.outcome

Ruby calls inbox.messages.send inbox.messages.send_, because every Ruby object already has a send method. Rust’s NewPost has no field for the key, so you send the Idempotency-Key header through the request’s options.

Errors and retries

Each SDK raises a typed error for each error status (Go and Rust return it). A refused key is the SDK’s 401 error, and a missing permission is its 403. The error carries the envelope the API answered, with its code, message and requestId. Log the request’s id, and quote it when you ask for help.

Whether the SDK retries depends on the request:

Request The SDK
GET, PUT or DELETE Retries, with backoff, when the API answers 408, 429 or a 5xx. Each request’s options set how many times (maxRetries, max_retries, option.WithMaxAttempts, MaxRetries: each README says).
POST or PATCH Never sends it twice, because the first may have made the post before its answer was lost.

To send a POST again safely, give it an Idempotency-Key (Idempotency). The API then answers with the same post and makes no other.

A key can send 600 requests a minute, or 60 on a billing account without a payment method (Rate limits).

Pages

You read lists that grow without end a page at a time. Pass limit and cursor, then pass the answer’s nextCursor as the next cursor until it’s null (Paging). The partner API’s lists (/api/v1/partner/workspaces, /api/v1/partner/customer-usage, /api/v1/partner/overview) take before instead, and answer next.

The SDKs pass both as they are. None of them has a helper that reads every page for you, so you write the loop:

let cursor: string | undefined;

do {
  const page = await peal.media.list({ limit: "100", cursor });

  for (const media of page.items) {
    console.log(media.id);
  }

  cursor = page.nextCursor ?? undefined;
} while (cursor !== undefined);
cursor = None

while True:
    page = peal.media.list(limit="100", cursor=cursor)

    for media in page.items:
        print(media.id)

    cursor = page.next_cursor
    if cursor is None:
        break
var cursor *string

for {
	page, err := client.Media.List(ctx, &peal.ListMediaRequest{
		Limit:  peal.String("100"),
		Cursor: cursor,
	})
	if err != nil {
		return err
	}

	for _, media := range page.Items {
		fmt.Println(media.ID)
	}

	if page.NextCursor == nil {
		break
	}
	cursor = page.NextCursor
}
cursor = nil

loop do
  # Send `cursor` only when there is one.
  query = { limit: "100" }
  query[:cursor] = cursor if cursor

  page = peal.media.list(**query)

  page.items.each { |media| puts media.id }

  cursor = page.next_cursor
  break if cursor.nil?
end
import java.util.Optional;
import social.peal.resources.media.requests.ListMediaRequest;
import social.peal.types.Media;
import social.peal.types.MediaPage;

Optional<String> cursor = Optional.empty();

do {
    MediaPage page = peal.media().list(ListMediaRequest.builder()
        .limit("100")
        .cursor(cursor)
        .build());

    for (Media media : page.getItems()) {
        System.out.println(media.getId());
    }

    cursor = page.getNextCursor();
} while (cursor.isPresent());
<?php
use Peal\Media\Requests\ListMediaRequest;

$cursor = null;

do {
    $page = $peal->media->list(new ListMediaRequest([
        'limit' => '100',
        'cursor' => $cursor,
    ]));

    foreach ($page->items as $media) {
        echo $media->id, PHP_EOL;
    }

    $cursor = $page->nextCursor;
} while ($cursor !== null);
string? cursor = null;

do
{
    var page = await peal.Media.ListAsync(new ListMediaRequest
    {
        Limit = "100",
        Cursor = cursor,
    });

    foreach (var media in page.Items)
    {
        Console.WriteLine(media.Id);
    }

    cursor = page.NextCursor;
} while (cursor != null);
let mut cursor: Option<String> = None;

loop {
    let page = peal
        .media
        .list(
            &MediaListQueryRequest {
                limit: Some("100".to_string()),
                cursor: cursor.clone(),
                ..Default::default()
            },
            None,
        )
        .await?;

    for media in &page.items {
        println!("{}", media.id);
    }

    cursor = page.next_cursor;
    if cursor.is_none() {
        break;
    }
}

Verify a webhook

The SDKs call the API, but they don’t receive webhooks. Verify each delivery with the Standard Webhooks library for your language before you act on it. Verify a delivery says what’s signed. In short:

  • The endpoint’s secret is whsec_ followed by base64. It’s shown once, when the endpoint is made (The signing secret).
  • Each delivery carries webhook-id, webhook-timestamp and webhook-signature (What Peal sends).
  • The libraries refuse a timestamp more than five minutes from the present.
  • For 24 hours after a rotation, webhook-signature holds two signatures, one per secret. The libraries accept either.

Verify the body as it arrived, byte for byte, before you parse it:

// npm install standardwebhooks
import { Webhook } from "standardwebhooks";

const webhook = new Webhook(process.env.PEAL_WEBHOOK_SECRET ?? "");

// `rawBody` is the request body as received, a string or a Buffer.
// Throws when the signature or the timestamp is wrong.
const event = webhook.verify(rawBody, {
  "webhook-id": request.headers["webhook-id"],
  "webhook-timestamp": request.headers["webhook-timestamp"],
  "webhook-signature": request.headers["webhook-signature"],
});
# pip install standardwebhooks
import os

from standardwebhooks.webhooks import Webhook

webhook = Webhook(os.environ["PEAL_WEBHOOK_SECRET"])

# `raw_body` is the request body as received, as bytes.
# Raises WebhookVerificationError when the signature or the timestamp is wrong.
event = webhook.verify(
    raw_body,
    {
        "webhook-id": request.headers["webhook-id"],
        "webhook-timestamp": request.headers["webhook-timestamp"],
        "webhook-signature": request.headers["webhook-signature"],
    },
)
// go get github.com/standard-webhooks/standard-webhooks/libraries
import (
	"io"
	"net/http"
	"os"

	standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
)

func handle(w http.ResponseWriter, r *http.Request) {
	webhook, err := standardwebhooks.NewWebhook(os.Getenv("PEAL_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "misconfigured", http.StatusInternalServerError)
		return
	}

	// The request body as received.
	rawBody, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "unreadable", http.StatusBadRequest)
		return
	}

	if err := webhook.Verify(rawBody, r.Header); err != nil {
		http.Error(w, "invalid signature", http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
# gem install standardwebhooks
require "standardwebhooks"

webhook = StandardWebhooks::Webhook.new(ENV.fetch("PEAL_WEBHOOK_SECRET"))

# `raw_body` is the request body as received, as a string.
# Raises StandardWebhooks::WebhookVerificationError when the signature
# or the timestamp is wrong.
event = webhook.verify(raw_body, {
  "webhook-id" => request.env.fetch("HTTP_WEBHOOK_ID"),
  "webhook-timestamp" => request.env.fetch("HTTP_WEBHOOK_TIMESTAMP"),
  "webhook-signature" => request.env.fetch("HTTP_WEBHOOK_SIGNATURE"),
})
// Maven: com.standardwebhooks:standardwebhooks:1.2.0
import com.standardwebhooks.Webhook;
import com.standardwebhooks.exceptions.WebhookVerificationException;

Webhook webhook = new Webhook(System.getenv("PEAL_WEBHOOK_SECRET"));

// `rawBody` is the request body as received, as a string, and `headers`
// the request's headers, a Map<String, List<String>> (names in any case).
// Throws WebhookVerificationException when the signature or the timestamp
// is wrong.
webhook.verify(rawBody, headers);
<?php
// composer require standard-webhooks/standard-webhooks

$webhook = new \StandardWebhooks\Webhook(getenv('PEAL_WEBHOOK_SECRET'));

// The request body as received.
$rawBody = file_get_contents('php://input');

// Throws \StandardWebhooks\Exception\WebhookVerificationException when
// the signature or the timestamp is wrong.
$event = $webhook->verify($rawBody, [
    'webhook-id' => $_SERVER['HTTP_WEBHOOK_ID'],
    'webhook-timestamp' => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'],
    'webhook-signature' => $_SERVER['HTTP_WEBHOOK_SIGNATURE'],
]);
// dotnet add package StandardWebhooks.StandardWebhooks
using System.Net;
using StandardWebhooks;

var webhook = new Webhook(Environment.GetEnvironmentVariable("PEAL_WEBHOOK_SECRET"));

// `rawBody` is the request body as received; `headers` carries the three
// webhook- headers. Throws WebhookVerificationException when the
// signature or the timestamp is wrong.
var headers = new WebHeaderCollection
{
    { "webhook-id", request.Headers["webhook-id"] },
    { "webhook-timestamp", request.Headers["webhook-timestamp"] },
    { "webhook-signature", request.Headers["webhook-signature"] },
};

webhook.Verify(rawBody, headers);
// cargo add standardwebhooks http
use standardwebhooks::Webhook;

let webhook = Webhook::new(&std::env::var("PEAL_WEBHOOK_SECRET")?)?;

// `raw_body` is the request body as received, as bytes, and `headers` the
// request's http::HeaderMap. Fails when the signature or the timestamp is
// wrong.
webhook.verify(&raw_body, &headers)?;

Was this page helpful?