Python SDK
crumbcast on PyPI is the API for Python: every endpoint a project's
API token reaches, typed, plus uploads in
parts and webhook checks. It needs Python 3.11 or later, is the same
sync and async, and depends only on httpx.
Installing
- pip
- uv
- Poetry
pip install crumbcast
uv add crumbcast
poetry add crumbcast
Making a client
One Crumbcast per token, made once and used for every request:
import os
from crumbcast import Crumbcast
crumbcast = Crumbcast(
token=os.environ["CRUMBCAST_TOKEN"], # a project's API token, cc_…
base_url="https://your-crumbcast",
)
| Argument | Without it | |
|---|---|---|
token | A project's API token (cc_…), from its Settings → API tokens | Required |
base_url | 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, or an httpx.Timeout | 60 s, 10 s to connect |
http_client | An httpx.Client of your own: a proxy's, or a test's transport. It's yours to close | One of its own |
It keeps its connections open between requests: close it when you're done with
crumbcast.close(), or use it as a context manager (with Crumbcast(...) as crumbcast:).
The token acts as its maker, in its project, at its role: read it from the environment, never from your code.
Async
AsyncCrumbcast is the same, awaited, on an httpx.AsyncClient:
from crumbcast import AsyncCrumbcast
async with AsyncCrumbcast(token=token, base_url="https://your-crumbcast") as crumbcast:
video = await crumbcast.videos.get_video(video_id)
Everything on this page works the same way in both; only the await differs.
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.get_video.
projects = crumbcast.projects.list_projects()["projects"]
videos = crumbcast.videos.list_videos(project_id, search="launch")["videos"]
video = crumbcast.videos.get_video(video_id)
crumbcast.videos.update_video(video_id, body={"title": "Launch day", "label_ids": [label_id]})
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 None on the last. previous_cursor, as before, goes back.
page = crumbcast.videos.list_videos(project_id, limit=100)
while True:
for video in page["videos"]:
print(video["id"])
if not page.get("next_cursor"):
break
page = crumbcast.videos.list_videos(project_id, limit=100, after=page["next_cursor"])
| 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 (video_id, project_id); then, by
name, the request's body and the query's parameters, as the reference names them
(search=, limit=). A query parameter left out keeps the API's default.
It answers with the API's JSON as dicts, typed with the reference's names, so your editor and type checker know each field:
from crumbcast.types import CreateVideoRequest, VideoResponse
Fields are only ever added to answers. One newer than your copy of the SDK is in the dict already; its type comes with the next version.
Errors
A request Crumbcast refuses raises a CrumbcastError: its message is the API's reason, as
the dashboard would show it, with the answer's status and its whole body.
from crumbcast import CrumbcastError
try:
crumbcast.videos.trim_video(video_id, body={"ranges": [{"start": 10, "end": 90}]})
except CrumbcastError as error:
if error.status != 409:
raise
print("Not now:", error)
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 raising. When there's no answer at all (the network failed, or it
timed out), the error is httpx's own. Errors has what each status means.
Uploading a video
upload_video 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.
video = crumbcast.upload_video(
project_id,
"launch.mp4",
{"title": "Launch day"},
on_progress=lambda progress: print(f"{progress.uploaded * 100 // progress.total}%"),
)
The file is a path, a file open in binary (open(path, "rb")), or its bytes. Its name and
media type come from it; bytes have 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 |
on_progress | 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 raises. The video is there, waiting for its file:
upload it again with replace_video_file, or delete it.
With AsyncCrumbcast, the parts go as tasks rather than threads, and cancelling the
upload (asyncio.timeout, or the task's cancel()) stops the parts still going.
Replacing a file
crumbcast.replace_video_file(video_id, "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 upload_video, and name= and content_type=
for bytes. An upload that failed half way is given up with
crumbcast.videos.cancel_replacing_video_file(video_id).
Other files
A thumbnail, a captions file, a player's logo: any endpoint that takes a file takes it in
its form as bytes, a file open in binary or a Path, or as (name, content) or
(name, content, media type) to say what it is.
from pathlib import Path
crumbcast.videos.upload_captions(video_id, body={"language": "en", "file": Path("launch.en.vtt")})
Checking webhooks
verify_webhook 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.
- FastAPI
- Flask
- Django
import os
from fastapi import FastAPI, HTTPException, Request, Response
from crumbcast import WebhookVerificationError, verify_webhook
app = FastAPI()
@app.post("/crumbcast")
async def crumbcast_webhook(request: Request):
try:
event = verify_webhook(
await request.body(),
request.headers.get("Crumbcast-Signature"),
os.environ["CRUMBCAST_WEBHOOK_SECRET"],
)
except WebhookVerificationError:
raise HTTPException(400)
if event["type"] == "video.ready":
mark_playable(event["data"]["video"]["id"])
return Response(status_code=204)
import os
from flask import Flask, abort, request
from crumbcast import WebhookVerificationError, verify_webhook
app = Flask(__name__)
@app.post("/crumbcast")
def crumbcast_webhook():
try:
event = verify_webhook(
request.get_data(),
request.headers.get("Crumbcast-Signature"),
os.environ["CRUMBCAST_WEBHOOK_SECRET"],
)
except WebhookVerificationError:
abort(400)
if event["type"] == "video.ready":
mark_playable(event["data"]["video"]["id"])
return "", 204
import os
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from crumbcast import WebhookVerificationError, verify_webhook
@csrf_exempt
@require_POST
def crumbcast_webhook(request):
try:
event = verify_webhook(
request.body,
request.headers.get("Crumbcast-Signature"),
os.environ["CRUMBCAST_WEBHOOK_SECRET"],
)
except WebhookVerificationError:
return HttpResponseBadRequest()
if event["type"] == "video.ready":
mark_playable(event["data"]["video"]["id"])
return HttpResponse(status=204)
It raises a WebhookVerificationError 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 is a WebhookEvent, whose type tells its data apart: after
if event["type"] == "video.encoded":, your type checker knows event["data"]["failed"]
is there. Each type and its data are in Events.
Answer within 10 seconds and do the work afterwards; skip an event whose id you've
already handled, as Answer quickly says.
Testing your code
Give it an httpx.Client whose transport answers for Crumbcast, with nothing sent:
import httpx
from crumbcast import Crumbcast
def answer(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/api/v1/videos/{video_id}/":
return httpx.Response(200, json={"id": video_id, "title": "Launch day"})
return httpx.Response(404, json={"detail": "Not found"})
crumbcast = Crumbcast(
token="cc_test",
base_url="https://crumbcast.test",
http_client=httpx.Client(transport=httpx.MockTransport(answer)),
)
For webhooks, verify_webhook 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.