For AI agents: every API docs page in one plain-text file is at /docs/llms-full.txt, and the documentation index is at /llms.txt. This page is available as Markdown at https://diffio.ai/docs/developers/guides/saas-podcast-cleanup.md, and every docs URL returns Markdown when requested with Accept: text/markdown.

Podcast cleanup in a SaaS app
Your users upload episodes from the browser straight to Diffio, your server keeps the API key and each user's projects apart, and a signed webhook tells you when the cleaned audio is ready to play.
How it works
- Browser → Your server:
POST /api/uploads, file name and size - Your server → Diffio API:
POST /projects, Diffio-End-User from your session - Diffio API → Your server:
upload, upload_token, upload.requests - Your server → Browser:
upload, never the API key - Browser → Media host:
start, parts, complete, Bearer upload_token - Browser → Your server:
POST …/{id}/complete, your route - Your server → Diffio API:
POST …/upload/complete, the restore starts - Diffio API → Your server:
generation.completed, signed; matched to one job - Browser → Your server:
GET /api/uploads/{id}, your route - Your server → Diffio API:
GET …/media, as the signed-in user, 6 hour URLs
Build it
- 1
Set up
Install the SDK and a web framework. Set the API key, the endpoint's
whsec_signing secret (step 4) and a session secret, on the server only.Terminalpip install diffio flask # Python npm install diffio express express-session # or Node.js export DIFFIO_API_KEY="diffio_..." export DIFFIO_WEBHOOK_SECRET="whsec_..." export SESSION_SECRET="..." - 2
Create the project for the signed-in user
create_uploadtakes the user id from your session, never from the request body, and sends it asDiffio-End-User.generationqueues the restore now; it starts once the file lands. The browser'supload_keybecomes theIdempotency-Key, so a retried request returns the same project. The job row keeps the project, its firstgeneration_idand the user. - 3
Upload from the browser
The server returns only
upload. The browser followsupload.requests(start, parts, complete) with theupload_tokenas a bearer token; the media host accepts these four requests from any origin. The token is scoped to this one project's file and works for 24 hours (upload.expires_at); POST .../upload gives a new one. Keep theuploadKeywith the file: a retry with the same key gets the same project, andupload: nullwhen its file already arrived.upload.js (browser)// Runs in the browser: the file goes straight to Diffio's media host with the upload token. // Pass the same uploadKey when you retry the same file (keep it with the file, for example in sessionStorage), so a // retry after a lost answer reuses its project instead of creating another. export async function uploadEpisode(file, uploadKey) { const created = await fetch("/api/uploads", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ upload_key: uploadKey, file_name: file.name, size_bytes: file.size }), }); if (!created.ok) throw new Error(`Could not start the upload (${created.status})`); const { project_id, upload } = await created.json(); if (upload) { // null: the file already arrived on an earlier try const { start, part, complete } = upload.requests; const send = async (request, url, body, headers = request.headers) => { const response = await fetch(url, { method: request.method, headers, body }); if (!response.ok) throw new Error(`Upload failed (${response.status})`); return response.json(); }; const { uploadId, partSizeBytes } = await send(start, start.url); const parts = []; for (let number = 1, offset = 0; offset < file.size; number += 1, offset += partSizeBytes) { const url = part.url.replace("{part_number}", number).replace("{upload_id}", encodeURIComponent(uploadId)); // The browser sets Content-Length itself; only the Authorization header is copied. const chunk = file.slice(offset, offset + partSizeBytes); const { etag } = await send(part, url, chunk, { Authorization: part.headers.Authorization }); parts.push({ partNumber: number, etag }); } await send(complete, complete.url, JSON.stringify({ uploadId, parts })); } const completed = await fetch(`/api/uploads/${project_id}/complete`, { method: "POST" }); // safe to repeat if (!completed.ok) throw new Error(`Could not finish the upload (${completed.status})`); return project_id; // poll GET /api/uploads/<project_id> until status is "complete" } - 4
Verify and record the webhook
Open the portal with
python app.py portalornode app.mjs portal(an account-wide client, no end user) and addhttps://your-app.example/webhooks/diffioforgeneration.completedandgeneration.failed.- Verify the signature with the SDK, on the raw body.
- One transaction: record
event.id(a repeat changes nothing) and update the job. - Match the job on
data.id= itsgeneration_idanddata.end_user= its user. A second restore or an edit of the same project, or another user's event, changes nothing. - Answer
204after the commit, with no API calls in the delivery; an error answers 500 and the delivery is retried.
Payloads and retries: Webhooks.
- 5
Fetch media on read
GET /api/uploads/<id>asks Diffio for media as the signed-in user once the job is complete, and again when the stored URL has less than 5 minutes of its 6 hours left.
The complete server
Run it locally: the example folder adds a development sign-in for two users, a page with a file input and player, and a signed sample webhook, with the commands and results to expect.
"""Podcast cleanup in a SaaS app: browser uploads, one Diffio end user per customer, signed webhooks.
python app.py serves on http://localhost:3000
python app.py portal prints a link to the webhook portal
"""
import os
import sqlite3
import sys
from datetime import datetime, timedelta, timezone
from diffio import DiffioClient, WebhookVerificationError, verify_webhook_signature
from flask import Flask, abort, g, jsonify, request, session
DB_PATH = "podcasts.db"
app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"] # signs the session cookie your sign-in sets
with sqlite3.connect(DB_PATH) as setup:
setup.executescript("""
create table if not exists jobs (
project_id text primary key, user_id text not null, generation_id text not null,
status text not null, error_code text, audio_url text, expires_at text);
create table if not exists webhook_events (id text primary key, type text, created_at text);
""")
def db():
"""One connection per request, so each delivery runs its own transaction."""
if "db" not in g:
g.db = sqlite3.connect(DB_PATH, timeout=10)
return g.db
@app.teardown_appcontext
def close_db(_error):
if "db" in g:
g.pop("db").close()
def diffio_for(user_id):
"""A client that acts for one of your users: every call sends Diffio-End-User."""
return DiffioClient(end_user=user_id)
def signed_in_user():
user_id = session.get("user_id") # set by your own sign-in, never by the request body
if not user_id:
abort(401)
return user_id
@app.post("/api/uploads")
def create_upload():
user_id = signed_in_user()
body = request.get_json()
with diffio_for(user_id) as diffio:
project = diffio.projects.create(
file_name=body["file_name"],
size_bytes=body["size_bytes"],
generation={"model": "diffio-flash"}, # starts by itself once the file lands
idempotency_key=f"upload-{body['upload_key']}", # a retried request gets the same project
)
with db() as conn:
conn.execute("insert or ignore into jobs (project_id, user_id, generation_id, status) values (?, ?, ?, ?)",
(project.id, user_id, project.latest_generation.id, "processing"))
# Only the upload descriptors go to the browser; the API key stays here.
return jsonify(project_id=project.id, upload=project.upload.to_dict() if project.upload else None)
@app.post("/api/uploads/<project_id>/complete")
def complete_upload(project_id):
with diffio_for(signed_in_user()) as diffio:
project = diffio.projects.complete_upload(project_id) # 404 unless it is this user's project
return jsonify(status=project.status)
@app.get("/api/uploads/<project_id>")
def get_upload(project_id):
user_id = signed_in_user()
conn = db()
job = conn.execute("select generation_id, status, error_code, audio_url, expires_at from jobs"
" where project_id = ? and user_id = ?", (project_id, user_id)).fetchone()
if job is None:
abort(404)
generation_id, status, error_code, audio_url, expires_at = job
soon = datetime.now(timezone.utc) + timedelta(minutes=5)
if status == "complete" and (not expires_at or datetime.fromisoformat(expires_at.replace("Z", "+00:00")) < soon):
# Media is fetched here, on read: media URLs last 6 hours.
with diffio_for(user_id) as diffio:
media = diffio.generations.media(project_id, generation_id)
audio_url, expires_at = media.files["audio"], media.expires_at
with conn:
conn.execute("update jobs set audio_url = ?, expires_at = ? where project_id = ?",
(audio_url, expires_at, project_id))
return jsonify(status=status, error_code=error_code, audio_url=audio_url, expires_at=expires_at)
@app.post("/webhooks/diffio")
def diffio_webhook():
try:
event = verify_webhook_signature(request.get_data(), request.headers, os.environ["DIFFIO_WEBHOOK_SECRET"])
except WebhookVerificationError:
return "", 400
data = event.data
with db() as conn: # one transaction: the receipt and the job update commit together, or neither does
first = conn.execute("insert or ignore into webhook_events (id, type, created_at) values (?, ?, ?)",
(event.id, event.type, event.created_at)).rowcount
if first and event.type in ("generation.completed", "generation.failed"):
# Only the job this generation started, for the user the event names.
conn.execute("update jobs set status = ?, error_code = ?"
" where project_id = ? and generation_id = ? and user_id = ?",
("complete" if event.type == "generation.completed" else "failed", data.error_code,
data.project_id, data.id, data.end_user))
return "", 204 # after the commit; an exception above answers 500 and Svix retries
if __name__ == "__main__":
if sys.argv[1:] == ["portal"]:
# The webhook portal belongs to the whole account: a client with no end user.
account = DiffioClient()
print(account.webhooks.portal().url)
else:
app.run(port=3000)What you get

Uploaded
Restored by Diffio 4.7 Flash
- Each customer's projects live under their own end user: another customer's project id answers
404Not found.. - Files go from the browser to Diffio; your server never handles the audio.
- A restored MP3 URL for each finished episode, renewed before its 6 hours run out.
Response of GET /api/uploads/<project_id>
{
"status": "complete",
"error_code": null,
"audio_url": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/restored.mp3",
"expires_at": "2026-11-13T06:33:47Z"
}API reference
- POSTCreate a project (
/projects): Project, first generation and upload descriptors. - POSTGet new upload instructions (
/projects/{project_id}/upload): A new upload token when the old one expired. - POSTComplete a project's upload (
/projects/{project_id}/upload/complete): Check the file now instead of waiting. - GETGet a playback grant (
/projects/{project_id}/generations/{generation_id}/media): Fresh playback and download URLs. - POSTOpen the webhook portal (
/webhooks/portal): Add endpoints and copy the signing secret.