← Lesson
HTTP and APIs
Joeven
Run
Reset
Python loads on first run
CALLS = {"search": 0} SLOW = {("GET", "/slow"): 10} def health(req): return {"status": 200, "body": {"ok": True}} def search(req): q = (req.get("body") or {}).get("q") if not q: return {"status": 400, "body": {"error": "q is required"}} CALLS["search"] += 1 if CALLS["search"] > 2: return {"status": 429, "body": {"error": "too many requests"}} return {"status": 200, "body": {"hits": ["note about " + q]}} def boom(req): return {"status": 500, "body": {"error": "server broke"}} def messages(req): return {"status": 200, "body": {"type": "tool", "name": "search"}} ROUTES = { ("GET", "/health"): health, ("POST", "/tools/search"): search, ("GET", "/boom"): boom, ("POST", "/v1/messages"): messages, } def request(method, path, body=None, headers=None, timeout=2): headers = headers or {} body = body or {} delay = SLOW.get((method, path), 0) if delay > timeout: return {"status": "timeout", "body": {"error": "no answer in time"}} if path.startswith("/v1/") and headers.get("Authorization") != "Bearer demo": return {"status": 401, "body": {"error": "need a key"}} handler = ROUTES.get((method, path)) if handler is None: return {"status": 404, "body": {"error": "not found"}} req = {"method": method, "path": path, "body": body, "headers": headers} return handler(req) print("health", request("GET", "/health")) print("search", request("POST", "/tools/search", body={"q": "rain"})) print("bad args", request("POST", "/tools/search", body={})) print("auth", request("POST", "/v1/messages", body={"prompt": "hi"})) print("ok auth", request("POST", "/v1/messages", headers={"Authorization": "Bearer demo"})) print("search2", request("POST", "/tools/search", body={"q": "coat"})) print("search3", request("POST", "/tools/search", body={"q": "hat"})) print("boom", request("GET", "/boom")) print("slow", request("GET", "/slow", timeout=2)) print("missing", request("GET", "/nope"))
Run to execute this in your browser. Nothing is sent to a server.