#!/usr/bin/env python3 """Executable standard-library ScriptHaul examples used by the documentation CI. Every scenario is checked against the real API contract: expected status plus a field the response actually carries. """ import json import os import sys from urllib.error import HTTPError from urllib.parse import quote from urllib.request import Request, urlopen scenario = sys.argv[1] if len(sys.argv) > 1 else "quickstart" base = os.environ.get("SCRIPTHAUL_BASE_URL", "https://api.scripthaul.com").rstrip("/") key = os.environ.get("SCRIPTHAUL_API_KEY", "") email = os.environ.get("SCRIPTHAUL_EMAIL", "developer@example.test") cases = { "authentication": ("GET", "/v1/keys", None, 200, '"keys"'), "transcripts": ("GET", "/v1/transcript?video_id=jNQXAC9IVRw&language=es&fallback=true&format=json", None, 200, "We the People"), "video-facts": ("GET", "/v1/video?video_id=jNQXAC9IVRw", None, 200, "cached_languages"), "listing": ("GET", "/v1/videos?url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2F%40YouTube&contents=videos&offset=0", None, 200, "next_offset"), "search": ("GET", "/v1/search?q=public%20domain&type=video", None, 200, "has_more"), "channel-search": ("GET", "/v1/search?q=public%20domain&channel=%40YouTube", None, 200, "has_captions"), "channels": ("GET", "/v1/channels/resolve?input=%40YouTube", None, 200, "uploads_playlist_id"), "latest-uploads": ("GET", "/v1/channels/latest?channel=UC0123456789abcdefghijkl", None, 200, "published_at"), "playlist-latest": ("GET", "/v1/channels/latest?playlist=UU0123456789abcdefghijkl", None, 200, "published_at"), "library": ("GET", "/v1/library?channel=UC0123456789abcdefghijkl", None, 200, "videos_known"), "library-search": ("GET", "/v1/library/search?q=%22We%20the%20People%22&channel=UC0123456789abcdefghijkl&limit=10&offset=0", None, 200, "We the People"), "monitors": ("POST", "/v1/monitors", {"channel": "UC0123456789abcdefghijkl", "auto_fetch": False}, 201, '"monitor"'), "pasted-lists": ("POST", "/v1/videos/resolve", {"text": "Research queue:\nhttps://youtu.be/jNQXAC9IVRw\ninvalid-id"}, 200, '"notFound"'), "bulk-jobs": ("POST", "/v1/jobs", {"input": "list:0123456789abcdef", "format": "json"}, 202, '"credits":{"reserved"'), "webhooks": ("GET", "/v1/webhooks", None, 200, "configured"), "languages": ("GET", "/v1/transcript?video_id=jNQXAC9IVRw&language=es&fallback=false&format=json", None, 200, '"delivered":"es"'), "mcp": ("POST", "/mcp", {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}, 200, "create_bulk_job"), "credits-limits": ("GET", "/v1/usage", None, 200, '"rows"'), "errors": ("GET", "/v1/transcript?video_id=aaaaaaaaaaa", None, 410, "Unavailable"), "status": ("GET", "/v1/status", None, 200, '"healthy"'), "migrating": ("GET", "/v1/transcript?video_id=jNQXAC9IVRw&format=json&language=en&fallback=false", None, 200, "not_requested"), "changelog": ("GET", "/v1/status", None, 200, '"canary"'), } if scenario not in cases: raise SystemExit(f"Unknown scenario: {scenario}") method, path, body, expected_status, marker = cases[scenario] headers = {"Accept": "application/json"} if not path.startswith("/v1/auth/") and path != "/v1/status": headers["Authorization"] = f"Bearer {key}" data = None if body is None else json.dumps(body).encode("utf-8") if data is not None: headers["Content-Type"] = "application/json" if scenario == "bulk-jobs": headers["Idempotency-Key"] = "docs-bulk-job" request = Request(f"{base}{path}", data=data, headers=headers, method=method) # A cold transcript request is held for up to 25 seconds before the API # answers 202 with a poll_url, so the socket timeout must sit well above that. try: with urlopen(request, timeout=60) as response: status = response.status text = response.read().decode("utf-8") except HTTPError as error: status = error.code text = error.read().decode("utf-8") if status != expected_status or marker not in text: raise SystemExit(f"{scenario}: expected HTTP {expected_status} and {marker}; got {status}: {text}") if scenario == "monitors": monitor_id = json.loads(text)["monitor"]["id"] monitor_path = "/v1/monitors/" + quote(monitor_id, safe="") def monitor_request(method, path, marker): request = Request(base + path, method=method, headers={"Authorization": f"Bearer {key}"}) with urlopen(request, timeout=60) as reply: result = reply.read().decode("utf-8") if reply.status != 200 or marker not in result: raise SystemExit(f"Monitor {method} failed: {reply.status}: {result}") try: monitor_request("GET", "/v1/monitors", monitor_id) monitor_request("GET", monitor_path, monitor_id) finally: monitor_request("DELETE", monitor_path, '"cancelled":true') sys.stdout.write(text)