HTTP API
Your backend talks to Pikoman with plain HTTP requests. There is no server SDK to install: if your language can make a POST, it can publish.
All endpoints
| Request | Right | What it does |
|---|---|---|
POST /{channel}/{event} |
publish |
Sends the body to everyone in the channel as that event; with ?to= or ?to_user=, to one member only. |
POST /mass_events |
publish |
Sends several payloads to many channels in one request. |
GET /{channel}/stats |
stats |
How many connections are in the channel, and how many messages were sent in it. |
GET /channels |
stats |
The channels in use that the key may see, with users, connections and messages. |
GET /{channel}/clients |
clients |
Who is in the channel, in the order they joined, with their member data, and which of them are bots. |
DELETE /{channel}/clients?to=… |
kick, ban |
Removes one member from this channel only, and with ban_seconds keeps it out for a while. |
DELETE /connection/{connectionId} |
disconnect |
Disconnects one client, from every channel (app-wide). |
DELETE /disconnect-all |
disconnect_all |
Disconnects every client of your app. |
Each request is signed with an API key, and the key needs the right in the second column. The same endpoints as an OpenAPI description: openapi.json. Import it into Postman, Insomnia or Bruno, make a token in the dashboard for the request you are about to send, and paste it as the Bearer token.
Base URL and authentication
All requests go to https://next-api.pikoman.se and carry a token signed with one of your app's
API keys, made for that one request. The key itself is never sent, and a token
someone overhears works for nothing but the request it was made for, and only for a minute.
Authorization: Bearer <token>The token is a JWT signed with Ed25519 (EdDSA):
header {"alg": "EdDSA", "typ": "JWT", "kid": "k_3f9a1c0e5b7d2468"}
payload {"iss": "<app id>", "iat": 1761300000, "exp": 1761300060,
"htm": "POST", "htu": "/orders/shipped", "bh": "<SHA-256 of the body>"}kidis the API key's id: the part ofsk_<key id>.<seed>betweensk_and the dot.-
issis your app id,iatwhen the token was made andexpwhen it stops working, in Unix seconds. Make itiat + 60. htmis the request's method, in capitals:POST,GET,DELETE.-
htuis the path with its query string, exactly as the request sends it, without scheme or host:/orders/shipped, or/orders/stats?x=1. -
bhis the SHA-256 of the exact bytes of the body, in base64url without padding. A request without a body, such as aGET, has the hash of nothing:47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU. -
Make a new token for every request. A token may live at most ten minutes (
exp - iatup to 600), andiatmay be up to a minute ahead of our clock.
Every token needs all three of htm, htu and bh: the API refuses a token
without them. A join token is never accepted here, and a token sent to http:// by mistake is refused
from then on, since it went over the network in clear.
A token for curl and Postman
In the dashboard, open your app and use Make a token for one request below its keys: paste the API key's secret, choose the method, path and body, and you get a token for exactly that request, with the curl command that sends it. It works for that request for a minute; for another request, make another token. In Postman, paste it as the Bearer token and send the same body.
From a terminal, the Node file below makes a token for each command:
TOKEN=$(node pikoman-token.mjs GET /orders/stats)
curl https://next-api.pikoman.se/orders/stats \
-H "Authorization: Bearer $TOKEN"A request with a body hashes the same bytes it sends, so keep the body in a variable and use it twice:
BODY='{"id": 1042, "status": "shipped"}'
TOKEN=$(node pikoman-token.mjs POST /orders/shipped "$BODY")
curl -X POST https://next-api.pikoman.se/orders/shipped \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d "$BODY"
In Git Bash on Windows, give the Node file the whole URL instead of the path
(node pikoman-token.mjs GET https://next-api.pikoman.se/orders/stats): Git Bash turns an argument
that starts with / into a Windows path.
A token in your code
Each example reads the app id from PIKOMAN_APP and the API key, sk_…, from
PIKOMAN_API_KEY. The 43 characters after the dot are the key's 32-byte Ed25519 seed in
base64url. Each call makes a token for one request: pass the method, the path with its query, and the body
exactly as you send it.
import { createHash, createPrivateKey, sign } from "node:crypto";
import { pathToFileURL } from "node:url";
const [keyId, seed] = process.env.PIKOMAN_API_KEY.slice(3).split(".");
// Node reads Ed25519 keys as PKCS#8: a fixed 16-byte prefix, then the seed.
const privateKey = createPrivateKey({
key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), Buffer.from(seed, "base64url")]),
format: "der",
type: "pkcs8",
});
const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
/**
* A request token for one request, good for a minute: its method, its path and query (a whole URL is cut down
* to them, as fetch sends them), and its exact body.
*/
export function pikomanToken(method, path, body = "") {
const { pathname, search } = new URL(path, "https://next-api.pikoman.se");
const now = Math.floor(Date.now() / 1000);
const claims = {
iss: process.env.PIKOMAN_APP,
iat: now,
exp: now + 60,
htm: method.toUpperCase(),
htu: pathname + search,
bh: createHash("sha256").update(body).digest("base64url"),
};
const signed = `${part({ alg: "EdDSA", typ: "JWT", kid: keyId })}.${part(claims)}`;
return `${signed}.${sign(null, Buffer.from(signed), privateKey).toString("base64url")}`;
}
// From a terminal: node pikoman-token.mjs POST /orders/shipped '{"id": 1042}'
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const [method = "GET", path = "/", body = ""] = process.argv.slice(2);
console.log(pikomanToken(method, path, body));
}In PHP 7.2 or later, where Sodium is built in:
<?php
function base64url(string $bytes): string
{
return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}
/** A request token for one request, good for a minute: its method, its path and query, and its exact body. */
function pikoman_token(string $method, string $path, string $body = ''): string
{
[$keyId, $seed] = explode('.', substr(getenv('PIKOMAN_API_KEY'), 3), 2);
$seed = sodium_base642bin($seed, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING);
$secretKey = sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair($seed));
$now = time();
$signed = base64url(json_encode(['alg' => 'EdDSA', 'typ' => 'JWT', 'kid' => $keyId])) . '.'
. base64url(json_encode([
'iss' => getenv('PIKOMAN_APP'),
'iat' => $now,
'exp' => $now + 60,
'htm' => strtoupper($method),
'htu' => $path,
'bh' => base64url(hash('sha256', $body, true)),
]));
return $signed . '.' . base64url(sodium_crypto_sign_detached($signed, $secretKey));
}In Python, with the cryptography package:
import base64, hashlib, json, os, time
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
key_id, seed = os.environ["PIKOMAN_API_KEY"].removeprefix("sk_").split(".", 1)
private_key = Ed25519PrivateKey.from_private_bytes(base64.urlsafe_b64decode(seed + "="))
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def pikoman_token(method: str, path: str, body: bytes = b"") -> str:
"""A request token for one request, good for a minute: its method, its path and query, its exact body."""
now = int(time.time())
part = lambda value: b64url(json.dumps(value).encode())
signed = part({"alg": "EdDSA", "typ": "JWT", "kid": key_id}) + "." + part({
"iss": os.environ["PIKOMAN_APP"], "iat": now, "exp": now + 60,
"htm": method.upper(), "htu": path, "bh": b64url(hashlib.sha256(body).digest()),
})
return signed + "." + b64url(private_key.sign(signed.encode()))
In Rust, the pikoman crate's Rest reads the key and signs every request for you,
each with a token of its own, as in publishing below. In Node, so does
Rest in @pikoman/ws from 1.0.0-rc.7; earlier release candidates sign tokens without
htm, htu and bh, which the API refuses.
When a request is refused
The answer is JSON with the reason in error, such as {"error": "The token has expired"}.
| Status | Why |
|---|---|
400 |
A channel name with characters it may not have, an event name over 128 bytes or one that starts with
client- (those are for the events members send each other), or a body the endpoint
cannot read.
|
401 |
No Authorization: Bearer header; a token that is not a JWT with kid,
iss, iat and exp; not signed with EdDSA; a signature that does
not match; expired, made in the future, or valid for more than ten minutes; an app or key id we do
not know; a token made for another request (its htm, htu or
bh does not match), or without all three; a join token; a token that was sent over
plain http://.
|
403 |
The token is good, but the key may not do this: it has expired, it is used from an address it may not be used from, it lacks the endpoint's right, or the channel is outside its kinds or prefixes. |
408 |
The request's body took too long to arrive: it has 5 seconds. Nothing was sent: try again. |
413 |
An event's data over 12 KiB, a body over 256 KB, or a /mass_events over its limits.
Nothing was sent.
|
429 |
Too many requests for the app, or too many refused requests from your address (its tokens are not even checked for a while); more deliveries than the app may make now; or the app's clients already have as much waiting as they may, because some read too slowly. Nothing was sent: wait a little and try again. |
503 |
The server is shutting down, or holds as much for all its clients as it may, or more request bodies
are being read than it takes at once (then with Retry-After, in seconds). Nothing was
sent: try again soon.
|
A 401 about time usually means the clock of the machine that made the token is wrong. We allow a
minute.
Publish an event
POST /{channel}/{event}The request body is delivered as the event's payload to every connection in the channel. A body that is valid JSON arrives as JSON, so the JavaScript client hands your handler an object; any other body arrives as a string.
BODY='{"id": 1042, "status": "shipped"}'
TOKEN=$(node pikoman-token.mjs POST /orders/shipped "$BODY")
curl -X POST https://next-api.pikoman.se/orders/shipped \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d "$BODY"import { pikomanToken } from "./pikoman-token.mjs";
// The token is made for these exact bytes, so sign the body you send.
const body = JSON.stringify({ id: 1042, status: "shipped" });
const response = await fetch("https://next-api.pikoman.se/orders/shipped", {
method: "POST",
headers: { authorization: `Bearer ${pikomanToken("POST", "/orders/shipped", body)}`, "content-type": "application/json" },
body,
});
const { clients } = await response.json();<?php
require 'pikoman_token.php';
// The token is made for these exact bytes, so sign the body you send.
$body = json_encode(['id' => 1042, 'status' => 'shipped']);
$response = file_get_contents('https://next-api.pikoman.se/orders/shipped', false, stream_context_create(['http' => [
'method' => 'POST',
'header' => "Authorization: Bearer " . pikoman_token('POST', '/orders/shipped', $body) . "\r\nContent-Type: application/json",
'content' => $body,
]]));import json, urllib.request
from pikoman_token import pikoman_token
# The token is made for these exact bytes, so sign the body you send.
body = json.dumps({"id": 1042, "status": "shipped"}).encode()
request = urllib.request.Request(
"https://next-api.pikoman.se/orders/shipped",
data=body,
headers={"Authorization": f"Bearer {pikoman_token('POST', '/orders/shipped', body)}", "Content-Type": "application/json"},
)
clients = json.load(urllib.request.urlopen(request))["clients"]use pikoman::Rest;
// Reads sk_<key id>.<seed> and signs each request with a token made for it.
let rest = Rest::from_secret(std::env::var("PIKOMAN_APP")?, &std::env::var("PIKOMAN_API_KEY")?)?;
let clients = rest.publish("orders", "shipped", &serde_json::json!({ "id": 1042, "status": "shipped" })).await?;The response reports how many connections the event was delivered to:
{ "clients": 12 }Zero is a normal answer: it means nobody was listening at that moment. Events are not stored, so a client that connects later will not receive it.
POST /{channel}, without an event name, sends the body with no event. on(event, fn)
handlers never see it; serverMessage(fn) gets it with the event undefined.
An event's data may be at most 12 KiB: 12,288 bytes of JSON, as it is sent. A larger one is never cut; it
gets a 413, {"error": "An event's data may be at most 12288 bytes (as JSON)"}, and
nothing is sent. An event name that starts with client- gets a 400: that prefix is
for the events members send each other, so your handlers can always tell a member's message from yours.
Publish to one member
Add ?to=<connection id> or ?to_user=<user id> to
POST /{channel}/{event} (or POST /{channel}), and the event goes to that member of the
channel and nobody else: the connection, or every connection whose signed member data has that
user_id (presence channels). The answer says how many got it: {"clients": 0} when
nobody in the channel matches, since only members can be reached. The member gets the event with
"direct": true. The query is part of the signed request (htu), so a token for one
member cannot be used for another. A bot answering the user who asked is the usual case; see
Build a bot.
POST /presence-chat-lobby/missed?to_user=42
{"op":"event","channel":"presence-chat-lobby","event":"missed","data":[…],"direct":true}Publish many events at once
POST /mass_events
The body is a JSON array. Each entry sends one payload to one or more channels, which is the cheap way to
notify a list of users. Leave out event to send the payload without an event name.
BODY='[
{ "channels": ["private-user-7", "private-user-9"],
"event": "invite", "data": { "team": "Design" } },
{ "channels": ["dashboard"], "event": "tick", "data": { "online": 31 } }
]'
TOKEN=$(node pikoman-token.mjs POST /mass_events "$BODY")
curl -X POST https://next-api.pikoman.se/mass_events \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d "$BODY"{ "count": 3, "message": "success" }
count is the number of channel deliveries that were queued, here two plus one. One request may
queue at most 1,000; more gets a 413 and sends nothing. Each entry's data may be at most 12 KiB,
as for a single event, and its event may not start with client-; one entry over the cap, or with
such a name, and nothing at all is sent.
Look inside a channel
| Request | Response | Use it for |
|---|---|---|
GET /{channel}/stats |
{"clients": 12, "message_count": 87} |
How many connections are in the channel. |
GET /{channel}/clients |
{"clients": {"c_8f3a…": {"name": "Ada"}, "c_b07e…": {"name": "Order bot"}}, "bots": {"c_b07e…": "k_3f9a1c0e5b7d2468"}} |
The connections in the channel, in the order they joined, each with its member data as an object.
Outside presence channels the data is null. The member data is exactly what the token
had; it never says who is a bot. bots does: the connections that joined with an
API key, with the key id. It is left out when there are none.
|
stats also answers message_count: the messages sent in the channel (pushes and client
events, once each however many they reached) since it became occupied. It starts at 0 with the first member
and is gone when the last one leaves.
List the channels in use
GET /channels?prefix=chat-&info=user_count,subscription_count,message_count&limit=100{"channels": {"chat-1": {"subscription_count": 4, "message_count": 1204},
"presence-chat-lobby": {"user_count": 3, "subscription_count": 4, "message_count": 87}},
"next": "presence-chat-lobby", "app_message_count": 1291}
The app's occupied channels in name order, in Pusher's shape (filter_by_prefix works too). It needs
the stats right and lists only the channels the key may see: its kinds, prefixes and exact names
apply, so a key for chat- never learns of admin-x. info asks for
user_count (presence channels: each user once, by the user_id in their member data),
subscription_count (connections) and message_count (as for stats, and
app_message_count, the app's total since the server started). At most limit channels
(1–1000, 100 by default); when there may be more, next is there: ask again with
after=<next>.
Remove a member from one channel
DELETE /{channel}/clients?to=<connection id>
DELETE /{channel}/clients?to_user=<user id>&reason=Be%20nice&ban_seconds=600
Needs the kick right for that channel (its kinds, prefixes and names apply), or ban
with ban_seconds. The member is found among the channel's own members (a connection, or every
connection of a user in a presence channel), gets
{"op":"kicked","channel":…,"reason":"Be nice","ban_seconds":600} and leaves this channel; its
connection and its other channels stay. The others see an ordinary member_left, and the
member_removed webhook says "reason": "kicked" and
which key did it.
{ "kicked": 1, "banned": true }kicked: how many connections left the channel; 0 when nobody there matches.-
banned, only withban_seconds(1 to 86 400): whether the ban was recorded. While it lasts, that connection and that user id are refused withbannedwhen they join this channel. Bans are kept per channel in memory, at most 100 per channel, and end early if the channel empties. reasonis at most 200 bytes, and the member sees it: write it for them.
It is a DELETE on the channel's member list, so no event you publish can be mistaken for it.
Bots in the channel kick over the WebSocket instead; see Moderation.
Disconnect clients
DELETE /connection/{connectionId}
Closes one connection, with close code 4401, for example when a user logs out or is banned. The
id is the one the client reports with pikoman.getClientId() and the one your token endpoint
receives. It is app-wide: the connection leaves every channel, and the key's channel limits do not narrow
it. To remove someone from one room, use kick.
{ "kicked": true }
false means your app has no connection with that id. @pikoman/ws does not connect
again after 4401 and calls pikoman.disconnected(fn); from Node,
rest.disconnect(connectionId) sends this request. Anyone can still open a new connection by
hand, so also make your token endpoint refuse that user: without a fresh token they cannot get back into a
presence or private channel.
DELETE /disconnect-all
Closes every connection of your app and answers with how many, such as {"kicked": 31}. It was
called /kick-all before keys had rights; that address is gone.
ONE=/connection/c_8f3a1c9e2b7d4a6051e0c3b9
curl -X DELETE "https://next-api.pikoman.se$ONE" \
-H "Authorization: Bearer $(node pikoman-token.mjs DELETE "$ONE")"
curl -X DELETE https://next-api.pikoman.se/disconnect-all \
-H "Authorization: Bearer $(node pikoman-token.mjs DELETE /disconnect-all)"Channels, names and limits
-
Channel names are 1 to 164 characters of
A-Z a-z 0-9 _ - = @ , . ;. Anything else gets a400. -
Names starting with
presence-andprivate-are special: joining them needs a join token. Public channels have no access control at all: anyone with your app id who knows the name can listen. -
Every connection is in the channel
global.POST /global/{event}reaches every connection of your app, andGET /global/statscounts them. A page handles those events afterpikoman.listen("global"). -
Event names are 1 to 128 bytes. A name that starts with
client-gets a400: those are the events members send each other (messages between browsers). -
An event's data may be at most 12 KiB (12,288 bytes) as JSON, in a single publish and in each entry of
/mass_events; a larger one gets a413and nothing is sent. Client events have the same cap. - A request body may be at most 256 KB; a larger one gets a
413. -
A request body has 5 seconds to arrive; slower gets a
408. When too many are being read at once, for your app or on the server, the answer is503withRetry-After.