PHP SDK
crumbcast/crumbcast on Packagist is the API for PHP: every endpoint a project's
API token reaches, typed for PHPStan and Psalm, plus
uploads in parts and webhook checks. It needs
PHP 8.1 or later and depends only on Guzzle 7.
Installing
composer require crumbcast/crumbcast
Making a client
One Crumbcast per token, made once and used for every request:
use Crumbcast\Crumbcast;
$crumbcast = new Crumbcast(
token: getenv('CRUMBCAST_TOKEN'), // a project's API token, cc_…
baseUrl: 'https://your-crumbcast',
);
| Argument | Without it | |
|---|---|---|
token | A project's API token (cc_…), from its Settings → API tokens | Required |
baseUrl | Your Crumbcast's address, as you open it in the browser (not /api/v1/) | Required |
retries | How many times a request is sent again when Crumbcast answers 429 or 503 | 2 |
timeout | Seconds a request may take | 60 s, 10 s to connect |
httpClient | A Guzzle ClientInterface of your own: a proxy's, or a test's handler | One of its own |
The token acts as its maker, in its project, at its role: read it from the environment, never from your code.
Calling the API
The API is grouped as the reference is, one group per section, each
method named after its endpoint: Get Video is
$crumbcast->videos->getVideo.
$projects = $crumbcast->projects->listProjects()['projects'];
$videos = $crumbcast->videos->listVideos($projectId, search: 'launch')['videos'];
$video = $crumbcast->videos->getVideo($videoId);
$crumbcast->videos->updateVideo($videoId, ['title' => 'Launch day', 'label_ids' => [$labelId]]);
Lists of videos (and the trash) come a page at a time, up to limit (100 at most).
Each page's next_cursor, passed as after with the same filters and order, asks for
the next one; it's null on the last. previous_cursor, as before, goes back.
$after = null;
do {
$page = $crumbcast->videos->listVideos($projectId, limit: 100, after: $after);
foreach ($page['videos'] as $video) {
echo $video['id'], "\n";
}
$after = $page['next_cursor'] ?? null;
} while ($after !== null);
| Group | |
|---|---|
videos | Uploading, importing, editing and deleting videos; their formats, captions, GIFs, protection and watermarks |
live | Live streams, their broadcasts, schedules and simulcast targets |
playlists | Playlists and their videos |
folders, labels | Where videos are filed |
workflows | Workflows and their runs |
webhooks | Webhooks, their deliveries and tests |
analytics | A project's, a video's and a broadcast's numbers |
playback | What players load: playback links, HLS playlists, viewings |
projects | The token's project: its overview, signing keys, players, ad tags and watermarks |
integrations | Connected YouTube, Twitch and Zoom accounts |
A method takes the path's parameters first, in order ($videoId, $projectId); then the
request's body, as an array; then the query's parameters, best given by name, in camelCase
(search:, orderBy:). A query parameter left out keeps the API's default.
It answers with the API's JSON as arrays, typed with the reference's names as array shapes, so PHPStan, Psalm and your editor know each field. Use one in your own docblocks:
/** @phpstan-import-type VideoResponse from \Crumbcast\Generated\Types */
Fields are only ever added to answers. One newer than your copy of the SDK is in the array already; its type comes with the next version.
An empty JSON object inside a body is new \stdClass(), since PHP's [] is a list. A
whole body that's empty ([]) is sent as {}.
Errors
A request Crumbcast refuses throws a CrumbcastException: its message is the API's reason,
as the dashboard would show it, with the answer's status and its whole body.
use Crumbcast\CrumbcastException;
try {
$crumbcast->videos->trimVideo($videoId, ['ranges' => [['start' => 10, 'end' => 90]]]);
} catch (CrumbcastException $error) {
if ($error->status !== 409) {
throw $error;
}
echo 'Not now: ', $error->getMessage();
}
A 422's message names each field that's wrong and why (size: …; title: …). A 429 or
503 means Crumbcast did nothing and asks to be tried a little later: the SDK waits as
long as its Retry-After says, or a little longer each time, and sends it again up to
retries times before throwing. When there's no answer at all (the network failed, or it
timed out), the exception is Guzzle's own. Errors has what each status
means.
Uploading a video
uploadVideo does the three calls an upload takes in one: it
creates the video, sends its file in parts straight to storage, and starts encoding. It
answers with the video, as Complete Upload does.
use Crumbcast\UploadProgress;
$video = $crumbcast->uploadVideo(
$projectId,
'launch.mp4',
['title' => 'Launch day'],
onProgress: fn (UploadProgress $progress) => printf("%d%%\n", $progress->uploaded * 100 / $progress->total),
);
The file is a path, an SplFileInfo, or a stream open for reading (fopen($path, 'rb')).
Its name and media type come from it; a stream that isn't a file on disk has neither, so
give its 'name' (and 'content_type'). Each part is read from the file as it's sent, so
a large file never sits in memory.
The third argument takes everything Create Video does (folder, labels, who may watch, encodings, a workflow: see What to pick), but the file's size, which comes from the file.
| Argument | Without it | |
|---|---|---|
concurrency | Parts sent at once | 4 |
retries | How many times a part is sent again before the upload fails | 3 |
onProgress | Called with an UploadProgress (uploaded, total, in bytes) as each part is in | None |
A part that fails is sent again on its own; its URL is signed again if it ran out. A part
that fails for good stops the others and throws. The video is there, waiting for its file:
upload it again with replaceVideoFile, or delete it.
Replacing a file
$crumbcast->replaceVideoFile($videoId, 'launch-v2.mp4');
The video plays as it was until the new file is encoded, and keeps its ID, links and
settings. It takes the same arguments as uploadVideo, and name: and contentType: for
a stream. An upload that failed half way is given up with
$crumbcast->videos->cancelReplacingVideoFile($videoId).
Other files
A thumbnail, a captions file, a player's logo: any endpoint that takes a file takes it in
its form as a Crumbcast\File, an SplFileInfo, or a stream open for reading.
use Crumbcast\File;
$crumbcast->videos->uploadCaptions($videoId, ['language' => 'en', 'file' => File::fromPath('launch.en.vtt')]);
File::fromString($contents, 'launch.en.vtt') sends what you already have; either takes a
media type when the name's extension doesn't say it.
Checking webhooks
Webhook::verify checks a delivery is your webhook's and recent,
then answers with its event. Hand it the body exactly as it came, before any JSON parsing:
the signature is over those bytes.
- Laravel
- Symfony
- Plain PHP
use Crumbcast\Webhook;
use Crumbcast\WebhookVerificationException;
use Illuminate\Http\Request;
// routes/api.php, outside the web middleware (no CSRF token)
Route::post('/crumbcast', function (Request $request) {
try {
$event = Webhook::verify(
$request->getContent(),
$request->header('Crumbcast-Signature'),
config('services.crumbcast.webhook_secret'),
);
} catch (WebhookVerificationException) {
abort(400);
}
if ($event['type'] === 'video.ready') {
MarkPlayable::dispatch($event['data']['video']['id']);
}
return response()->noContent();
});
use Crumbcast\Webhook;
use Crumbcast\WebhookVerificationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
final class CrumbcastWebhookController
{
#[Route('/crumbcast', methods: ['POST'])]
public function __invoke(Request $request): Response
{
try {
$event = Webhook::verify(
$request->getContent(),
$request->headers->get('Crumbcast-Signature'),
$_ENV['CRUMBCAST_WEBHOOK_SECRET'],
);
} catch (WebhookVerificationException) {
return new Response(status: 400);
}
if ($event['type'] === 'video.ready') {
$this->markPlayable($event['data']['video']['id']);
}
return new Response(status: 204);
}
}
use Crumbcast\Webhook;
use Crumbcast\WebhookVerificationException;
try {
$event = Webhook::verify(
file_get_contents('php://input'),
$_SERVER['HTTP_CRUMBCAST_SIGNATURE'] ?? null,
getenv('CRUMBCAST_WEBHOOK_SECRET'),
);
} catch (WebhookVerificationException) {
http_response_code(400);
exit;
}
if ($event['type'] === 'video.ready') {
markPlayable($event['data']['video']['id']);
}
http_response_code(204);
It throws a WebhookVerificationException when the Crumbcast-Signature header is
missing, isn't the webhook's, or the delivery is more than 5 minutes old (tolerance:, in
seconds, changes that). The event's type is one of Events,
and its data is typed with what each type may carry.
Answer within 10 seconds and do the work afterwards (a queued job); skip an event whose
id you've already handled, as Answer quickly
says.
Testing your code
Give it a Guzzle client whose handler answers for Crumbcast, with nothing sent:
use Crumbcast\Crumbcast;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
$crumbcast = new Crumbcast(
token: 'cc_test',
baseUrl: 'https://crumbcast.test',
httpClient: new Client(['handler' => HandlerStack::create(new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], json_encode(['id' => $videoId, 'title' => 'Launch day'])),
]))]),
);
For webhooks, Webhook::verify takes now: (Unix seconds), so a delivery signed in a
fixture stays recent.
Versions
The SDK is generated from the API's OpenAPI spec, and a new version follows each change to it. Its methods and types are the reference's: when they differ, the reference is the newer.