Virtual Try-On SDK for Python
Reference for the tryiton Python package: client options, every method, wait helpers, TryItOnError handling, live sessions in Flask and test stubs.
The tryiton package is the official Python client for the virtual try-on API.
It wraps every server endpoint of https://tryiton.now/api/v1, raises one error class, and polls jobs for you. New
to the API? Run your first try-on with the Quickstart.
pip install tryitonIt needs Python 3.8 or later and uses requests for HTTP. The client is
synchronous: each call blocks until the response arrives. The package ships type hints (py.typed).
Configure the client
Retry GET requests only
A retried POST /tryon/* can create a second job and hold credits twice. The client below retries GET requests
on 502, 503 and 504, and leaves every POST alone.
import os
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from tryiton import TryItOn
# Retry GETs (status, credits, sessions) on gateway errors. Never retry a POST:
# a retried submit can create a second job.
session = requests.Session()
retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504], allowed_methods=["GET"])
session.mount("https://", HTTPAdapter(max_retries=retry))
client = TryItOn(api_key=os.environ["TRYITON_API_KEY"], timeout=30, session=session)
print(client.get_credits())| Argument | Type | Default | Description |
|---|---|---|---|
api_key | str | required | Your API key. An empty key raises TryItOnError with error_name="ConfigError". |
base_url | str | https://tryiton.now/api/v1 | API base URL (keyword only). A trailing slash is removed. |
timeout | float | 60.0 | Timeout for each HTTP request, in seconds (keyword only). A wait has its own timeout. |
session | requests.Session | a new session | Your own session, for retries, a proxy or a test stub (keyword only). |
Methods
Parameters are keyword arguments in snake_case. Arguments you leave as None are left out of the request, so the
API defaults apply.
| Method | Endpoint | Returns |
|---|---|---|
try_on_fashion(**kwargs) | POST /tryon/fashion | job id (str) |
try_on_hairstyle(**kwargs) | POST /tryon/hairstyle | job id (str) |
try_on_tattoo(**kwargs) | POST /tryon/tattoo | job id (str) |
get_status(job_id) | GET /status/{id} | Status dataclass (status, output, error) |
wait_for_result(job_id, ...) | polls GET /status/{id} | result URLs (list[str]) |
get_credits() | GET /credits | Credits dataclass |
get_live_config() | GET /live/config | dict |
prepare_live_garment(garment_image, ...) | POST /live/garments | garment dict |
prepare_live_outfit(garment_ids, ...) | POST /live/outfits | garment dict |
start_live_session(**kwargs) | POST /live/sessions | full response dict |
list_live_sessions(**kwargs) | GET /live/sessions | dict with sessions, nextCursor |
get_live_session(session_id) | GET /live/sessions/{id} | session dict |
stop_live_session(session_id) | POST /live/sessions/{id}/stop | session dict |
The live methods return plain dicts with the API's camelCase keys, typed as TypedDicts (LiveSessionStart,
LiveSession, …). The package also exports HAIRCUTS, the 42 accepted haircut values. Images are public URLs or
base64 data URLs. The snippets below reuse the client from above.
fashion_job_id = client.try_on_fashion(
model_image="https://example.com/model.jpg",
garment_image="https://example.com/tshirt.jpg",
category="clothing",
subcategory="tops",
)
hair_job_id = client.try_on_hairstyle(
face_image="https://example.com/face.jpg",
haircut="PixieCut",
hair_color="copper red",
)
tattoo_job_id = client.try_on_tattoo(
body_image="https://example.com/forearm.jpg",
design_image="https://example.com/rose.png",
region={"x": 0.32, "y": 0.18, "w": 0.28, "h": 0.34},
)Wait for results
wait_for_result(job_id, *, poll_interval=2.0, timeout=120.0) polls every 2 seconds and gives up after 120 seconds.
It returns the result URLs, or raises ProcessingError (the job failed) or Timeout. Every job has a final status
within 4 minutes, so a 4-minute wait never gives up early:
urls = client.wait_for_result(fashion_job_id, timeout=240)Timeout only stops the wait. The job keeps running, so poll it later instead of resubmitting. To check a stored job
id from a worker (Celery, RQ), call get_status yourself:
job = client.get_status(fashion_job_id)
if job.status == "completed":
print(job.output)
elif job.status == "failed":
print("Failed:", job.error)output is an empty list until the job completes, and error is the failure reason as a string, or None. See
Jobs, Polling & Retries for job lifetimes.
Errors
Every API error and failed job raises TryItOnError. Branch on error_name, not on the message.
| Attribute | Type | Description |
|---|---|---|
status | int or None | HTTP status. None for errors raised by the SDK. |
error_name | str or None | The API error name, such as OutOfCredits, or an SDK name below. None for a non-JSON error page. |
str(err) | str | Human-readable text. For ProcessingError, the job's failure reason. |
from tryiton import TryItOnError
try:
urls = client.wait_for_result(fashion_job_id, timeout=240)
print(urls[0])
except TryItOnError as err:
if err.error_name == "ProcessingError":
print("Failed, not charged:", err)
elif err.error_name == "Timeout":
print("Still running. Poll it later.")
else:
print(f"{err.status} {err.error_name}: {err}")The SDK adds these names, all with status None: ProcessingError, Timeout (the wait gave up), NetworkError
(any requests exception, including a request that hit timeout) and ConfigError. RateLimitExceeded,
ConcurrencyLimitExceeded, 500 and 503 are worth retrying with backoff. OutOfCredits, 400, 403, 404 and
413 are not. See when to retry and the full list of
error codes.
Verify webhooks
verify_webhook (SDK 2.5 or later) checks that a webhook request came from TryItOn and returns the event.
Pass the raw body exactly as it arrived.
import os
from flask import Flask, request
from tryiton import TryItOnError, verify_webhook
app = Flask(__name__)
@app.post("/webhooks/tryiton")
def tryiton_webhook():
try:
event = verify_webhook(request.get_data(), request.headers, os.environ["TRYITON_WEBHOOK_SECRET"])
except TryItOnError:
return "", 400
if event["type"] == "tryon.completed":
print(event["data"]["jobId"], event["data"]["output"])
return "", 200verify_webhook(payload, headers, secret, *, tolerance_seconds=300, now=None) takes the body as bytes or str
(Django: request.body) and any headers mapping, a WSGI environ included. It raises TryItOnError with
error_name="WebhookVerificationFailed" and status=None.
Live try-on from your server
Your server prepares garments and starts sessions with the API key. The shopper's browser streams with the
tryiton-live package and never sees the key.
import os
from flask import Flask, jsonify, request
from tryiton import TryItOn, TryItOnError
client = TryItOn(api_key=os.environ["TRYITON_API_KEY"])
# Once per product, for example at catalog sync. Store garment["id"].
garment = client.prepare_live_garment(
"https://example.com/tshirt.jpg", category="clothing", subcategory="tops"
)
app = Flask(__name__)
# The browser POSTs {"garmentId": ...} and passes the response to connectLiveTryOn.
@app.post("/live-session")
def live_session():
body = request.get_json(silent=True) or {}
try:
start = client.start_live_session(
garment_id=body.get("garmentId"),
end_user_id="shopper-42", # your signed-in shopper's id, from your session
allowed_origin="https://shop.example.com",
)
except TryItOnError as err:
error = {"name": err.error_name, "message": str(err)}
return jsonify(ok=False, error=error), err.status or 502
return jsonify(start) # unchanged
if __name__ == "__main__":
app.run(port=3000)end_user_id gives each shopper one stream: starting again ends the previous one. allowed_origin locks the media
token to your site. Sessions start on the primary stream and switch to the backup stream if it fails to connect.
prepare_live_outfit(garment_ids) combines 2 or 3 prepared garments, and its id works like a garment id. The
browser side is in the Real-Time Virtual Try-On Quickstart, and billing in
Live Try-On Billing.
Testing
Pass a mock session to test your code without network calls or credits. The client calls
session.request(method, url, headers=..., json=..., timeout=...):
import json
from unittest import mock
import requests
from tryiton import TryItOn
def fake_response(status, body):
resp = requests.Response()
resp.status_code = status
resp._content = json.dumps(body).encode()
return resp
def test_try_on_fashion():
session = mock.Mock(spec=requests.Session)
session.request.return_value = fake_response(201, {"ok": True, "jobId": "job_123"})
client = TryItOn(api_key="YOUR_API_KEY", session=session)
job_id = client.try_on_fashion(
model_image="https://example.com/model.jpg",
garment_image="https://example.com/tshirt.jpg",
)
assert job_id == "job_123"
method, url = session.request.call_args.args
assert (method, url) == ("POST", "https://tryiton.now/api/v1/tryon/fashion")
assert session.request.call_args.kwargs["json"]["model_image"] == "https://example.com/model.jpg"Return {"ok": False, "error": {"name": ..., "message": ...}} with a 4xx status to test your error handling.
Libraries such as responses work too, since the client sends everything through requests.
Node.js
Reference for the tryiton npm package: client options, methods, wait helpers, TryItOnError handling, live sessions and test stubs for Node.js and TypeScript.
Go
Reference for the tryiton-go/v2 module: client options, every method, context timeouts, *tryiton.Error handling, live sessions in net/http and httptest stubs.