PYTHON INTEGRATION RECIPES

Idiomatic Python for async and synchronous pipelines.

Build production pipelines using requests. Submit generation jobs, poll task status with backoff, inspect append-only billing ledgers, and verify cryptographic webhooks.

1import os
2import time
3import requests
4 
5BASE = "https://api.apimarketplace.com"
6headers = {"Authorization": "Bearer " + os.environ["API_KEY"]}
7 
8def call(method, path, **kwargs):
9 response = requests.request(method, BASE + path, headers=headers, timeout=300, **kwargs)
10 response.raise_for_status()
11 return response.json() if response.content else None
12 
13def wait(path, success):
14 deadline = time.monotonic() + 900
15 while time.monotonic() < deadline:
16 result = call("GET", path)
17 if result["status"] == success:
18 return result
19 if result["status"] == "failed":
20 raise RuntimeError(result.get("errorMessage") or "Generation failed")
21 time.sleep(3)
22 raise TimeoutError("Still pending; keep the returned ID and check later")
23 
24character = call("POST", "/v1/characters", json={'name': 'Example character',
25 'model_alias': 'photoreal-v1',
26 'subject': 'A 30-year-old adult with brown eyes and short brown hair',
27 'action': 'Wearing a blue shirt, facing the camera',
28 'environment': 'A plain studio'})
29print("Character ID:", character["id"])
30wait("/v1/characters/" + character["id"], "ready")
31payload = {'model_alias': 'photoreal-v1',
32 'action': 'Wearing a green jacket, standing by a window',
33 'environment': 'A modern apartment in soft morning light',
34 'aspect_ratio': '2:3'}
35payload["character_id"] = character["id"]
36generation = call("POST", "/v1/generations", json=payload)
37print("Generation ID:", generation["id"])
38completed = wait("/v1/generations/" + generation["id"], "completed")
39print("Temporary output URL:", completed["outputUrl"])
RECIPE // SYNCHRONOUS BILLING

Recipe 1: Check Credit Ledger with Requests

Query account balance and credit ledger transactions synchronously.

1import os
2import time
3import requests
4 
5BASE = "https://api.apimarketplace.com"
6headers = {"Authorization": "Bearer " + os.environ["API_KEY"]}
7 
8def call(method, path, **kwargs):
9 response = requests.request(method, BASE + path, headers=headers, timeout=300, **kwargs)
10 response.raise_for_status()
11 return response.json() if response.content else None
12 
13def wait(path, success):
14 deadline = time.monotonic() + 900
15 while time.monotonic() < deadline:
16 result = call("GET", path)
17 if result["status"] == success:
18 return result
19 if result["status"] == "failed":
20 raise RuntimeError(result.get("errorMessage") or "Generation failed")
21 time.sleep(3)
22 raise TimeoutError("Still pending; keep the returned ID and check later")
23 
24result = call('GET', '/v1/billing')
25print(result)
RECIPE // FASTAPI WEBHOOK RECEIVER

Recipe 2: Webhook Signature Verification

Safeguard your webhook receiving endpoint using hmac.compare_digest.

1import hashlib
2import hmac
3import json
4import time
5 
6def verify_webhook(raw_body: bytes, signature_header: str, secret: str):
7 # Pass the X-Webhook-Signature header and the original request bytes.
8 try:
9 parts = dict(part.split("=", 1) for part in signature_header.split(","))
10 timestamp = int(parts["t"])
11 signature = parts["v1"]
12 except (ValueError, KeyError):
13 raise ValueError("Malformed webhook signature") from None
14 if abs(int(time.time()) - timestamp) > 300:
15 raise ValueError("Expired webhook")
16 expected = hmac.new(secret.encode(), str(timestamp).encode() + b"." + raw_body,
17 hashlib.sha256).hexdigest()
18 if not hmac.compare_digest(expected, signature):
19 raise ValueError("Invalid signature")
20 event = json.loads(raw_body)
21 # Persist event["id"] with a UNIQUE constraint before enqueueing your own work.
22 # Return HTTP 2xx promptly. Repeated IDs must not repeat your side effects.
23 return event
PRODUCTION RUNTIME

Start integrating in Python.

Create your account to get an API key and test these recipes in your environment.