# TryItOn Virtual Try-On API > AI virtual try-on for clothing and accessories, hairstyles and tattoos (async jobs), plus real-time live try-on through a shopper's webcam (streaming sessions). - Base URL: https://tryiton.now/api/v1 - Auth: `Authorization: Bearer ` from https://tryiton.now/app/developer. Missing or invalid key: 403 `Forbidden`. Call from your server only. - Responses: success `{ "ok": true, ... }`; errors `{ "ok": false, "error": { "name", "message" } }`. Branch on `error.name`. - Photo try-ons: POST /tryon/fashion | /tryon/hairstyle | /tryon/tattoo returns `jobId`; poll GET /status/{jobId} every ~2 s, or get a signed webhook POST (`tryon.completed` / `tryon.failed`, Standard Webhooks signatures; endpoint set in the dashboard). 1 credit per output image. - Live try-on: server prepares garments (POST /live/garments) and starts sessions (POST /live/sessions); the browser streams with the `tryiton-live` npm package. - SDKs: Node.js `tryiton`, Python `tryiton`, Go `github.com/tryiton-now/tryiton-go/v2`, PHP `tryiton/tryiton`, Ruby `tryiton`. - OpenAPI 3.1 spec: https://docs.tryiton.now/openapi.yaml - Every page below is also plain markdown: append `.md` to its URL (or send `Accept: text/markdown`). # Authentication & API Keys (/docs/concepts/authentication) Every request to the TryItOn virtual try-on API carries an API key in the `Authorization` header. A key belongs to your TryItOn account: every request made with it spends that account's credits and counts against its rate limits. The API is built to be called from your server. Keep the key there. ## Create an API key [#create-an-api-key] Sign in and open **Developer API → API Keys** at [tryiton.now/app/developer](https://tryiton.now/app/developer). In the **API Keys** table, click **+ Create new API Key**. Don't use **Site Keys**: those are for the [storefront widget](/docs/guides/embed-widget) and don't work with `/api/v1` server endpoints. Give the key a name (up to 50 characters), such as `production-backend`, and click **Create Key**. Copy the key. It's shown only once. Store it in your secret manager or environment, then click **I've saved my key**. An account can have up to 10 API keys. ## Send the key [#send-the-key] Send the key as a Bearer token on every request. The base URL for all endpoints is `https://tryiton.now/api/v1`. ```http Authorization: Bearer YOUR_API_KEY ``` [`GET /credits`](/docs/api-reference/credits-balance) is the cheapest way to check a key. It costs no credits and returns your balance: ```bash curl https://tryiton.now/api/v1/credits \ -H "Authorization: Bearer YOUR_API_KEY" ``` A working key returns `200` with `{ "ok": true, "credits": { ... } }`. A bad key returns `403`. The [SDKs](/docs/sdks) set the header for you from the key you pass to the client. ## Authentication errors [#authentication-errors] The API answers authentication problems with **`403 Forbidden`**. It never returns `401` for a bad or missing key, so handle `403` wherever your HTTP client handles auth failures. | Status | `error.name` | `error.message` | Cause | |---|---|---|---| | 403 | `Forbidden` | `Missing or invalid Authorization header.` | No `Authorization` header, or it doesn't start with `Bearer `. | | 403 | `Forbidden` | `API key is invalid.` | The key doesn't exist: mistyped, deleted, or a site key. | | 403 | `Forbidden` | `Your account has been disabled. Please contact support.` | The account that owns the key is disabled. | | 500 | `InternalServerError` | `Failed to verify API key.` | The key check itself failed on our side. Retry with backoff. | Retrying a `403` with the same key won't help. Fix the key or header first. See [Error Codes & Handling](/docs/concepts/errors) for every error the API returns. ## Keep the key on your server [#keep-the-key-on-your-server] Call the API from your backend, never from a browser or a mobile app bundle: - **Anyone who has the key can spend your credits.** A key in front-end JavaScript or an app binary is public. - **Browsers are blocked anyway.** The server endpoints only allow cross-origin requests from TryItOn's own sites, so a `fetch` from your web page fails the CORS check. - **Mobile apps** should call your own backend, which calls TryItOn with the key. The one exception is [live try-on](/docs/api-reference/live-tryon). Your server starts the session with the API key, then passes the session's own short-lived credentials to the browser. The [browser endpoints](/docs/api-reference/live-tryon-browser-endpoints) accept those credentials and are open to cross-origin requests. The API key never reaches the browser. ## Key hygiene [#key-hygiene] - **Load the key from the environment** (`TRYITON_API_KEY` in the samples) or a secret manager. Don't commit it. - **Use one key per service or environment** and name it after where it runs. When a key leaks you can delete that one key without breaking the others. - **Use one key per store or client** to see usage store by store. **Developer API → Analytics** has a **Usage by API key** table with try-ons, live sessions, live time and live credits for each key. All keys of an account share one credit balance. Usage from before this was recorded shows under **Other**. - **Don't log the `Authorization` header.** Redact it in request logging and error reporting. - **Rotate by creating a new key.** A key's value can't be regenerated. Create a new key, deploy it, confirm traffic works, then delete the old key with the delete icon in the **API Keys** table. A deleted key stops working right away. - **If a key leaks, delete it now**, then create a replacement. Check **Developer API → Requests** in the dashboard for requests you don't recognise. ## Related [#related] - [Virtual Try-On API Quickstart](/docs/getting-started/quickstart) - [Error Codes & Handling](/docs/concepts/errors) - [Rate Limits & Concurrency](/docs/concepts/rate-limits) - [Get Credits Balance](/docs/api-reference/credits-balance) # Virtual Try-On API Pricing & Credits (/docs/concepts/credits-and-pricing) The TryItOn virtual try-on API is paid with credits. You buy credits and spend them on any model: clothing and accessories, hairstyle, tattoo and live try-on. You pay for the images and live seconds you actually get, not for requests. ## How virtual try-on API pricing works [#how-virtual-try-on-api-pricing-works] | Model | Endpoint | Cost | |---|---|---| | Clothing & accessories | `POST /tryon/fashion` | 1 credit per output image | | Hairstyle | `POST /tryon/hairstyle` | 1 credit per output image | | Tattoo | `POST /tryon/tattoo` | 1 credit per output image | | Live (real-time webcam) | `POST /live/sessions` | 1 credit per `secondsPerCredit` seconds of streaming (3 seconds by default) | `num_samples` (1 to 4) sets how many images a photo try-on produces, so one request costs 1 to 4 credits. Checking a job (`GET /status/{id}`), reading your balance (`GET /credits`), reading the live config and preparing a live garment are free. Buy credit packs or a subscription at [tryiton.now/app/billing](https://tryiton.now/app/billing). ## One balance for everything [#one-balance-for-everything] Your account has one credit balance. The TryItOn web app, browser extension, mobile app, storefront widget and the API all spend from it, and all your API keys share it. Storefront widget try-ons on the same account also share your API [rate limits](/docs/concepts/rate-limits). ## You pay only for images you get [#you-pay-only-for-images-you-get] - **Partial success:** a job that asked for `num_samples: 4` may come back with fewer images in `output`. You're charged only for the images produced. - **Failed jobs are free:** a job that ends with `status: "failed"`, including one that timed out after 3 minutes, costs nothing. - **Rejected requests are free:** a request that returns an error (400, 403, 429, …) creates no job and no charge. ## Credit holds [#credit-holds] When you submit a photo try-on, the API checks that you have at least `num_samples` spendable credits and **holds** that many while the job runs. When the job ends, the hold turns into a charge for the images produced and the rest is released. - Held credits can't be spent on another job. A request that needs more than you have left fails with `429 OutOfCredits`. - Photo try-on holds count toward the concurrency limit: new work is refused while 10 or more credits are held. See [concurrency](/docs/concepts/rate-limits#concurrency). ## Read your balance [#read-your-balance] [`GET /credits`](/docs/api-reference/credits-balance) returns four numbers: | Field | Meaning | |---|---| | `subscription` | Credits from your subscription plan's allowance. | | `purchased` | Credits from packs you bought. They don't expire. Refunds land here. | | `reserved` | Credits held by in-flight jobs and live sessions right now. | | `on_demand` | `subscription + purchased + reserved`. | `on_demand` **includes** held credits, so it is not what you can spend. Compute spendable credits yourself: `spendable = subscription + purchased − reserved` For example, this response means you can start jobs worth 149 credits, not 151: ```json title="GET /credits" { "ok": true, "credits": { "on_demand": 151, "subscription": 50, "purchased": 100, "reserved": 1 } } ``` Before a batch, read `/credits`, compute `spendable`, and only submit as many images as it covers. The API still enforces the balance on every request, so treat the pre-check as a courtesy, not a guarantee. ## Live try-on billing [#live-try-on-billing] Live sessions are billed by streaming time. A start needs at least `minCredits` spendable credits (enough for 10 seconds, 4 credits at the default price) and holds 1 credit. Billing starts with the first try-on frame. Read `secondsPerCredit`, `minCredits` and `maxSeconds` from `GET /live/config` instead of hard-coding them. The full rules, including how partial periods and failed starts are charged, are in [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Related [#related] - [Get Credits Balance](/docs/api-reference/credits-balance) - [Rate Limits & Concurrency](/docs/concepts/rate-limits) - [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) - [Live Try-On Billing](/docs/concepts/live-tryon-billing) # Data Retention & Privacy (/docs/concepts/data-retention-and-privacy) This page lists what the virtual try-on API keeps when you call it, and for how long. Use it to answer privacy questions from your users and to plan what you need to store on your side. ## Summary [#summary] | Data | Stored by TryItOn? | How long | |---|---|---| | Input images for photo try-ons (URLs or base64) | Not saved to storage or the job record | Only in the processing queue while the job runs | | Job records (metadata only) | Yes | Until your account is deleted | | Result images | Yes | About 72 hours after submission | | Shared copies of storefront widget results | Yes | 30 days | | Live garments and outfits you prepare | Yes | Until unused for 90 days, or your account is deleted | | Live video | No | Never stored | | Live session usage (duration, credits, end reason, API key, `end_user_id`) | Yes | Until your account is deleted | | Item auto-detection results | Yes, without the image | 7 days | ## Input images [#input-images] Photo inputs (`model_image`, `garment_image`, `face_image`, `body_image`, `design_image`) are fetched or decoded when the job runs and sent to the AI sub-processor that runs the job. TryItOn doesn't save them to its storage, and the job record holds no input images, URLs or base64 data, whichever form you sent. The inputs travel with the job through TryItOn's internal processing queue while it waits and runs. They're removed from the queue as soon as the job is finished for good: when it completes, or when it fails with no retry left. TryItOn's logs don't record input image URLs. ## Job records and results [#job-records-and-results] Each job keeps a small record: the job id, the try-on type, the category, the number of images, the status, the failure reason if it failed, the result file names, and timestamps. This is what you see under **Developer API → Requests** in the dashboard. Records are kept while your account exists. `GET /status/{id}` only serves jobs from the last 3 days; older ones return `404`. Result images are deleted about **72 hours after the job was submitted**. A cleanup runs every hour, and after it the result URLs stop working. Download a result before then if you need it longer. Result images carry an EXIF tag that marks them as AI-generated. When a shopper shares a result from the [storefront widget](/docs/guides/embed-widget), TryItOn makes a separate, watermarked copy for the share link. That copy is deleted after 30 days. ## Live try-on [#live-try-on] - **Prepared garments are stored.** For `POST /live/garments`, TryItOn keeps a normalized copy of the garment image, its category, a description and its prompt (including your own `instructions`), so sessions can switch to it instantly. Outfits (`POST /live/outfits`) are stored the same way, with the combined image. Both are deleted when nobody has used them for 90 days, or with your account. - **Extra views aren't stored.** `detail_images` are read once to write the description, then discarded. - **Video is never stored.** The shopper's camera video streams from their device to our real-time media sub-processor. It doesn't pass through TryItOn's servers and TryItOn doesn't store it. - **Usage is recorded** for billing: each session's duration, credits used and end reason, the API key that started it and the `end_user_id` you sent. Use an opaque id for `end_user_id`, not an email address or a name. Your site still has to tell shoppers about the camera before it turns on. The [Live Try-On Camera & Privacy Guide](/docs/guides/live-tryon-camera-privacy) has sample wording for your notice and privacy policy. ## Item auto-detection [#item-auto-detection] With `category: "auto"` (or no category) on a fashion try-on, the item type is detected from the garment image. The result is cached for 7 days, keyed by a hash of the image, so the same image isn't analysed twice. The image itself isn't stored. ## Sub-processors [#sub-processors] The AI and media sub-processors that run try-ons and live streams are listed in Annex 3 of our [Data Processing Agreement](https://tryiton.now/legal/dpa#annex-3-subprocessors). ## Account deletion [#account-deletion] Deleting your TryItOn account deletes your job records, your prepared live garments and their stored images. ## Related [#related] - [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) - [Image Guidelines](/docs/guides/image-guidelines) - [Live Try-On Camera & Privacy Guide](/docs/guides/live-tryon-camera-privacy) - [Authentication & API Keys](/docs/concepts/authentication) # Error Codes & Handling (/docs/concepts/errors) The virtual try-on API reports errors in two places. A request that can't be accepted gets a non-2xx HTTP response with an error envelope. A job that was accepted but then failed shows up later as `status: "failed"` on [`GET /status/{id}`](/docs/api-reference/job-status), with HTTP `200`. Handle both. ## The error envelope [#the-error-envelope] Every non-2xx response has the same shape: ```json title="Error response" { "ok": false, "error": { "name": "OutOfCredits", "message": "You do not have enough credits left." } } ``` Branch on `error.name`. It's stable and machine-readable. `error.message` is for humans and logs: its wording can change, so don't match on it. New names may be added, so treat an unknown name by its HTTP status. ## Error reference [#error-reference] | Status | `error.name` | When | What to do | |---|---|---|---| | 400 | `BadRequest` | The body isn't valid JSON. On `POST /tryon/hairstyle`: `face_image` or `haircut` is missing, or `haircut` isn't in the list. On live endpoints: a malformed id, an invalid `max_seconds`, `end_user_id`, `allowed_origin`, `description`, `instructions` or `enhance_prompt`, or outfit `garment_ids` that can't be worn together (see [live garments](/docs/api-reference/live-garments)). | Fix the request. Check the endpoint's parameters. | | 400 | `ImageLoadError` | A required image (`model_image`, `garment_image`, `body_image`, `design_image`) is missing. On `POST /live/garments`, which loads images during the request, also an image or `detail_images` entry that is badly formed or can't be fetched. | Send a public `http(s)` URL or a `data:image/...;base64,` URL. See [Image Guidelines](/docs/guides/image-guidelines). | | 400 | `InvalidCategory` | `category`/`subcategory` isn't a valid pair, or you sent a `subcategory` with `category: "auto"`. | Use a pair from the [fashion try-on](/docs/api-reference/fashion-tryon) table, or omit `subcategory`. | | 400 | `InvalidNumSamples` | `num_samples` isn't an integer from 1 to 4. | Send 1, 2, 3 or 4. | | 400 | `InvalidOutputFormat` | `output_format` isn't `png` or `jpeg`. | Send `png` or `jpeg`. | | 400 | `InvalidRegion` | Tattoo `region` isn't a valid `{x, y, w, h}` object (or JSON string of one). | Send four numbers from 0 to 1, or omit `region`. See [tattoo try-on](/docs/api-reference/tattoo-tryon). | | 403 | `Forbidden` | Missing or malformed `Authorization` header, unknown API key, or a disabled account. | Check the key and header. See [Authentication](/docs/concepts/authentication). Don't retry unchanged. | | 404 | `NotFound` | Unknown job id, a job older than 3 days, or an unknown live session or garment. On live browser endpoints, also a wrong session `secret`. | Check the id. Job results can't be fetched after 3 days. | | 404 | `ImageLoadError` | `POST /live/garments`: an image URL returned 404. | Fix the image URL. | | 409 | `LiveSessionActive` | A live session is already running for this `end_user_id`. | Stop the running session, or retry the start. | | 409 | `LiveSessionEnded` | A garment switch or failover on a live session that has already ended. | Start a new session. | | 409 | `LiveFailoverRefused` | A failover the session can't make: it has no backup stream, already streamed or switched, is past the 60-second window, or the account hit its daily limit. | End the session and start a new one. | | 413 | `PayloadTooLarge` | The JSON body is over 12 MB on `/tryon/*` and `/live/garments`, or over 10 KB on any other endpoint. | Send large images as a URL instead of base64. | | 429 | `OutOfCredits` | Not enough spendable credits: a photo try-on needs `num_samples` credits; a live session needs `minCredits`. | Buy credits at [tryiton.now/app/billing](https://tryiton.now/app/billing). Don't retry until you have. | | 429 | `ConcurrencyLimitExceeded` | Running photo try-ons already hold your account's concurrency limit in credits (10 by default). | Wait for a running job to finish, then retry. See [concurrency](/docs/concepts/rate-limits#concurrency). | | 429 | `RateLimitExceeded` | Over a request rate limit, such as 300/min per IP or 30/min per account for photo try-ons. | Back off and retry after the 60-second window. See [Rate Limits](/docs/concepts/rate-limits). | | 429 | `LiveTryonBusy` | The account already runs its maximum live sessions (3 by default), or live try-on is at capacity right now. | End a session, or retry in a minute. | | 429 | `GarmentLimitExceeded` | The account prepared 2000 new live garments and outfits today (UTC). | Reuse prepared garments, or prepare more after UTC midnight. | | 500 | `InternalServerError` | Something failed on our side, including the API key check or queuing the job. | Retry with exponential backoff. Contact support if it persists. | | 503 | `LiveTryonUnavailable` | Live try-on is turned off for your account (`enabled: false` in `/live/config`) or unavailable right now. | Retry later or fall back to a photo try-on. | The order of checks explains which error you see first: - On photo try-ons the API checks, in order: the API key (403), the per-account rate limit (429), the request body (400), then the account: disabled (403), credits, concurrency. - `OutOfCredits` comes before `ConcurrencyLimitExceeded`. If both apply, you get `OutOfCredits`. - The submit only checks that each required image is **present**. Fetching and decoding happen inside the job, so an unreachable URL or a corrupt file doesn't return `400`: the job ends with `status: "failed"`. ## Job failures [#job-failures] A failed job is not an HTTP error. `GET /status/{id}` returns `200` with the reason as a plain string: ```json title="GET /status/{id}: failed job" { "ok": true, "status": "failed", "output": [], "error": "Timed out." } ``` `error` is `null` unless the job failed. Common causes are an image URL that couldn't be fetched or a job still running after 3 minutes (`"Timed out."`). A failed job costs nothing. Resubmitting is safe, but fix the input first if the reason points at it. See [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling). ## Errors in the SDKs [#errors-in-the-sdks] Each SDK raises one error type for both API errors and failed jobs: [Node.js](/docs/sdks/node#errors) and [Python](/docs/sdks/python#errors) `TryItOnError`, [Go](/docs/sdks/go#errors) `*tryiton.Error`, [PHP](/docs/sdks/php#errors) `TryItOn\TryItOnException`, [Ruby](/docs/sdks/ruby#errors) `Tryiton::Error`. It carries the HTTP status and the API's `error.name`, so you branch on the same names as above. The SDKs add a few names of their own, with no HTTP status: `ProcessingError` (the job failed), `Timeout` (the wait gave up; the job may still complete), `NetworkError` (no response), `ConfigError` (no API key) and `WebhookVerificationFailed` (a webhook request whose signature doesn't check out). ## When to retry [#when-to-retry] | Status | Retry? | How | |---|---|---| | 400, 404, 413 | No | The request is wrong. Fix it first. | | 403 | No | Fix the key or contact support about the account. | | 409 `LiveSessionActive` | After a change | Stop the running session for that end user, then start again. | | 409 `LiveSessionEnded`, `LiveFailoverRefused` | No | Start a new session. | | 429 `OutOfCredits` | No | Buy credits first. | | 429 `ConcurrencyLimitExceeded` | Yes | Wait until one of your running jobs finishes (poll it), then resubmit. | | 429 `RateLimitExceeded` | Yes | Exponential backoff with jitter, up to the 60-second window. There's no `Retry-After` header. | | 429 `LiveTryonBusy` | Yes | End one of your live sessions, or wait a minute. | | 429 `GarmentLimitExceeded` | After UTC midnight | Reuse garments you already prepared. | | 500 | Yes | Exponential backoff, a few attempts. | | 503 | Yes | Retry later. For live try-on, offer a photo try-on meanwhile. | | Job `failed` | Yes | Resubmit as a new job. It's free if it fails again. | | Your wait loop gave up | Don't resubmit yet | Keep polling the same `jobId`: the job may still complete. | | Submit got no response | Check first | The job may have been created. See [retries and duplicates](/docs/concepts/jobs-and-polling#retries-and-duplicate-jobs). | A submit that returned an error response created nothing billable, so resubmitting it is safe. ## Related [#related] - [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) - [Rate Limits & Concurrency](/docs/concepts/rate-limits) - [Authentication & API Keys](/docs/concepts/authentication) - [Image Guidelines](/docs/guides/image-guidelines) # Jobs, Polling & Retries (/docs/concepts/jobs-and-polling) Every photo try-on in the virtual try-on API is an asynchronous job. You submit it, get a `jobId` back right away, then poll [`GET /status/{id}`](/docs/api-reference/job-status) until the job is `completed` or `failed`. To skip the polling loop, set up a [webhook](/docs/guides/webhooks): we POST the result to your server when the job finishes. ## Job lifecycle [#job-lifecycle] > Diagram: Photo job lifecycle. POST /tryon/* returns 201 with a jobId, and the job’s credits are held. The job is then processing: poll GET /status/{id} every 2 seconds; most jobs finish within a minute. It ends as completed, with the result image URLs in output, the credits charged and the images kept for about 72 hours. Or it ends as failed, with the reason in error and the held credits released, so it costs nothing. A job still processing after 3 minutes fails with "Timed out.". **Submit.** `POST /tryon/fashion`, `/tryon/hairstyle` or `/tryon/tattoo` returns `201` with the job id. The job's credits are [held](/docs/concepts/credits-and-pricing#credit-holds) from this moment. ```json title="201 Created" { "ok": true, "jobId": "64b7f1a9d9a3b8e5c7f9a123" } ``` **Processing.** `GET /status/{id}` returns `status: "processing"` and an empty `output` while the job runs. Most jobs finish well within a minute. ```json title="200 OK: processing" { "ok": true, "status": "processing", "output": [], "error": null } ``` **Completed or failed.** A finished job has `status: "completed"` and one URL per image in `output`: ```json title="200 OK: completed" { "ok": true, "status": "completed", "output": ["https://cdn.tryiton.now/USER_ID/tryons/3f2c9a.png"], "error": null } ``` A failed job has `status: "failed"`, an empty `output` and the reason as a plain string in `error`. This is still HTTP `200`: the status request worked, the job didn't. ```json title="200 OK: failed" { "ok": true, "status": "failed", "output": [], "error": "Timed out." } ``` `output` is always an array and `error` is always a string or `null`, so you can read both without checking for missing fields. Result files are `.png` or `.jpg`, matching the `output_format` you sent. Result images carry an EXIF tag that marks them as AI-generated. ## Polling [#polling] - **Poll every 2 seconds.** Polling faster doesn't make the job finish sooner and spends the 300 requests/minute per-IP [rate limit](/docs/concepts/rate-limits) that all your requests share. - **Stop at `completed` or `failed`.** Both are final. A job never goes back to `processing`. - **Jobs time out after 3 minutes.** A job still processing 3 minutes after submission is marked `failed` with `"Timed out."` and isn't charged. The check runs every minute, so every job has a final status within about 4 minutes. - **Bound your wait at about 4 minutes.** If your wait gives up earlier, keep polling the same `jobId` rather than resubmitting. A minimal loop, in plain JavaScript: ```js const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function waitForJob(jobId, timeoutMs = 6 * 60_000) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const res = await fetch(`https://tryiton.now/api/v1/status/${jobId}`, { headers: { Authorization: `Bearer ${process.env.TRYITON_API_KEY}` }, }); const { status, output, error } = await res.json(); if (status === "completed") return output; if (status === "failed") throw new Error(`Job failed: ${error}`); await sleep(2_000); } throw new Error("Still processing: poll this jobId again later"); } ``` Every SDK has a [wait helper](/docs/sdks#wait-helpers) that does this for you. It polls every 2 seconds and gives up after 120 seconds (Go waits until its context ends). That covers almost every job. Raise it to 4 minutes to always get a final status. ## Result lifetime [#result-lifetime] - **Download results you want to keep.** Result images are deleted about **72 hours after the job was submitted** (an hourly cleanup), and their URLs stop working. - **Job records expire for polling after 3 days.** After that, `GET /status/{id}` returns `404 NotFound`. Your request history stays visible in the dashboard under **Developer API → Requests**. ## Retries and duplicate jobs [#retries-and-duplicate-jobs] The API has no idempotency keys, so a retried submit is a new job. What to do depends on how the first attempt ended: | First attempt | Was a job created? | What to do | |---|---|---| | Returned `201` with a `jobId` | Yes | Don't resubmit. Poll that `jobId`. | | Returned an error response (`4xx`/`5xx`) | No, nothing billable | Retrying is safe once the cause is fixed. See [when to retry](/docs/concepts/errors#when-to-retry). | | Timed out or the connection dropped, no response | Maybe | If duplicates matter, check **Developer API → Requests** in the dashboard before resubmitting. A duplicate is billed only if it completes. | | Job ended `failed` | Yes, not billed | Resubmit as a new job. Fix the input first if the reason points at it. | | Your wait gave up | Yes, may still complete | Keep polling the same `jobId`. | To avoid paying twice for the same work, store the `jobId` with your own record (an order, a product, a user) as soon as the submit returns, and check it before submitting again. ## Related [#related] - [Get Job Status](/docs/api-reference/job-status) - [Webhooks](/docs/guides/webhooks) - [Error Codes & Handling](/docs/concepts/errors) - [Rate Limits & Concurrency](/docs/concepts/rate-limits) - [Data Retention & Privacy](/docs/concepts/data-retention-and-privacy) # Live Try-On Billing (/docs/concepts/live-tryon-billing) Live try-on spends the same credit balance as photo try-ons (see [Pricing & Credits](/docs/concepts/credits-and-pricing)). It's billed in **ticks**: 1 credit buys `secondsPerCredit` seconds of video, 3 by default. Read the current values from [`GET /live/config`](/docs/api-reference/live-tryon#get-the-live-config). ## How a session is charged [#how-a-session-is-charged] > Diagram: Live billing timeline at the default 3 seconds per credit. The start holds 1 credit. The billing clock starts at the first try-on frame. Every 3 seconds a heartbeat charges the held credit and holds the next one. The end charges the credit still held, so a partial tick rounds up: 10 seconds of video costs 4 credits. 1. **Start.** You need at least `minCredits` usable credits (10 seconds' worth, 4 by default). The start holds 1 credit. A start that returns an error holds nothing. 2. **Streaming.** `tryiton-live` starts the billing clock at the first try-on frame and sends a heartbeat every tick. Each heartbeat charges the held credit and holds the next one. When the next credit can't be held, the stream stops with `out_of_credits`. 3. **End.** Ending charges the held credit, so a partial tick rounds up: 10 seconds at 3 seconds per credit costs 4 credits. This is the same for every end: from the browser, from your server, a superseded session, or one that went stale. `secondsLeft` in the start and heartbeat responses is how long the session can still stream: the held credit plus your usable credits, capped by `max_seconds`. ## The server's clock sets a floor [#the-servers-clock-sets-a-floor] When a session ends, it pays at least for the time it was open: from the start to the end (or to when it went stale), minus up to 20 seconds for connecting, and never more than its media token can stream. Heartbeats normally cover this already. The floor only matters when a browser sends fewer heartbeats than the time it streamed. Balances never go below zero. ## When a session fails [#when-a-session-fails] - **The start fails: nothing.** No credit is held. - **The stream never connects: nothing, up to 5 times a day.** `tryiton-live` ends such a session with `reason: "error"` and `connected: false`. If that end arrives within 20 seconds of the start (or of a switch to the [backup stream](/docs/api-reference/live-sessions#backup-stream)) and no heartbeat has billed yet, the held credit goes back and the session shows `refunded: true`. This works for 5 sessions per account per UTC day. After that, a failed connect is charged like any other end, usually 1 credit. A connect that waits out its whole timeout can end just after the 20 seconds and is charged too. - **The stream drops after it connected: the time it streamed**, rounded up to the tick. - **The browser disappears without ending.** The session stays open until it goes stale (3 missed ticks plus 30 seconds), and the server's clock sets the charge. To keep this short, [stop the session](/docs/api-reference/live-sessions#stop-a-session) from your server when the shopper leaves. ## What's free [#whats-free] - Preparing garments and outfits (up to 2000 new ones a day). - Switching garments mid-stream. - Reading the live config and your sessions. - A start that returns an error, and a failed attempt before a failover to the backup stream. ## Check what you paid [#check-what-you-paid] Every session has `creditsCharged`, `refunded` and `creditsRefunded`. [List your sessions](/docs/api-reference/live-sessions#list-sessions) with `end_reason=error` to see failed streams, or `refunded=true` to see refunded ones. The dashboard shows the same list under **Developer API → Requests → Live**, and **Developer API → Analytics** has live sessions, time and credits per API key. If a charge looks wrong, email [contact@tryiton.now](mailto:contact@tryiton.now) with the session `id`. A refund from support shows on the session as `refunded: true` and `creditsRefunded`. # Rate Limits & Concurrency (/docs/concepts/rate-limits) The virtual try-on API applies two kinds of limits. **Rate limits** cap how many requests you send per time window. **Concurrency** caps how much work can run at once, measured in held credits. Both return `429` with a different `error.name`, and you handle them differently. ## Rate limits [#rate-limits] | Scope | Endpoints | Limit | Counted per | |---|---|---|---| | All requests | Every `/api/v1` endpoint, including `/health` | 300 requests / minute | IP address | | Photo try-ons | `POST /tryon/fashion`, `/tryon/hairstyle` and `/tryon/tattoo` combined | 30 requests / minute | Account | | Live garments | `POST /live/garments` and `POST /live/outfits` combined | 120 requests / minute | Account | | Live sessions | `POST /live/sessions` | 300 requests / hour | Account | | Live heartbeat | `POST /live/sessions/{id}/heartbeat` (browser) | 90 requests / minute | IP address | | Live garment switch | `POST /live/sessions/{id}/garments/{garmentId}` (browser) | 30 requests / minute | IP address | | Live failover | `POST /live/sessions/{id}/failover` (browser) | 20 requests / hour | IP address | | Live end | `POST /live/sessions/{id}/end` (browser) | 120 requests / minute | IP address | - **The photo try-on limit is per account, not per key.** More keys don't raise it. Try-ons on the same account from the TryItOn app and the [storefront widget](/docs/guides/embed-widget) count toward the same 30 per minute. - **The 300/minute IP limit is shared** by every request from that IP, polling included. Workers behind one NAT address share one budget. - Over a limit you get `429 RateLimitExceeded`. The API sends no `Retry-After` header and no rate-limit headers. ## Concurrency [#concurrency] Every running photo try-on **holds** `num_samples` credits until it ends. While **10 or more credits** are held by running photo try-ons on your account, new ones are refused with `429 ConcurrencyLimitExceeded`. The check looks at what's already held, not at the size of the new request. On an account with plenty of credits: | Step | Request | Held before | Result | Held after | |---|---|---|---|---| | 1 | Fashion try-on, `num_samples: 4` | 0 | Accepted | 4 | | 2 | Fashion try-on, `num_samples: 4` | 4 | Accepted | 8 | | 3 | Hairstyle try-on, `num_samples: 2` | 8 | Accepted (8 is under 10) | 10 | | 4 | Tattoo try-on, `num_samples: 1` | 10 | `429 ConcurrencyLimitExceeded` | 10 | | 5 | Step 1's job completes | | Its 4 credits are charged or released | 6 | | 6 | Retry step 4 | 6 | Accepted | 7 | So with `num_samples: 1` you can run up to 10 jobs at once. With `num_samples: 4` you can run 3 (the third is accepted because 8 is under 10, which brings the total to 12 held). Other rules: - **Live sessions:** at most 3 run at once per account. A fourth start returns `429 LiveTryonBusy`. Each running session holds 1 credit, but those holds don't count toward the photo try-on limit. - **Live garments:** up to 2000 new garments and outfits per account per UTC day (`429 GarmentLimitExceeded`). Repeat calls for a garment or outfit you already prepared don't count. - **Credits come first:** if you're also short of credits, you get `429 OutOfCredits` instead of `ConcurrencyLimitExceeded`. - **Stuck jobs don't block you for long.** A job still running after 3 minutes is failed and its hold is released. ## Raising the limits [#raising-the-limits] The photo try-on rate (30/minute), photo concurrency (10 held credits) and live sessions at once (3) are defaults. They can be raised per account on request: [contact us](https://tryiton.now/contact). ## How to back off [#how-to-back-off] - **`RateLimitExceeded`:** retry with exponential backoff and jitter, capped at 60 seconds, the length of the window. For example, wait `min(60, 2 × 2^attempt)` seconds plus up to 1 second of jitter, for up to 6 attempts. Better, pace yourself: keep photo try-on submits under 30 per minute per account with a queue on your side. - **`ConcurrencyLimitExceeded`:** don't retry on a timer. Wait until one of your running jobs reaches `completed` or `failed`, then submit the next. A local queue that keeps at most 10 one-image jobs (or 3 four-image jobs) in flight avoids the error entirely. - **`OutOfCredits`:** retrying won't help. Buy credits at [tryiton.now/app/billing](https://tryiton.now/app/billing). - **Polling:** poll each job every 2 seconds or slower. With many jobs in flight, the 300/minute IP limit is the one you hit first. The [SDKs](/docs/sdks) don't retry `429` for you. Wrap submits in your own backoff as above. ## Related [#related] - [Virtual Try-On API Pricing & Credits](/docs/concepts/credits-and-pricing) - [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) - [Error Codes & Handling](/docs/concepts/errors) # Go-Live Checklist for the Try-On API (/docs/getting-started/go-live-checklist) Run through this list before real users hit your integration. Each item links to the page that explains it. ## Keys [#keys] - [ ] The API key is only on your server, loaded from the environment or a secret manager. No browser, no app bundle, no repository. - [ ] Each environment has its own key, so you can delete a leaked one without downtime. - [ ] Your logs redact the `Authorization` header. See [Authentication](/docs/concepts/authentication). ## Credits and limits [#credits-and-limits] - [ ] You have enough credits for launch traffic, and you know your spendable balance is `subscription + purchased − reserved`, not `on_demand`. - [ ] You handle 429 `OutOfCredits` with a clear message, not a generic error. - [ ] You queue submits on your side so a traffic spike stays under 30 photo try-ons a minute and 10 credits in flight. Need more? [Ask us](https://tryiton.now/contact) to raise your limits. - [ ] Polling from many workers behind one IP stays under 300 requests a minute. See [Pricing & Credits](/docs/concepts/credits-and-pricing) and [Rate Limits](/docs/concepts/rate-limits). ## Jobs and errors [#jobs-and-errors] - [ ] You poll about every 2 seconds and wait about 4 minutes before giving up on a job. - [ ] You check `status` on every poll. A failed job is still HTTP 200. - [ ] You branch on `error.name`, never on `error.message`, and treat unknown names as generic errors. - [ ] You retry 429 `RateLimitExceeded` and 5xx with backoff, and you don't resubmit after a network error until you know the first submit failed. - [ ] You store each `jobId` with your own request, so support can trace it. - [ ] If you use webhooks: you verify `webhook-signature` on the raw body, answer within 10 seconds, skip repeated `webhook-id`s, and keep the signing secret on your server. See [Jobs & Polling](/docs/concepts/jobs-and-polling), [Webhooks](/docs/guides/webhooks) and [Errors](/docs/concepts/errors). ## Images and results [#images-and-results] - [ ] Input image URLs are public and stay reachable until the job finishes. No signed URLs that expire in seconds. - [ ] You download result images you want to keep. They're deleted after about 72 hours. - [ ] Your upload flow nudges users toward photos that work. See the [Image Guidelines](/docs/guides/image-guidelines). ## Privacy [#privacy] - [ ] Your privacy policy covers sending user photos to TryItOn. See [Data Retention & Privacy](/docs/concepts/data-retention-and-privacy) and our [DPA](https://tryiton.now/legal/dpa). - [ ] Live try-on shows an "AI-modified video" label and asks for camera consent. See the [Camera & Privacy Guide](/docs/guides/live-tryon-camera-privacy). ## Live try-on [#live-try-on] - [ ] Garments are prepared ahead of time, for example at catalog sync, not when a shopper clicks. - [ ] You start sessions with `end_user_id` and `allowed_origin`, and end them when the shopper leaves. - [ ] Your Content Security Policy allows what `tryiton-live` needs. See the [Live Try-On Quickstart](/docs/guides/live-tryon-quickstart). ## Monitoring [#monitoring] - [ ] An uptime check calls `GET https://tryiton.now/api/v1/health`. It needs no key. - [ ] You alert on a rising share of failed jobs or 429s. - [ ] Someone follows the [Changelog](/docs/resources/changelog). # Virtual Try-On API Quickstart (/docs/getting-started/quickstart) This page takes you from a new account to your first result image. You create an API key, add credits, install an SDK, then submit a clothing try-on and wait for the result. ## Make your first virtual try-on API call [#make-your-first-virtual-try-on-api-call] ### Create an API key [#create-an-api-key] 1. Sign in at [tryiton.now](https://tryiton.now) and open **Developer API → API Keys** at [tryiton.now/app/developer](https://tryiton.now/app/developer). 2. Under **API Keys** (not **Site Keys**, which are for the storefront widget), click **+ Create new API Key**. 3. Enter a name (up to 50 characters) and click **Create Key**. 4. Copy the key. It is shown only once. Then click **I've saved my key**. More on keys and rotation: [Authentication](/docs/concepts/authentication). Store the key in an environment variable. Every sample on this page reads `TRYITON_API_KEY`: ```bash export TRYITON_API_KEY="YOUR_API_KEY" ``` Call the API from your server only. The try-on endpoints are CORS-locked to TryItOn's own sites, and anyone who has your key can spend your credits. Never ship the key to a browser or a mobile app. See [Authentication & API Keys](/docs/concepts/authentication). ### Get credits [#get-credits] Buy a credit pack or a plan at [tryiton.now/app/billing](https://tryiton.now/app/billing). A clothing, hairstyle or tattoo try-on costs 1 credit per output image, and a job that fails is free. One balance covers the API, the TryItOn app, the browser extension, the mobile app and the storefront widget. See [Virtual Try-On API Pricing & Credits](/docs/concepts/credits-and-pricing). ### Install an SDK [#install-an-sdk] ```bash npm install tryiton ``` Requires Node.js 18 or later. ```bash pip install tryiton ``` Requires Python 3.8 or later. ```bash go get github.com/tryiton-now/tryiton-go/v2 ``` Requires Go 1.20 or later. ```bash composer require tryiton/tryiton ``` Requires PHP 7.4 or later with the `curl` and `json` extensions. ```bash gem install tryiton ``` Requires Ruby 2.6 or later. Nothing to install. The sample uses `curl` and `sed` in a POSIX shell (macOS, Linux, WSL or Git Bash). ### Run a clothing try-on and wait for the result [#run-a-clothing-try-on-and-wait-for-the-result] The sample submits a T-shirt try-on, polls the job until it finishes, and prints the result image URL. Replace the two image URLs with public images of your own: a photo of one person, front-facing and well lit, and a product photo of the garment on a plain background. A base64 data URL (`data:image/jpeg;base64,...`) works too. ```js title="tryon.mjs" import { TryItOn } from "tryiton"; const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY }); const jobId = await client.tryOnFashion({ modelImage: "https://example.com/model.jpg", garmentImage: "https://example.com/tshirt.jpg", category: "clothing", subcategory: "tops", }); console.log("Job:", jobId); const [resultUrl] = await client.waitForResult(jobId, { timeoutMs: 240_000 }); console.log("Result:", resultUrl); ``` The sample uses `import` and top-level `await`, so run it as an ES module: save it as `.mjs` (`node tryon.mjs`) or set `"type": "module"` in your `package.json`. ```python title="tryon.py" import os from tryiton import TryItOn client = TryItOn(api_key=os.environ["TRYITON_API_KEY"]) job_id = client.try_on_fashion( model_image="https://example.com/model.jpg", garment_image="https://example.com/tshirt.jpg", category="clothing", subcategory="tops", ) print("Job:", job_id) urls = client.wait_for_result(job_id, timeout=240) print("Result:", urls[0]) ``` ```go title="main.go" package main import ( "context" "fmt" "log" "os" "time" tryiton "github.com/tryiton-now/tryiton-go/v2" ) func main() { client, err := tryiton.New(os.Getenv("TRYITON_API_KEY")) if err != nil { log.Fatal(err) } // WaitForResult has no timeout of its own: the context sets it. ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute) defer cancel() jobID, err := client.TryOnFashion(ctx, tryiton.FashionParams{ ModelImage: "https://example.com/model.jpg", GarmentImage: "https://example.com/tshirt.jpg", Category: "clothing", Subcategory: "tops", }) if err != nil { log.Fatal(err) } fmt.Println("Job:", jobID) urls, err := client.WaitForResult(ctx, jobID, 2*time.Second) if err != nil { log.Fatal(err) } fmt.Println("Result:", urls[0]) } ``` ```php title="tryon.php" tryOnFashion([ 'model_image' => 'https://example.com/model.jpg', 'garment_image' => 'https://example.com/tshirt.jpg', 'category' => 'clothing', 'subcategory' => 'tops', ]); echo "Job: {$jobId}\n"; // Poll every 2 seconds, give up after 240. $urls = $client->waitForResult($jobId, 2.0, 240.0); echo "Result: {$urls[0]}\n"; ``` ```ruby title="tryon.rb" require "tryiton" client = Tryiton::Client.new(api_key: ENV["TRYITON_API_KEY"]) job_id = client.try_on_fashion( model_image: "https://example.com/model.jpg", garment_image: "https://example.com/tshirt.jpg", category: "clothing", subcategory: "tops" ) puts "Job: #{job_id}" urls = client.wait_for_result(job_id, timeout: 240) puts "Result: #{urls.first}" ``` ```bash title="tryon.sh" # Submit the job and keep its id. JOB_ID=$(curl -s https://tryiton.now/api/v1/tryon/fashion \ -H "Authorization: Bearer $TRYITON_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model_image": "https://example.com/model.jpg", "garment_image": "https://example.com/tshirt.jpg", "category": "clothing", "subcategory": "tops" }' | sed -E 's/.*"jobId":"([^"]+)".*/\1/') echo "Job: $JOB_ID" # Poll every 2 seconds until the job is no longer processing. while true; do STATUS=$(curl -s "https://tryiton.now/api/v1/status/$JOB_ID" \ -H "Authorization: Bearer $TRYITON_API_KEY") case "$STATUS" in *'"status":"processing"'*) sleep 2 ;; *) echo "$STATUS"; break ;; esac done ``` The submit returns `201` with `{"ok":true,"jobId":"..."}`. The last status response looks like this: ```json title="Final status response" { "ok": true, "status": "completed", "output": ["https://cdn.tryiton.now/USER_ID/tryons/3f2c9a.png"], "error": null } ``` Every SDK sample prints something like this: ```text title="Output" Job: 64b7f1a9d9a3b8e5c7f9a123 Result: https://cdn.tryiton.now/USER_ID/tryons/3f2c9a.png ``` Most jobs finish in under a minute. The samples wait up to 4 minutes: a job still running after 3 is failed, so by then every job has a final status. A failed job raises the SDK's error with the reason, or returns `"status": "failed"` with cURL. Failed jobs are free. ### Save the result [#save-the-result] Each URL in `output` is a PNG (or JPEG with `output_format: "jpeg"`) on TryItOn's CDN. Results are deleted about 72 hours after you submitted the job, so download the images you want to keep. ## Next steps [#next-steps] - Try [Hairstyle](/docs/api-reference/hairstyle-tryon) and [Tattoo](/docs/api-reference/tattoo-tryon), or see every category on [Clothing & Accessories](/docs/api-reference/fashion-tryon). - Get better results with the [Image Guidelines](/docs/guides/image-guidelines). - Skip polling: get results pushed to your server with [Webhooks](/docs/guides/webhooks). - Add real-time webcam try-on with the [Live Try-On Quickstart](/docs/guides/live-tryon-quickstart). - Before you launch, run through the [Go-Live Checklist](/docs/getting-started/go-live-checklist). # Embed the Try-On Widget on Your Storefront (/docs/guides/embed-widget) The storefront widget is a ready-made try-on window you put on a product page in an ` ``` | Parameter | Meaning | |---|---| | `site_key` | Your site key. Required. | | `garment_image` | URL of the product image to try on. URL-encode it. | | `category`, `subcategory` | Optional hints for what the garment is. | | `product_id`, `product_title` | Your own product reference, used for analytics. | | `visitor_id` | An anonymous id you generate per shopper, used for per-shopper limits and analytics. | The widget posts messages to the parent page so you can react to it: | Message `type` | Sent when | |---|---| | `tryiton:add-to-cart` | The shopper taps add to cart. | | `tryiton:busy` | A try-on starts or ends (`busy: true` or `false`). | | `tryiton:live` | The live camera opens or closes (`active: true` or `false`). | ## Hide TryItOn branding [#hide-tryiton-branding] By default the widget shows the TryItOn logo. To hide it, edit the key in **Site Keys**, turn on **Hide TryItOn branding** and save. The change reaches the widget right away. - **It needs a paid plan that includes it.** Credit packs alone don't qualify. If your plan doesn't include it, the dashboard shows an error and the key stays branded. - **It follows your plan.** If the subscription ends or moves to a plan without it, branding comes back on its own. Nothing on your site needs to change. - **It is set per key**, so you can hide branding on one site and keep it on another. Hiding branding removes the TryItOn logo and name, not the AI disclosure. Result images keep a plain "AI-generated" label, and shared or downloaded copies are always stamped. The EU AI Act requires that disclosure, so it can't be turned off. Shopify stores set this per store in the TryItOn Shopify app, not through site keys. ## Live camera [#live-camera] The widget's **live camera** is currently available to Shopify merchants only, through the TryItOn Shopify app. On other sites the widget offers photo try-on. For a live camera on your own storefront, build it with the [Live Try-On API](/docs/api-reference/live-tryon) and the [Live Try-On Quickstart](/docs/guides/live-tryon-quickstart). You design the interface, so there is no TryItOn branding to hide, and you show your own [AI disclosure](/docs/guides/live-tryon-quickstart#show-the-ai-disclosure). ## Billing and limits [#billing-and-limits] Widget try-ons spend credits from the account that owns the site key, at the same price as the API, and count toward the same per-account photo try-on rate limit. See [Credits & Pricing](/docs/concepts/credits-and-pricing) and [Rate Limits](/docs/concepts/rate-limits). Shared result copies are kept for 30 days; see [Data Retention & Privacy](/docs/concepts/data-retention-and-privacy). ## Related [#related] - [Authentication & API Keys](/docs/concepts/authentication) - [Live Try-On Quickstart](/docs/guides/live-tryon-quickstart) - [Credits & Pricing](/docs/concepts/credits-and-pricing) # Image Guidelines for Best Try-On Results (/docs/guides/image-guidelines) The input photos decide most of the result quality. This guide covers what the API accepts, how to pick photos for each try-on model, and the usual reasons a job fails or looks wrong. ## Accepted inputs [#accepted-inputs] Every image parameter (`model_image`, `garment_image`, `face_image`, `body_image`, `design_image`, and the live `garment_image`) takes one of two forms: | Form | Example | Limits | |---|---|---| | Public image URL | `https://example.com/photos/model.jpg` | `http` or `https` only. Fetched by TryItOn's servers: up to 25 MB, 15-second timeout, up to 5 redirects. Private and internal network addresses are refused. | | Base64 data URL | `data:image/jpeg;base64,/9j/4AAQ...` | Must start with `data:image/;base64,`. The whole JSON body must stay under 12 MB, which leaves room for about 9 MB of image once encoded. | Prefer URLs for large images. A body over 12 MB is rejected with `413 PayloadTooLarge`. A URL must point at the image file itself, not at an HTML page that shows it. It must also **stay reachable until the job finishes**, which can take up to 3 minutes. If you use signed URLs, give them at least that long, plus margin. ## Tips for each try-on model [#tips-for-each-try-on-model] **Clothing and accessories** - **Person (`model_image`):** one person, facing the camera, well lit. Show the whole body, or at least the region the item goes on: the torso for a top, the feet for shoes, the face for eyewear. - **Item (`garment_image`):** a product photo on a plain background, or a flat lay, with the item on its own. - **Category:** leave it out (or send `auto`) and the item type is detected for you. Send `category` and `subcategory` when you know them. See the [fashion try-on reference](/docs/api-reference/fashion-tryon). **Hairstyle** - **Face (`face_image`):** a clear, front-facing photo of the face, well lit. **Tattoo** - **Body (`body_image`):** a close-up of bare skin where the tattoo goes, evenly lit. - **Design (`design_image`):** the design alone. A transparent or white background is dropped, so only the design lands on the skin. - **Position:** use `placement` to describe where and how big, or `region` to mark the exact spot. See the [tattoo try-on reference](/docs/api-reference/tattoo-tryon). **Live try-on** - **Garment:** a product photo on a plain background. Send `category` when you prepare it, so it doesn't have to be detected. See [live garments](/docs/api-reference/live-garments). ## Common causes of failed jobs [#common-causes-of-failed-jobs] A photo try-on submit only checks that each required image is present. Fetching and decoding happen inside the job, so most image problems don't return `400`: the job is accepted and later ends with `status: "failed"` and a reason in `error`. Failed jobs cost nothing. | Symptom | Likely cause | Fix | |---|---|---| | Job `failed` | URL is private, needs a login or cookie, has expired, or returns a 404 | Use a public URL that works in a private browser window, or send base64. | | Job `failed` | Image over 25 MB, or the host took longer than 15 seconds | Resize the image or host it somewhere faster. | | Job `failed` | URL points at `localhost`, a private IP or an internal hostname | Use a public host. Internal addresses are always refused. | | Job `failed` | Malformed base64 (no `data:image/...;base64,` prefix, or truncated data) | Send the full data URL with its prefix. | | Job `failed` with `"Timed out."` | The job ran over 3 minutes | Resubmit. If it keeps happening with the same inputs, try different photos. | | `413 PayloadTooLarge` | JSON body over 12 MB | Send the image as a URL. | | `400 ImageLoadError` | A required image parameter is missing or empty | Check the parameter name for the endpoint you're calling. | The safety filters of our AI sub-processors always apply. If a job completes but the result looks wrong, check the photos against the tips above. A cluttered item photo, several people in the frame, or a crop that hides where the item goes are the usual problems. ## Related [#related] - [Clothing & Accessories Try-On API](/docs/api-reference/fashion-tryon) - [Tattoo Try-On API](/docs/api-reference/tattoo-tryon) - [Error Codes & Handling](/docs/concepts/errors) - [Data Retention & Privacy](/docs/concepts/data-retention-and-privacy) # Live Try-On Camera & Privacy Guide (/docs/guides/live-tryon-camera-privacy) Live try-on turns on the shopper's camera and shows them an AI-edited video of themselves. Shoppers will want to know what happens to that video, and the law in many places says you have to tell them. This guide splits the work into what TryItOn and [`tryiton-live`](https://www.npmjs.com/package/tryiton-live) do for you, and what your site has to do itself. It ends with sample wording you can adapt. This guide is not legal advice. The rules depend on where you and your shoppers are. Have your own lawyer or privacy team review your notice, consent flow and privacy policy before you launch. ## Who handles what [#who-handles-what] | Topic | TryItOn and `tryiton-live` | Your site | | ----- | -------------------------- | --------- | | Opening the camera | Asks the browser for the camera and reports `camera_denied` or `camera_unavailable` | Tells the shopper why before the browser asks | | The live video | Streams it from the device to the media network. TryItOn never stores it | Mentions it in your privacy policy | | Recording or downloads | Not part of the API. Nothing is recorded | Asks for consent and decides what happens to the files | | AI label | Shows an "AI-modified video" label when you pass `disclosure` | Turns it on, or shows its own label | | Prepared garments | Stores them on your account | Nothing extra: they are your product photos | | Laws in your markets | Gives you the facts on this page | Checks GDPR, US state biometric laws and others | ## What TryItOn and tryiton-live handle [#what-tryiton-and-tryiton-live-handle] ### The camera [#the-camera] `openCamera()` asks the browser for the front camera. If the shopper says no, it rejects with a `TryItOnLiveError` whose `code` is `camera_denied`. If the browser has no camera support, the page isn't on HTTPS or the camera can't be opened, the `code` is `camera_unavailable`. Show the shopper a short message and a way back, for example: ```js import { openCamera, TryItOnLiveError } from "tryiton-live"; try { const camera = await openCamera(); // ... start the session and connect } catch (err) { if (err instanceof TryItOnLiveError && err.code === "camera_denied") showMessage("Live try-on needs your camera. You can allow it in your browser settings."); else if (err instanceof TryItOnLiveError && err.code === "camera_unavailable") showMessage("We couldn't open a camera on this device. Try another browser or device."); else throw err; } ``` Open the camera before your server starts the session, as in the [quickstart](/docs/guides/live-tryon-quickstart#stream-in-the-browser). A camera that `tryiton-live` opens for itself is turned off when the session ends. A camera you open with `openCamera()` and pass in is yours to turn off: stop its tracks in `onEnd`. ### The video [#the-video] > Diagram: Live try-on architecture. Your server keeps the API key and uses it to prepare garments and start sessions on the TryItOn API. It passes the start response, which holds no API key, to the shopper’s browser. In the browser, tryiton-live opens the camera and streams the video over WebRTC to the media network, which returns the try-on video. The video never passes through TryItOn. The browser sends heartbeats, garment switches, failover and end to the TryItOn API with the session secret. - **It goes from the device to the media network and back.** The camera video streams over WebRTC to a third-party media network, which edits it in real time and returns it. It never passes through TryItOn's servers. - **TryItOn never stores it.** There's no copy on TryItOn's side to delete or hand over. - **Who processes it.** The media network runs on TryItOn's sub-processors, listed in [Annex 3 of the DPA](https://tryiton.now/legal/dpa#annex-3-subprocessors). A session may move to a [backup stream](/docs/api-reference/live-sessions#backup-stream) when the primary one fails to connect. - **`tryiton-live` doesn't record anything.** It shows the stream and sends billing heartbeats. It doesn't save frames or upload images. - **It stops when the shopper leaves.** A closed page ends the session, and so does a hidden one unless you set `endWhenHidden: false`. ### What TryItOn stores [#what-tryiton-stores] - **Prepared garments:** a normalized copy of each garment image, with its category, description and prompt. They are kept until your account is deleted, or until nobody has used them for 90 days. - **Session records:** duration, credits, end reason, the API key that started the session, and the `end_user_id` you sent. No video and no images of the shopper. `end_user_id` is your own id for the shopper. Use an opaque id, like a random string or a hash of your customer number, rather than an email address or a name. Details are in [Data Retention & Privacy](/docs/concepts/data-retention-and-privacy). ## What your site handles [#what-your-site-handles] ### Tell shoppers before the camera turns on [#tell-shoppers-before-the-camera-turns-on] The browser's permission prompt only says that your site wants the camera. Before you call `openCamera()`, show your own short notice that says: - what the camera is used for (seeing the item on themselves, live), - that the video is processed in real time by a third-party media network and that it is AI-modified, - whether anything is saved, and - where to read more (a link to your privacy policy). Let the shopper turn the camera on from that notice, with a clear way to say no. A shopper who says no should still be able to shop. ### Ask before you record or save [#ask-before-you-record-or-save] Recording, screenshots and downloads are **not** part of the TryItOn API. If you build them yourself, for example by recording the stream with `MediaRecorder` or letting shoppers save a still, that feature and its files are yours. Before you record or save anything: - ask the shopper first, every time or with a clear setting they can change, - say where the file goes (only their device, or your servers) and for how long, - say who can see it, and - let them delete it. If you upload saved files to your servers, they are personal data you hold. Your own retention and deletion rules apply to them, not TryItOn's. ### Update your privacy policy [#update-your-privacy-policy] Add a section on live try-on. It should say that you use the camera with permission, that the live video is processed in real time by a third-party media network through TryItOn, that TryItOn doesn't store it, and what you save yourself. If your policy lists service providers or sub-processors, add TryItOn and point to TryItOn's [sub-processor list](https://tryiton.now/legal/dpa#annex-3-subprocessors). For more details for your records, email [contact@tryiton.now](mailto:contact@tryiton.now). ### Show the AI label [#show-the-ai-label] Under the EU AI Act (Article 50), a site that shows AI-altered video of a real person has to say so. That duty sits with the site that shows the video, which is yours. Pass `disclosure` to `connectLiveTryOn` and `tryiton-live` shows an "AI-modified video" label while the video is live (see [Show the AI disclosure](/docs/guides/live-tryon-quickstart#show-the-ai-disclosure)), or show your own label that stays visible on the video while it plays. ### Check the laws where you sell [#check-the-laws-where-you-sell] Camera video of a person is personal data in many places. Some laws need more than a notice: - **GDPR and similar laws** (EU, UK and others) need a legal basis for using the camera, such as consent, and clear information up front. Saved recordings add retention and deletion duties. - **US state biometric laws**, such as Illinois' BIPA, cover scans of face or body geometry. Some need written consent before any collection, and they have been used in lawsuits over virtual try-on tools. - **Other places** have their own rules for camera data, minors and AI content. Whether a law applies depends on your setup, your shoppers and how you use the video. Get your own legal review. ## Sample wording [#sample-wording] Adapt these to your shop, your languages and your own legal advice. Text in brackets is for you to fill in or pick. ### Camera notice [#camera-notice] Show this before the browser asks for the camera: > **Try it on live** > > We'll use your camera to show you wearing this item, live. Your video is processed in real time by our try-on > provider to create an AI-modified preview. We don't save it. [Read our privacy policy.] > > [Turn on camera] [Not now] If you do save anything, replace "We don't save it" with what you save and for how long. ### Recording consent [#recording-consent] Show this before you record or save a video or photo: > Save this try-on? We'll keep the [video / photo] [on your device only / in your account for 30 days] so you can > [watch it again / share it]. You can delete it at any time. [Save] [Cancel] ### Privacy policy paragraph [#privacy-policy-paragraph] > **Live virtual try-on.** When you use live try-on, we turn on your device's camera only after you allow it. Your > camera video is streamed in real time to a media provider used by our try-on service, TryItOn, which creates an > AI-modified preview of you wearing the selected item. The video is processed only while you use live try-on and > is not stored by TryItOn. [We don't record or save your video. / If you choose to save a try-on, we keep it > [where] for [how long], and you can delete it at any time.] We keep basic usage records, such as when a session > started and how long it lasted, for billing and support. The preview is AI-generated and may not show exactly how > an item will look or fit. ## Related [#related] - [Real-Time Virtual Try-On Quickstart](/docs/guides/live-tryon-quickstart): camera, session and `tryiton-live`, step by step. - [Live Virtual Try-On API](/docs/api-reference/live-tryon): how live try-on works, and its endpoints. - [Data Retention & Privacy](/docs/concepts/data-retention-and-privacy): everything the API stores, and for how long. # Real-Time Virtual Try-On Quickstart (/docs/guides/live-tryon-quickstart) This guide adds live virtual try-on from the shopper's webcam to a web page. It has two pieces: 1. **Your server** keeps the API key. It prepares garments and starts a session for each shopper, with an [official SDK](/docs/sdks) or the [REST endpoints](/docs/api-reference/live-tryon). 2. **The shopper's browser** streams with [`tryiton-live`](https://www.npmjs.com/package/tryiton-live). It only sees the session's start response, never your key. > Diagram: Live try-on architecture. Your server keeps the API key and uses it to prepare garments and start sessions on the TryItOn API. It passes the start response, which holds no API key, to the shopper’s browser. In the browser, tryiton-live opens the camera and streams the video over WebRTC to the media network, which returns the try-on video. The video never passes through TryItOn. The browser sends heartbeats, garment switches, failover and end to the TryItOn API with the session secret. You need an [API key](/docs/concepts/authentication) and at least `minCredits` usable credits (4 by default). The Node.js samples are ES modules: use `"type": "module"` in `package.json` or a `.mjs` file. *** #### Prepare your garments [#prepare-your-garments] Prepare each product once, for example when you sync your catalog, and store the returned `id` with the product. Pass the `category` if you know it. See [Live Garments & Outfits](/docs/api-reference/live-garments) for every option. ```js import { TryItOn } from "tryiton"; const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY }); const garment = await client.prepareLiveGarment({ garmentImage: "https://example.com/products/shirt.jpg", category: "clothing", subcategory: "tops", }); console.log(garment.id); // store it with the product ``` ```python import os from tryiton import TryItOn client = TryItOn(api_key=os.environ["TRYITON_API_KEY"]) garment = client.prepare_live_garment( garment_image="https://example.com/products/shirt.jpg", category="clothing", subcategory="tops", ) print(garment["id"]) # store it with the product ``` ```go package main import ( "context" "fmt" "log" "os" "github.com/tryiton-now/tryiton-go/v2" ) func main() { client, err := tryiton.New(os.Getenv("TRYITON_API_KEY")) if err != nil { log.Fatal(err) } garment, err := client.PrepareLiveGarment(context.Background(), tryiton.PrepareLiveGarmentParams{ GarmentImage: "https://example.com/products/shirt.jpg", Category: "clothing", Subcategory: "tops", }) if err != nil { log.Fatal(err) } fmt.Println(garment.ID) // store it with the product } ``` ```php prepareLiveGarment([ 'garment_image' => 'https://example.com/products/shirt.jpg', 'category' => 'clothing', 'subcategory' => 'tops', ]); echo $garment['id'], PHP_EOL; // store it with the product ``` ```ruby require "tryiton" client = Tryiton::Client.new(api_key: ENV.fetch("TRYITON_API_KEY")) garment = client.prepare_live_garment( garment_image: "https://example.com/products/shirt.jpg", category: "clothing", subcategory: "tops" ) puts garment["id"] # store it with the product ``` ```bash curl -X POST https://tryiton.now/api/v1/live/garments \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "garment_image": "https://example.com/products/shirt.jpg", "category": "clothing", "subcategory": "tops" }' ``` #### Start a session on your server [#start-a-session-on-your-server] Add an endpoint your page can call, here `POST /live-session` with a JSON body `{ "garmentId": "..." }`. It starts a session and returns the start response **unchanged**. Replace `shopper-42` with your signed-in shopper's id: each shopper then gets one stream, and a reload ends their previous session. See [Start a session](/docs/api-reference/live-sessions#start-a-session) for the other options. ```js import express from "express"; import { TryItOn } from "tryiton"; const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY }); const app = express(); app.use(express.json()); app.post("/live-session", async (req, res) => { try { const start = await client.startLiveSession({ garmentId: req.body.garmentId, endUserId: "shopper-42", // your signed-in shopper's id allowedOrigin: "https://shop.example.com", // locks the media token to your site }); res.json(start); } catch (err) { res.status(err.status ?? 502).json({ error: err.errorName ?? "LiveStartFailed" }); } }); app.listen(3000); ``` ```python import os from flask import Flask, jsonify, request from tryiton import TryItOn, TryItOnError client = TryItOn(api_key=os.environ["TRYITON_API_KEY"]) app = Flask(__name__) @app.post("/live-session") def live_session(): try: start = client.start_live_session( garment_id=request.json["garmentId"], end_user_id="shopper-42", # your signed-in shopper's id allowed_origin="https://shop.example.com", ) except TryItOnError as err: return jsonify(error=err.error_name), err.status or 502 return jsonify(start) ``` ```go package main import ( "encoding/json" "errors" "log" "net/http" "os" "github.com/tryiton-now/tryiton-go/v2" ) func main() { client, err := tryiton.New(os.Getenv("TRYITON_API_KEY")) if err != nil { log.Fatal(err) } http.HandleFunc("/live-session", liveSession(client)) log.Fatal(http.ListenAndServe(":3000", nil)) } func liveSession(client *tryiton.Client) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } var body struct { GarmentID string `json:"garmentId"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } start, err := client.StartLiveSession(r.Context(), tryiton.StartLiveSessionParams{ GarmentID: body.GarmentID, EndUserID: "shopper-42", // your signed-in shopper's id AllowedOrigin: "https://shop.example.com", }) if err != nil { status := http.StatusBadGateway var apiErr *tryiton.Error if errors.As(err, &apiErr) && apiErr.Status != 0 { status = apiErr.Status } http.Error(w, err.Error(), status) return } // Marshals back to the same JSON the API returned, which the browser passes to connectLiveTryOn. w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(start); err != nil { log.Println(err) } } } ``` ```php startLiveSession([ 'garment_id' => $body['garmentId'] ?? null, 'end_user_id' => 'shopper-42', // your signed-in shopper's id 'allowed_origin' => 'https://shop.example.com', ]); echo json_encode($start); } catch (TryItOnException $e) { http_response_code($e->status ?? 502); echo json_encode(['error' => $e->errorName]); } ``` ```ruby require "json" require "sinatra" require "tryiton" TRYITON = Tryiton::Client.new(api_key: ENV.fetch("TRYITON_API_KEY")) post "/live-session" do content_type :json payload = JSON.parse(request.body.read) begin start = TRYITON.start_live_session( garment_id: payload["garmentId"], end_user_id: "shopper-42", # your signed-in shopper's id allowed_origin: "https://shop.example.com" ) start.to_json rescue Tryiton::Error => e halt (e.status || 502), { error: e.error_name }.to_json end end ``` #### Stream in the browser [#stream-in-the-browser] ```bash npm install tryiton-live ``` ```html
``` A session holds a credit from the moment it starts. Open the camera before you ask your server for a session, so a shopper who blocks the camera never starts one. ```js import { attachStream, connectLiveTryOn, openCamera } from "tryiton-live"; const garmentId = "6b0827eba2f220ae7dd7c7fb"; // from step 1 const otherGarmentId = "6b0827eba2f220ae7dd7c7fc"; // another prepared garment // 1. Camera first: the session holds a credit from the moment it starts. const camera = await openCamera(); // 2. Ask your server for a session. const start = await fetch("/live-session", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ garmentId }), }).then((r) => r.json()); // 3. Stream. const live = await connectLiveTryOn(start, { camera, onStream: (stream) => attachStream(document.getElementById("tryon"), stream), // plays it, iOS included disclosure: document.getElementById("tryon-stage"), // "AI-modified video" label while live onSecondsLeft: (s) => console.log(`${s}s left`), onEnd: ({ reason, session }) => { camera.getTracks().forEach((t) => t.stop()); console.log("ended:", reason, session?.creditsCharged, "credits"); }, }); // Swap garments on the running stream (no reconnect, free): await live.switchGarment(otherGarmentId); // Done: await live.end(); ``` **Billing runs until the session ends.** Call `live.end()` when the shopper is done. Switching garments on a running stream is free and doesn't reconnect. See [Live Try-On Billing](/docs/concepts/live-tryon-billing). `connectLiveTryOn` resolves once the first try-on frame arrives, usually within a few seconds. If no video arrives within 20 seconds (`connectTimeoutMs`), it rejects with a `TryItOnLiveError` and ends the session, which is normally [refunded](/docs/concepts/live-tryon-billing#when-a-session-fails). The error's `code` is one of `camera_denied`, `camera_unavailable`, `garment_required`, `busy`, `connect_failed`, `heartbeat_failed` or `http_error`. When the page closes, `tryiton-live` ends the session for you. If the primary stream fails to connect, the session switches to the [backup stream](/docs/api-reference/live-sessions#backup-stream) by itself and keeps connecting (for up to 30 seconds). Pass `onFailover` to log it.
*** #### Show the AI disclosure [#show-the-ai-disclosure] Under the EU AI Act (Article 50), the shopper has to be told the try-on video is AI-modified, and that's the job of the site that shows it. The `disclosure` option above does it: `tryiton-live` puts a small "AI-modified video" label in a corner of the element you pass while the video is live. Change the text or the corner with an object: ```js connectLiveTryOn(start, { onStream: (stream) => attachStream(video, stream), disclosure: { container: stage, label: "KI-veränderte Vorschau", position: "bottom-right" }, }); ``` To place the label in your own UI, `showAiDisclosure(container, { label, position })` shows it and returns a function that removes it. If you design your own disclosure instead, keep it visible on the video while it plays. The [Live Try-On Camera & Privacy Guide](/docs/guides/live-tryon-camera-privacy) covers the camera notice, consent for recordings and your privacy policy, with sample wording. *** #### iOS Safari [#ios-safari] - **Show the video with `attachStream(video, stream)`.** It sets `muted` and `playsinline` and calls `play()` itself, because iOS ignores `autoplay` in Low Power Mode, and it resumes playback when the page is shown again. - **A hidden page ends the session** (reason `hidden`). iOS pauses the camera and the stream when the shopper switches apps, so start a new session when they come back. `endWhenHidden: false` turns this off. - **Call `openCamera()` before each session.** iOS stops the camera in the background. If you pass a camera whose track has ended, `tryiton-live` opens a fresh one, but your own preview needs a new one too. - **In-app browsers** (Instagram, TikTok, Facebook) often can't open the camera. Check `navigator.mediaDevices?.getUserMedia` and suggest opening the page in Safari if it's missing. *** #### Whole outfits and swapping one item [#whole-outfits-and-swapping-one-item] To show a top, trousers and shoes at once, combine prepared garments into an [outfit](/docs/api-reference/live-garments#prepare-an-outfit) on your server. Its `id` works anywhere a garment id does. To swap one item, prepare the new combination and switch to it: ```js // Server: once per combination (cached). const outfit = await client.prepareLiveOutfit({ garmentIds: [topId, trousersId, shoesId] }); // Browser: on the running stream. await live.switchGarment(outfit.id); ``` To control what the stream does, say "replace only the shoes and keep the outfit", use [custom instructions](/docs/api-reference/live-garments#custom-instructions). *** #### Billing [#billing] Each credit buys `secondsPerCredit` seconds of video (3 by default), counted from the first try-on frame. See [Live Try-On Billing](/docs/concepts/live-tryon-billing). #### Bundlers [#bundlers] On Chromium, `tryiton-live` sends each outgoing video frame through a Web Worker file, `frame-metadata-worker.js`. Vite, webpack 5 and Next.js emit it for you. With esbuild, Bun or a plain script tag, copy it next to your bundle: ```bash node node_modules/tryiton-live/scripts/copy-media-worker.mjs ``` Without the worker, the camera connects but no video is sent, and `connectLiveTryOn` rejects with `connect_failed` (unbilled). #### Content security policy [#content-security-policy] If your page sets a Content Security Policy, allow the TryItOn API, the script the backup stream loads from TryItOn, and the backup stream's hosts. These are the ones it used in our tests: ```text title="Content-Security-Policy" script-src https://tryiton.now connect-src https://tryiton.now https://*.aliyuncs.com wss://*.aliyuncs.com https://*.alicdn.com https://*.alivecdn.com https://time.akamai.com ``` The video itself goes over WebRTC, which CSP doesn't cover. **Debugging:** pass `{ debug: true }` to `connectLiveTryOn` to log connection states and media diagnostics to the console, prefixed `[tryiton-live]`. ## Related [#related] - [Live Virtual Try-On API](/docs/api-reference/live-tryon): how it works, end reasons and limits. - [Live Sessions](/docs/api-reference/live-sessions): every start option, and the backup stream. - [Live Try-On Browser Endpoints](/docs/api-reference/live-tryon-browser-endpoints): for building your own client. - [Live Try-On Camera & Privacy Guide](/docs/guides/live-tryon-camera-privacy): what to tell shoppers before the camera turns on, with sample wording. - [Virtual Try-On SDKs](/docs/sdks): install the server SDK for your language. # Webhooks: Get Try-On Results Pushed (/docs/guides/webhooks) Instead of polling, you can have us POST an event to your server when a photo try-on job finishes. Every event is signed, so your server can check that it came from TryItOn and wasn't changed on the way. - Events are sent for photo try-ons made with an **API key**: `tryon.completed` and `tryon.failed`. Each job sends exactly one of them. - Storefront widget jobs and live sessions don't send events. - Polling keeps working. A webhook only saves you the loop. See [Jobs & Polling](/docs/concepts/jobs-and-polling). ## Set up an endpoint [#set-up-an-endpoint] **Add a route to your server** that accepts `POST` requests with a JSON body. It must use HTTPS on a public host. The code is under [Verify the signature](#verify-the-signature). **Add the URL in the dashboard.** Open [Developer API → API Keys](https://tryiton.now/app/developer), enter the URL under **Webhook** and press **Add endpoint**. Copy the signing secret it shows (it starts with `whsec_`) into your server's environment, for example as `TRYITON_WEBHOOK_SECRET`. You can reveal it again later. **Send a test event.** Press **Send test event**. The deliveries table shows how your endpoint answered. Every attempt we make is listed there for 30 days. One endpoint per account. **Send events** pauses delivery without losing your settings. ## Events [#events] | `type` | Sent when | |---|---| | `tryon.completed` | A job completed. `data.output` has the result image URLs. | | `tryon.failed` | A job failed, including one that [timed out](/docs/concepts/jobs-and-polling#polling) after 3 minutes. It isn't charged. | | `webhook.test` | You pressed **Send test event**. `data` holds only a `message`. | `data` is what [`GET /status/{id}`](/docs/api-reference/job-status) returns for the job, plus its `jobId`: ```json title="tryon.completed" { "id": "evt_5f0c8a1e2b3d4c5e6f708192", "type": "tryon.completed", "created_at": "2026-12-04T10:15:30.120Z", "data": { "jobId": "64b7f1a9d9a3b8e5c7f9a123", "status": "completed", "output": ["https://cdn.tryiton.now/USER_ID/tryons/3f2c9a.png"], "error": null } } ``` Every field is on [Webhook Events](/docs/api-reference/webhook-events). Handle unknown `type` values by answering `200` and ignoring them: we may add events later. ## Verify the signature [#verify-the-signature] We sign with the open [Standard Webhooks](https://www.standardwebhooks.com) scheme, so its libraries work too. Each request carries three headers: | Header | Value | |---|---| | `webhook-id` | The event `id`. The same on every retry. | | `webhook-timestamp` | When this attempt was sent, in Unix seconds. | | `webhook-signature` | One or more `v1,` entries, separated by spaces. | From 2.5, each SDK has a helper that does all of this and returns the event: `verifyWebhook` in Node.js, `verify_webhook` in Python and Ruby, `VerifyWebhook` in Go and `Webhook::verify` in PHP. See [Verify webhooks](/docs/sdks#verify-webhooks). The code below is for servers without an SDK. To check a request: 1. Read the **raw** body as it arrived. Parsing the JSON and serializing it again changes the bytes. 2. Reject the request when `webhook-timestamp` is more than 5 minutes from your clock. This stops replays. 3. Compute HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{raw body}`. The key is your secret without the `whsec_` prefix, base64-decoded. 4. Base64-encode the result. Accept the request when it matches any `v1,` entry. Compare in constant time. ```js title="Express" import crypto from "node:crypto"; import express from "express"; const secret = Buffer.from(process.env.TRYITON_WEBHOOK_SECRET.replace(/^whsec_/, ""), "base64"); function isValidSignature(headers, rawBody) { const id = headers["webhook-id"]; const timestamp = Number(headers["webhook-timestamp"]); if (!id || !Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > 300) return false; const expected = crypto.createHmac("sha256", secret).update(`${id}.${timestamp}.${rawBody}`).digest(); return String(headers["webhook-signature"] || "") .split(" ") .some((entry) => { const [version, signature = ""] = entry.split(","); const given = Buffer.from(signature, "base64"); return version === "v1" && given.length === expected.length && crypto.timingSafeEqual(given, expected); }); } const app = express(); // express.raw keeps the exact bytes that were signed. app.post("/webhooks/tryiton", express.raw({ type: "application/json" }), (req, res) => { const rawBody = req.body.toString("utf8"); if (!isValidSignature(req.headers, rawBody)) return res.sendStatus(400); const event = JSON.parse(rawBody); res.sendStatus(200); // Handle event.type and event.data here, or queue them. }); app.listen(3000); ``` ```python title="Flask" import base64, hashlib, hmac, os, re, time from flask import Flask, request SECRET = base64.b64decode(os.environ["TRYITON_WEBHOOK_SECRET"].removeprefix("whsec_")) app = Flask(__name__) def is_valid_signature(headers, raw_body: bytes) -> bool: msg_id = headers.get("webhook-id", "") timestamp = headers.get("webhook-timestamp", "") if not msg_id or not re.fullmatch(r"[0-9]+", timestamp) or abs(time.time() - int(timestamp)) > 300: return False signed = f"{msg_id}.{timestamp}.".encode() + raw_body expected = base64.b64encode(hmac.new(SECRET, signed, hashlib.sha256).digest()).decode() return any( entry.startswith("v1,") and hmac.compare_digest(entry[3:].encode(), expected.encode()) for entry in headers.get("webhook-signature", "").split(" ") ) @app.post("/webhooks/tryiton") def tryiton_webhook(): raw_body = request.get_data() if not is_valid_signature(request.headers, raw_body): return "", 400 event = request.get_json() # Handle event["type"] and event["data"] here, or queue them. return "", 200 ``` ```go title="net/http (Go 1.22+)" package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "io" "net/http" "os" "strconv" "strings" "time" ) var secret, _ = base64.StdEncoding.DecodeString(strings.TrimPrefix(os.Getenv("TRYITON_WEBHOOK_SECRET"), "whsec_")) func isValidSignature(h http.Header, body []byte) bool { id, ts := h.Get("webhook-id"), h.Get("webhook-timestamp") sent, err := strconv.ParseInt(ts, 10, 64) if age := time.Now().Unix() - sent; id == "" || err != nil || age > 300 || age < -300 { return false } mac := hmac.New(sha256.New, secret) mac.Write([]byte(id + "." + ts + ".")) mac.Write(body) expected := mac.Sum(nil) for _, entry := range strings.Split(h.Get("webhook-signature"), " ") { version, signature, _ := strings.Cut(entry, ",") given, err := base64.StdEncoding.DecodeString(signature) if version == "v1" && err == nil && hmac.Equal(given, expected) { return true } } return false } func main() { http.HandleFunc("POST /webhooks/tryiton", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil || !isValidSignature(r.Header, body) { w.WriteHeader(http.StatusBadRequest) return } var event struct { ID string `json:"id"` Type string `json:"type"` Data json.RawMessage `json:"data"` } if err := json.Unmarshal(body, &event); err != nil { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) // Handle event.Type and event.Data here, or queue them. }) http.ListenAndServe(":8080", nil) } ``` ```php title="webhook.php (PHP 8+)" 300 || !$isSigned) { http_response_code(400); exit; } $event = json_decode($rawBody, true); http_response_code(200); // Handle $event['type'] and $event['data'] here, or queue them. ``` ```ruby title="Sinatra" require "json" require "openssl" require "sinatra" SECRET = ENV.fetch("TRYITON_WEBHOOK_SECRET").delete_prefix("whsec_").unpack1("m") def valid_signature?(id, timestamp, signatures, raw_body) return false if id.to_s.empty? || !timestamp.to_s.match?(/\A\d+\z/) return false if (Time.now.to_i - timestamp.to_i).abs > 300 expected = [OpenSSL::HMAC.digest("SHA256", SECRET, "#{id}.#{timestamp}.#{raw_body}")].pack("m0") signatures.to_s.split(" ").any? do |entry| version, signature = entry.split(",", 2) version == "v1" && Rack::Utils.secure_compare(signature.to_s, expected) end end post "/webhooks/tryiton" do raw_body = request.body.read signed = valid_signature?( request.env["HTTP_WEBHOOK_ID"], request.env["HTTP_WEBHOOK_TIMESTAMP"], request.env["HTTP_WEBHOOK_SIGNATURE"], raw_body ) halt 400 unless signed event = JSON.parse(raw_body) # Handle event["type"] and event["data"] here, or queue them. status 200 end ``` ## Answer fast, handle duplicates [#answer-fast-handle-duplicates] - **Answer with any `2xx` within 10 seconds.** Do slow work, like downloading the images, after you answer or in a queue. Any other status, a redirect, or no answer in time counts as a failed attempt. We don't follow redirects. - **The same event can arrive more than once,** for example when your server answered after our timeout. Store the `webhook-id` of events you handled and skip repeats. - **Events from different jobs can arrive in any order.** Each job sends one final event, so there is nothing to reorder within a job. ## Retries [#retries] A failed attempt is retried on this schedule: | Attempt | After the previous attempt failed | |---|---| | 1 | Sent when the job finishes | | 2 | 10 seconds | | 3 | 1 minute | | 4 | 10 minutes | | 5 | 1 hour | | 6 | 6 hours | After the sixth failure the event is marked failed. Retries stop early when you turn events off or delete the endpoint. Each attempt has a fresh `webhook-timestamp` and signature. You can resend any event from the deliveries table, as long as it's there (30 days). The last retry comes about 7 hours after the job, and result images last 72 hours, so a delayed event still has working URLs. If your endpoint was down longer, fetch missed results with `GET /status/{id}`. Status works for 3 days after a job. ## Rotate the secret [#rotate-the-secret] Rotate when a secret may have leaked, or on your own schedule: 1. Press **Rotate** next to the signing secret. The new secret signs every event from then on. 2. The old secret keeps signing too for 24 hours. During that time `webhook-signature` has one entry per secret, so the code above keeps working with either. Rotate again within those 24 hours and up to three secrets sign at once. Each old one stops 24 hours after its own rotation. 3. Put the new secret in your server's environment and deploy within 24 hours. ## Related [#related] - [Webhook Events](/docs/api-reference/webhook-events): every field of each event - [Jobs & Polling](/docs/concepts/jobs-and-polling) - [Get Job Status](/docs/api-reference/job-status) - [Go-Live Checklist](/docs/getting-started/go-live-checklist) # Virtual Try-On API Documentation (/docs) The TryItOn API puts a garment, accessory, haircut or tattoo onto a photo of a real person, or onto a shopper's live webcam video. Your server sends the images and gets back AI-generated results. ```bash title="Request" curl https://tryiton.now/api/v1/tryon/fashion \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model_image": "https://example.com/model.jpg", "garment_image": "https://example.com/shirt.jpg", "category": "clothing", "subcategory": "tops" }' ``` ```json title="Response: 201 Created" { "ok": true, "jobId": "64b7f1a9d9a3b8e5c7f9a123" } ``` Then poll `GET /status/{jobId}` until the job is done. The status response holds the result image URLs. ## Which product do you need? [#which-product-do-you-need] | You want to show | Use | How it works | | ---------------- | --- | ------------ | | Clothing, shoes, glasses, hats, jewelry or bags on a person | [Clothing & Accessories](/docs/api-reference/fashion-tryon) | Photo in, photo out. Async job. | | A new haircut or hair color | [Hairstyle](/docs/api-reference/hairstyle-tryon) | Photo in, photo out. Async job. | | A tattoo design on skin | [Tattoo](/docs/api-reference/tattoo-tryon) | Photo in, photo out. Async job. | | Clothing on the shopper's live webcam video | [Live Try-On](/docs/api-reference/live-tryon) | Real-time stream in the browser. | | Try-on on your store without writing code | [Storefront Widget](/docs/guides/embed-widget) | Paste an iframe with a site key. | Photo try-ons cost 1 credit per result image. Live try-on is billed by streaming time. One credit balance covers everything. See [Pricing & Credits](/docs/concepts/credits-and-pricing). ## Live try-on [#live-try-on] The shopper sees themselves wearing the garment in real time, and can switch garments without reconnecting. Start with the [Live Try-On Quickstart](/docs/guides/live-tryon-quickstart). ## Built for agents too [#built-for-agents-too] Every page is plain markdown if you add `.md` to its URL. [`/llms.txt`](/llms.txt) indexes the docs, [`/llms-full.txt`](/llms-full.txt) has all of them in one file, and the whole API is one [OpenAPI 3.1 spec](/docs/api-reference/openapi). # Get Credits Balance (/docs/api-reference/credits-balance) Your account has one credit balance. The API, the TryItOn app, the browser extension, the mobile app and the storefront widget all spend from it, so it can change between two of your requests. Buy packs or a plan at [tryiton.now/app/billing](https://tryiton.now/app/billing). ## What you can spend [#what-you-can-spend] `on_demand` **includes** held credits, so it isn't your spendable balance. What you can spend right now is `subscription + purchased − reserved`. That's what the try-on endpoints check before they accept a job. In the example below, `on_demand` is 50 + 100 + 1 = 151, and you can spend 50 + 100 − 1 = **149**. - `reserved` holds credits for running photo try-ons and live sessions. A hold becomes a charge when the work finishes, or is released if it fails. See [Pricing & Credits](/docs/concepts/credits-and-pricing). - Live session holds don't count toward the photo concurrency limit. See [Rate Limits](/docs/concepts/rate-limits). ### GET /credits Get your credit balance Auth: `Authorization: Bearer YOUR_API_KEY`. Responses: - `200`: The account's current balance. ```json { "ok": true, "credits": { "on_demand": 151, "subscription": 50, "purchased": 100, "reserved": 1 } } ``` - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `404`: The API key's account no longer exists. (`error.name`: `NotFound`) - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) ## Health check [#health-check] `GET /health` needs no API key. Point your uptime monitor at it. It counts toward the per-IP limit. ### GET /health Liveness probe Unauthenticated. For uptime monitors. Counts against the per-IP limit. Auth: none. Responses: - `200`: The API is up. ```json { "ok": true } ``` - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) # Clothing & Accessories Try-On API (/docs/api-reference/fashion-tryon) Put a garment or accessory on a person. Send a photo of the person (`model_image`) and an image of the item (`garment_image`). You get a `jobId` back right away. Then poll [Get Job Status](/docs/api-reference/job-status) until the result images are ready. Each output image costs 1 credit. A failed job is free. See [Pricing & Credits](/docs/concepts/credits-and-pricing). ## Categories and subcategories [#categories-and-subcategories] `category` says what the item is. `subcategory` says where it goes on the body. | `category` | `subcategory` | | ---------- | ------------- | | `auto` (default) | leave it out | | `clothing` | required: `auto`, `tops`, `bottoms`, `dresses` | | `jewelry` | required: `rings`, `earrings`, `necklaces`, `bracelets`, `anklets` | | `accessories` | required: `watches`, `belts`, `scarves`, `bags`, `gloves`, `ties` | | `eyewear`, `footwear`, `headwear`, `others` | leave it out | Any other combination returns 400 `InvalidCategory`. With `auto`, the API looks at `garment_image` and picks the category before it queues the job. The submit takes a little longer, and a failed guess falls back to `clothing`. Send the category when you know it. ## Good to know [#good-to-know] - **Images** are public `http(s)` URLs or base64 data URLs. URLs must stay reachable while the job runs. See the [Image Guidelines](/docs/guides/image-guidelines). - **A bad image URL doesn't fail the submit.** The job fails later, and the status shows the reason. - **Partial results.** With `num_samples` above 1, `output` can hold fewer images than you asked for. You pay only for the images you get. - **Results expire** about 72 hours after the submit. Download the ones you want to keep. - **Limits** are shared with the hairstyle and tattoo endpoints. See [Rate Limits](/docs/concepts/rate-limits). ### POST /tryon/fashion Try a garment or accessory on a person Puts the item in `garment_image` on the person in `model_image` and returns a `jobId`. `category` says what the item is. Leave it out (or send `auto` with no `subcategory`) and the item is detected from the image. `clothing`, `jewelry` and `accessories` need a `subcategory` from their own list; `eyewear`, `footwear`, `headwear` and `others` must not have one. Auth: `Authorization: Bearer YOUR_API_KEY`. Request body (JSON): - `model_image` (string, required): The person. - `garment_image` (string, required): The garment or accessory. - `category` (string, optional, default "auto", one of "auto", "clothing", "eyewear", "footwear", "headwear", "jewelry", "accessories", "others"): What the item is. `auto` detects it from the image. `clothing`, `jewelry` and `accessories` need a `subcategory`; `auto`, `eyewear`, `footwear`, `headwear` and `others` must not have one. - `subcategory` (string | null, optional): Required for `clothing`, `jewelry` and `accessories`; omit (or `null`) otherwise. - `num_samples` (integer, optional, default 1, range 1..4): Number of output images. Each costs 1 credit. - `output_format` (string, optional, default "png", one of "png", "jpeg"): Format of the output images. ```json { "model_image": "https://example.com/model.jpg", "garment_image": "https://example.com/shirt.jpg", "category": "clothing", "subcategory": "tops" } ``` Responses: - `201`: Job accepted. Poll `GET /status/{id}` with `jobId`. ```json { "ok": true, "jobId": "64b7f1a9d9a3b8e5c7f9a123" } ``` - `400`: Invalid request. (`error.name`: `ImageLoadError`, `InvalidCategory`, `InvalidNumSamples`, `InvalidOutputFormat`) - `403`: Missing, malformed or unknown API key, or a disabled account. (`error.name`: `Forbidden`) - `404`: The API key's account no longer exists. (`error.name`: `NotFound`) - `413`: The JSON body is over 12 MB. Send large images as a URL. (`error.name`: `PayloadTooLarge`) - `429`: Not enough credits for `num_samples`, too much in flight, or rate limited. (`error.name`: `OutOfCredits`, `ConcurrencyLimitExceeded`, `RateLimitExceeded`) - `500`: The job could not be queued. Nothing was charged; retry. (`error.name`: `InternalServerError`) # Hairstyle Try-On API (/docs/api-reference/hairstyle-tryon) Restyle the hair in a face photo. Send the photo (`face_image`) and one of 42 `haircut` values. Add `hair_color` to change the color too. You get a `jobId` back right away. Then poll [Get Job Status](/docs/api-reference/job-status) until the result images are ready. Each output image costs 1 credit. A failed job is free. See [Pricing & Credits](/docs/concepts/credits-and-pricing). ## Haircuts [#haircuts] `haircut` is case-sensitive and must be one of the values listed under the request body below. Each SDK ships the list as a constant, so you can build a picker or check input before you submit: | SDK | Constant | | --- | -------- | | Node.js | `import { HAIRCUTS } from "tryiton"` | | Python | `from tryiton import HAIRCUTS` | | Go | `tryiton.Haircuts` | | PHP | `TryItOn\Client::HAIRCUTS` | | Ruby | `Tryiton::HAIRCUTS` | ## Good to know [#good-to-know] - **`hair_color` is free text**, such as `"ash blonde"` or `"copper red, subtle balayage"`. Leave it out to keep the current color. - **Photos.** A clear, front-facing face works best. See the [Image Guidelines](/docs/guides/image-guidelines). - **A bad image URL doesn't fail the submit.** The job fails later, and the status shows the reason. - **Results expire** about 72 hours after the submit. Download the ones you want to keep. - **Limits** are shared with the clothing and tattoo endpoints. See [Rate Limits](/docs/concepts/rate-limits). ### POST /tryon/hairstyle Try a haircut (and optionally a hair color) on a person Restyles the hair in `face_image` to `haircut` and returns a `jobId`. Auth: `Authorization: Bearer YOUR_API_KEY`. Request body (JSON): - `face_image` (string, required): The person's face. A portrait works best. - `haircut` (string, required, one of "Afro", "BobCut", "BowlCut", "BoxBraids", "ButterflyCut", "BuzzCut", "Chignon", "CombOver", "CornrowBraids", "CurlyBob", "CurlyShag", "DoubleBun", "Dreadlocks", "FauxHawk", "FishtailBraid", "FrenchBob", "LongCurly", "LongHairTiedUp", "LongHimeCut", "LongStraight", "LongTwintails", "LongWavy", "LongWavyCurtainBangs", "LowTaperFade", "ManBun", "MessyTousled", "MiddlePart", "ModernMullet", "PixieCut", "Pompadour", "Ponytail", "ShortCurlyPixie", "ShortTwintails", "ShoulderLengthHair", "SlickBack", "Spiky", "TexturedCrop", "TexturedFringe", "TwinBraids", "Updo", "WavyShag", "WolfCut"): A supported haircut. - `hair_color` (string, optional): Optional free-text color, e.g. `ash blonde with subtle highlights`. Trimmed and cut to 120 characters. Omit (or send an empty string) to keep the current color. - `num_samples` (integer, optional, default 1, range 1..4): Number of output images. Each costs 1 credit. - `output_format` (string, optional, default "png", one of "png", "jpeg"): Format of the output images. ```json { "face_image": "https://example.com/face.jpg", "haircut": "BuzzCut" } ``` Responses: - `201`: Job accepted. Poll `GET /status/{id}` with `jobId`. ```json { "ok": true, "jobId": "64b7f1a9d9a3b8e5c7f9a123" } ``` - `400`: Invalid request. (`error.name`: `BadRequest`, `InvalidNumSamples`, `InvalidOutputFormat`) - `403`: Missing, malformed or unknown API key, or a disabled account. (`error.name`: `Forbidden`) - `404`: The API key's account no longer exists. (`error.name`: `NotFound`) - `413`: The JSON body is over 12 MB. Send large images as a URL. (`error.name`: `PayloadTooLarge`) - `429`: Not enough credits for `num_samples`, too much in flight, or rate limited. (`error.name`: `OutOfCredits`, `ConcurrencyLimitExceeded`, `RateLimitExceeded`) - `500`: The job could not be queued. Nothing was charged; retry. (`error.name`: `InternalServerError`) # Virtual Try-On API Reference (/docs/api-reference) Every endpoint lives under one base URL and takes your API key as a bearer token. ```text title="Base URL" https://tryiton.now/api/v1 ``` ```bash curl https://tryiton.now/api/v1/credits \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Basics [#basics] - **Auth.** Send `Authorization: Bearer YOUR_API_KEY` from your server. Never from a browser or an app. See [Authentication](/docs/concepts/authentication). - **Requests** are JSON (`Content-Type: application/json`). Try-on and garment bodies can be up to 12 MB. Images are public URLs or base64 data URLs. - **Responses** carry `"ok": true` on success. Errors look like `{ "ok": false, "error": { "name": "...", "message": "..." } }`. Branch on `error.name`. See [Errors](/docs/concepts/errors). - **Photo try-ons are async.** A submit returns a `jobId`, and you poll [Get Job Status](/docs/api-reference/job-status). See [Jobs & Polling](/docs/concepts/jobs-and-polling). - **Limits** apply per account and per IP. See [Rate Limits](/docs/concepts/rate-limits). ## Endpoints [#endpoints] | Endpoint | What it does | | -------- | ------------ | | [`POST /tryon/fashion`](/docs/api-reference/fashion-tryon) | Put a garment or accessory on a person | | [`POST /tryon/hairstyle`](/docs/api-reference/hairstyle-tryon) | Restyle hair in a face photo | | [`POST /tryon/tattoo`](/docs/api-reference/tattoo-tryon) | Ink a design onto skin | | [`GET /status/{id}`](/docs/api-reference/job-status) | Get a photo try-on's status and result | | [`GET /credits`](/docs/api-reference/credits-balance) | Get your credit balance | | [`GET /health`](/docs/api-reference/credits-balance#health-check) | Check that the API is up (no key) | | [`GET /live/config`](/docs/api-reference/live-tryon) | Live try-on availability and pricing | | [`POST /live/garments`, `POST /live/outfits`](/docs/api-reference/live-garments) | Prepare garments and outfits for live try-on | | [`POST /live/sessions`, `GET`, list, stop](/docs/api-reference/live-sessions) | Start and manage live sessions | | [Browser endpoints](/docs/api-reference/live-tryon-browser-endpoints) | Heartbeat, garment switch, end. `tryiton-live` calls them | ## Machine-readable [#machine-readable] - The whole API as [OpenAPI 3.1](/docs/api-reference/openapi), for Postman, code generators and agents. - Every page is also plain markdown: add `.md` to its URL. [`/llms.txt`](/llms.txt) indexes them all, and [`/llms-full.txt`](/llms-full.txt) has every page in one file. - Prefer a client library? See the [SDKs](/docs/sdks). # Get Job Status (/docs/api-reference/job-status) Photo try-ons are asynchronous. The submit returns a `jobId`. Poll this endpoint about every 2 seconds until `status` is `completed` or `failed`. The SDK wait helpers do this for you. To get the result pushed instead, set up a [webhook](/docs/guides/webhooks). `{id}` is the `jobId`. It's also the **Prediction ID** under **Developer API → Requests** in your dashboard. ## Good to know [#good-to-know] - **A failed job is still HTTP 200.** Check `status`, not the HTTP code. `error` explains why, as text for people: log it or show it, but don't branch on its wording. - **Timeouts.** A job still processing 3 minutes after the submit fails with `"Timed out."`. Its held credits are released and you aren't charged. - **Result URLs** end in `.png` or `.jpg`, matching `output_format`. The images carry an EXIF tag that marks them as AI-generated. - **Retention.** Images are deleted about 72 hours after the submit, and after 3 days this endpoint returns 404 for the job. See [Data Retention](/docs/concepts/data-retention-and-privacy). - **Polling counts** toward the 300 requests a minute per IP limit. See [Jobs & Polling](/docs/concepts/jobs-and-polling). ### GET /status/{id} Get the status and result of a try-on job Works for every photo try-on type. Poll until `status` is `completed` or `failed`; every ~2 seconds is a good default. Jobs can be polled for 3 days after they were created; after that, and for an id that isn't yours or isn't a valid id, the answer is `404`. Output URLs are kept for 72 hours, so download what you need to keep. A failed job is a `200` with `status: "failed"` and the reason in `error`, a plain string. Failed jobs are not charged. Auth: `Authorization: Bearer YOUR_API_KEY`. Parameters: - `id` (in path, string, required): The `jobId` returned when the try-on was submitted. Responses: - `200`: The job's current status. ```json { "ok": true, "status": "processing", "output": [], "error": null } ``` - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `404`: No such job on this account, or it is older than 3 days. (`error.name`: `NotFound`) - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) # Live Try-On Garments & Outfits API (/docs/api-reference/live-garments) Before a garment can appear on a live stream, prepare it once on your server. You get an `id` back. Pass it as `garment_id` when you [start a session](/docs/api-reference/live-sessions#start-a-session), or to `live.switchGarment(id)` in the browser. To show 2 or 3 items at once, combine prepared garments into an outfit. Preparing is free, up to 2000 new garments and outfits per account per UTC day. Repeat calls for something already prepared return it at once with `200` and don't count. ## Good to know [#good-to-know] - **Prepare ahead.** Fetching, normalizing and describing an image takes a few seconds. Do it when you sync your catalog, not when the shopper clicks. - **Send the `category`.** Detection can misread photos that show more than the item, for example a model wearing a shirt *and* trousers. Categories are the same as for [Clothing & Accessories Try-On](/docs/api-reference/fashion-tryon#categories-and-subcategories). - **One garment per combination.** The same photo with a different category or different options gets a different `id`. - **Image URLs** are fetched by TryItOn: public, at most 25 MB, answering within 15 seconds and at most 5 redirects. Private and internal addresses are refused. Data URLs count toward the 12 MB body limit. - **Unused garments expire.** A garment or outfit nobody starts or switches to for 90 days is deleted. Prepare it again for a new `id`. Using an outfit keeps its items alive. Storage details are in [Data Retention & Privacy](/docs/concepts/data-retention-and-privacy). ### POST /live/garments Prepare a garment Turns a product image into what the live stream needs. This is the slow step (fetch, normalize, describe: a few seconds), so do it ahead of time, for example at catalog sync. Idempotent per image, category and options: a repeat call returns the stored garment with `200` instead of `201`. Free. An account can prepare up to 2000 new garments per UTC day (`429 GarmentLimitExceeded` past that); repeat calls for an already prepared garment don't count. A garment nobody has started or switched to for 90 days is deleted: prepare it again to get a new `id`. Auth: `Authorization: Bearer YOUR_API_KEY`. Request body (JSON): - `garment_image` (string, required): A public `http(s)` URL or a `data:image/...;base64,` URI of the garment. A product photo on a plain background works best. - `category` (string | null, optional): Recommended. What the item is, or `auto` / omitted to detect it. Detection can misread photos that show more than the item. - `subcategory` (string | null, optional): Must be valid for `category` (see `TryonSubcategory`). Ignored when `category` is omitted. - `detail_images` (string[], optional): Up to 3 extra photos of the same item (back, side, close-up detail), each a URL (at most 8 MB) or data URI. They only sharpen the item's description, so they're ignored when you send `description`; the stream is shown `garment_image` alone. - `description` (string, optional): Your own description of the item, e.g. `black leather knee-high boots`. Replaces the detected one in the generated prompt. - `instructions` (string, optional): Your own prompt for the stream, used instead of the generated one, word for word. - `enhance_prompt` (boolean, optional, default true): Let the stream expand the prompt. Turn it off to have exact `instructions` used as written. ```json { "garment_image": "https://example.com/products/shirt.jpg", "category": "clothing", "subcategory": "tops" } ``` Responses: - `200`: Already prepared from the same image and pick (cached). ```json { "ok": true, "garment": { "id": "6b0827eba2f220ae7dd7c7fb", "category": "clothing", "subcategory": "tops", "description": "a navy short-sleeve pique polo shirt", "prompt": "Substitute the current top with a navy short-sleeve pique polo shirt shown in the reference image, matching its color, material, and fit.", "enhancePrompt": true, "items": null, "createdAt": "2026-11-26T12:20:59.512Z" } } ``` - `201`: Newly prepared. ```json { "ok": true, "garment": { "id": "6b0827eba2f220ae7dd7c7fb", "category": "clothing", "subcategory": "tops", "description": "a navy short-sleeve pique polo shirt", "prompt": "Substitute the current top with a navy short-sleeve pique polo shirt shown in the reference image, matching its color, material, and fit.", "enhancePrompt": true, "items": null, "createdAt": "2026-11-26T12:20:59.512Z" } } ``` - `400`: Invalid or unreadable image (`garment_image` or a `detail_images` entry), an invalid category pick, or an invalid `description`, `instructions` or `enhance_prompt`. (`error.name`: `ImageLoadError`, `InvalidCategory`) - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `404`: The `garment_image` URL answered 404. (`error.name`: `ImageLoadError`) - `413`: The JSON body is over 12 MB. Send large images as a URL. (`error.name`: `PayloadTooLarge`) - `429`: Too many requests, or the daily allowance of new garments is used up. (`error.name`: `RateLimitExceeded`, `GarmentLimitExceeded`) - `500`: Unexpected server error. Retry after a delay. (`error.name`: `InternalServerError`) ## Custom instructions [#custom-instructions] The generated prompt replaces the item's slot ("Substitute the current shoes with…") or adds an accessory, and leaves the rest of the shopper's outfit alone. When you need something else, send your own `instructions`. They're used word for word. Set `enhance_prompt: false` to stop the stream from expanding them. ```json title="POST /live/garments request body" { "garment_image": "https://example.com/products/boots.jpg", "category": "footwear", "instructions": "Replace only the shoes with the black leather knee-high boots shown in the reference image. Keep the person's clothing, body shape and proportions unchanged.", "enhance_prompt": false } ``` Describe the item in words. The stream follows the text, and an instruction that only says "the item in the reference image" can leave the video unchanged. To keep the generated prompt and only fix the item's name, send a `description` instead. Check the returned `prompt` on a real stream before you prepare a whole catalog. ## Outfits [#outfits] **What can go together.** Each item needs a known place on the body, which comes from its category. No two items may take the same place: one top, one bottom, one pair of shoes, one hat, one watch and so on. A dress takes the top and the bottom. Items in the `others` category (socks, suspenders) combine freely. An outfit can't contain another outfit. A garment prepared with `category: "auto"` works when detection could tell where it's worn. **Use product photos.** Each item's image becomes one part of the outfit's image. An item prepared from a photo of a model in a full outfit brings that whole outfit along. Use packshots, flat lays or ghost mannequin photos. **Swapping one item.** Prepare the new combination (the same trousers and shoes with a different top) and switch to it. The stream keeps running and the other items stay in place. Prepare the variants ahead to make switches instant. Items' own `instructions` don't carry over. The outfit's prompt names each item by its category and description, unless you send `instructions` for the outfit. ### POST /live/outfits Prepare an outfit Combines 2 or 3 prepared garments (say a top, trousers and shoes) into one outfit the stream applies at once. The returned `id` works anywhere a garment id does: `garment_id` when starting a session, or a mid-stream switch. To swap one item, prepare the new combination and switch to it; the other items stay in place. Each item needs a known place on the body (its category) and no two items may take the same place (a dress takes the top and bottoms). Items' own `instructions` don't carry over: the outfit's prompt names each item by its category and description, unless you send `instructions` for the outfit. Idempotent per set of garments and options, in any order. Free; counts toward the same daily allowance and rate limit as `POST /live/garments`. Auth: `Authorization: Bearer YOUR_API_KEY`. Request body (JSON): - `garment_ids` (string[], required): Prepared garments to wear together, in any order. At most one per body place. - `instructions` (string, optional): Your own prompt for the stream, used instead of the generated one, word for word. - `enhance_prompt` (boolean, optional, default true): Let the stream expand the prompt. ```json { "garment_ids": [ "6b0827eba2f220ae7dd7c7fb", "6b0827eba2f220ae7dd7c7fc", "6b0827eba2f220ae7dd7c7fd" ] } ``` Responses: - `200`: Already prepared from the same garments and options (cached). - `201`: Newly prepared. ```json { "ok": true, "outfit": { "id": "6b0827eba2f220ae7dd7c800", "category": "outfit", "subcategory": null, "description": "a navy short-sleeve pique polo shirt, black slim jeans, white leather sneakers", "prompt": "Substitute the current top with a navy short-sleeve pique polo shirt shown at the top, the current pants with black slim jeans shown in the middle and the current shoes with white leather sneakers shown at the bottom of the reference image, matching each item's color, material, and fit.", "enhancePrompt": true, "items": [ "6b0827eba2f220ae7dd7c7fb", "6b0827eba2f220ae7dd7c7fc", "6b0827eba2f220ae7dd7c7fd" ], "createdAt": "2026-11-26T12:24:10.031Z" } } ``` - `400`: `garment_ids` isn't 2 or 3 distinct ids, an item is an outfit or has no known place on the body, two items take the same place, or `instructions` / `enhance_prompt` is invalid. - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `404`: A garment id isn't a prepared garment on this account. - `429`: Too many requests, or the daily allowance of new garments is used up. - `500`: Unexpected server error. Retry after a delay. (`error.name`: `InternalServerError`) # Live Try-On Sessions API (/docs/api-reference/live-sessions) A session is one shopper's live stream. Your server starts it with the API key and sends the whole start response to the browser, where `tryiton-live` connects. Your server can also list, inspect and stop sessions. What a session costs is on [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Before you start one [#before-you-start-one] - **Open the camera first.** The session holds a credit from the moment it starts, and a permission prompt can take a while. - **Send the whole response to the browser, unchanged**, and pass it to `connectLiveTryOn`. Don't pick fields out: `tryiton-live` reads `clientSecret`, `connection` and `garment`. The media token in it can only start a connection within 60 seconds. - **Send `end_user_id`** for signed-in shoppers. Each shopper then gets one stream: a reload or a second tab ends the previous session with `endReason: "superseded"`, charged like any other end. Use an opaque id, not an email. - **Send `allowed_origin`** on the web. It locks the media token to pages on your site. Leave it out for native apps. - **Send `garment_id`** when you know the first garment. Its stream input comes back in the response, so the first frame doesn't wait on another call. Without it, the browser names a garment when it connects. **The order of the start checks.** The first one that fails is the error you get: 1. Parameters: `400`, or `404` for an unknown `garment_id`. 2. Live try-on switched off: `503 LiveTryonUnavailable`. 3. Account disabled: `403 Forbidden`. 4. At capacity, for accounts that haven't bought credits or a plan: `503 LiveTryonUnavailable`. 5. Already `maxConcurrentSessions` streams, not counting the shopper's own session that this start replaces: `429 LiveTryonBusy`. 6. Fewer than `minCredits` usable credits, or the first credit can't be held: `429 OutOfCredits`. 7. With `end_user_id`, the shopper's previous session is ended. A start refused above leaves it running. 8. Two racing starts for the same `end_user_id`: `409 LiveSessionActive`. Retry once. 9. Starts racing past the stream cap: `429 LiveTryonBusy`. The hold is returned. 10. The media token or first garment couldn't be loaded: `503 LiveTryonUnavailable`. The hold is returned. Live starts never return `ConcurrencyLimitExceeded`: running photo try-ons don't block them. ### POST /live/sessions Start a session Starts a live session for one end user and holds its first credit. Call it from your server and send the whole response, unchanged, to the end user's device (for example to `connectLiveTryOn` from `tryiton-live`). Open the camera before calling: the session holds a credit from the moment it starts. With `end_user_id`, each end user gets one stream: starting again ends their previous session with `endReason: "superseded"`, once the new start has passed its checks (a refused start leaves it running). **Billing.** A start that returns an error holds nothing. Heartbeats charge one credit per tick while the stream runs, and every end charges the held credit, so a partial tick rounds up. A stream that never connected gets the held credit back: the device ends it with `reason: "error"` and `connected: false` within 20 s of the start, before any heartbeat (5 sessions per account per UTC day). An ended session also pays for the time it was open by the server's clock, from the start to the end (or to when it went stale), minus up to 20 s for connecting, and never more than its media token can stream. So a device that skips heartbeats still pays for the time it was open. Balances never go below zero. The media token can only start a connection within 60 s of this call. **Backup stream.** When the primary stream fails to connect before the first frame and the response has a `connection.backup`, the device moves the same session to the backup stream with `POST /live/sessions/{id}/failover` (`tryiton-live` 0.4+ does this). It's on by default. With `providers: ["decart", "vidu"]` and a `garment_id`, a start may also go straight to the backup while the primary is down. Send `providers: ["decart"]` to turn the backup off: no failover, and a `503` while the primary is down. Auth: `Authorization: Bearer YOUR_API_KEY`. Request body (JSON): - `garment_id` (string | null, optional): A prepared garment to start with. Its stream input comes back in the response, so the first frame doesn't wait on another call. Without it, the device names a garment when it connects. - `max_seconds` (integer | null, optional, range 10..180): Cap for this session, from 10 to `maxSeconds` in `GET /live/config` (180 by default). Defaults to `maxSeconds`. - `end_user_id` (string | null, optional): Your id for the end user: 1-100 letters, digits and `_ . - @ :`. One stream per end user: starting again ends their previous session. - `allowed_origin` (string | null, optional): The browser origin the media token is locked to, e.g. `https://shop.example.com` (scheme matched case-insensitively, no path). Recommended for web integrations; leave it out for native apps. - `providers` (array | null, optional): The streams the device's client can play; must include `decart`. Left out, the session starts on the primary stream and has the backup during connect. `[decart, vidu]` (`tryiton-live` 0.4+) may also start on the backup while the primary is down. `[decart]`: primary only, no backup. ```json { "garment_id": "6b0827eba2f220ae7dd7c7fb", "end_user_id": "shopper-42", "allowed_origin": "https://shop.example.com", "providers": [ "decart", "vidu" ] } ``` Responses: - `201`: Session started. Hand this body to the device. ```json { "ok": true, "session": { "id": "6b0828e5ed117d43a6d10ad1", "status": "active", "endReason": null, "seconds": 0, "creditsCharged": 0, "endUserId": "shopper-42", "apiKeyId": "6b0827eba2f220ae7dd7c7aa", "refunded": false, "creditsRefunded": 0, "createdAt": "2026-11-26T12:21:57.402Z", "endedAt": null }, "clientSecret": "3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3", "connection": { "provider": "decart", "model": "lucy-vton-latest", "token": "ek_live_8f2b9c4d1a7e", "backup": "vidu" }, "secondsPerCredit": 3, "maxSeconds": 180, "secondsLeft": 117, "garment": { "id": "6b0827eba2f220ae7dd7c7fb", "category": "clothing", "subcategory": "tops", "description": "a navy short-sleeve pique polo shirt", "prompt": "Substitute the current top with a navy short-sleeve pique polo shirt shown in the reference image, matching its color, material, and fit.", "enhancePrompt": true, "items": null, "createdAt": "2026-11-26T12:20:59.512Z", "input": { "prompt": "Substitute the current top with a navy short-sleeve pique polo shirt shown in the reference image, matching its color, material, and fit.", "enhancePrompt": true, "referenceImage": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD" } } } ``` - `400`: An invalid parameter. (`error.name`: `BadRequest`) - `403`: Missing, malformed or unknown API key, or a disabled account. (`error.name`: `Forbidden`) - `404`: Unknown `garment_id` on this account. (`error.name`: `NotFound`) - `409`: Two starts for the same `end_user_id` raced (or a newer start replaced this one while its stream opened). Retry once. (`error.name`: `LiveSessionActive`) - `429`: Too many streams, the backup stream full, not enough credits, or rate limited. (`error.name`: `LiveTryonBusy`, `OutOfCredits`, `RateLimitExceeded`) - `500`: Unexpected server error. Retry after a delay. (`error.name`: `InternalServerError`) - `503`: Live try-on is switched off, at capacity (accounts that haven't bought credits or a plan only), or the media token or first garment couldn't be loaded. Nothing was charged. (`error.name`: `LiveTryonUnavailable`) ## Backup stream [#backup-stream] Sessions run on the primary stream. A backup stream steps in two ways: - **During connect.** When the primary stream fails for this shopper before the first frame, and the start response has a `connection.backup`, `tryiton-live` 0.4 or later moves the same session to the backup with [failover](/docs/api-reference/live-tryon-browser-endpoints#switch-to-the-backup-stream). Same session, same id. Your server does nothing. This is on by default. - **At start.** While the primary stream is down, a start can go straight to the backup. This needs `providers: ["decart", "vidu"]` (your browser client is `tryiton-live` 0.4 or later) and a `garment_id`. Send `providers: ["decart"]` to turn the backup off. You then get no failover, and a `503` while the primary is down. Billing is the same on both streams: a session that fails over is billed from its first backup frame, and the failed attempt is free. If your page sets a Content Security Policy, see [the quickstart](/docs/guides/live-tryon-quickstart#content-security-policy). ### GET /live/sessions/{id} Get a session Status and usage of one of your live sessions. Auth: `Authorization: Bearer YOUR_API_KEY`. Parameters: - `id` (in path, string, required): A live session `id` from `POST /live/sessions`. Anything other than 24 hex characters is a `400`. Responses: - `200`: The session. ```json { "ok": true, "session": { "id": "6b0828e5ed117d43a6d10ad1", "status": "ended", "endReason": "user", "seconds": 9, "creditsCharged": 5, "endUserId": "shopper-42", "apiKeyId": "6b0827eba2f220ae7dd7c7aa", "refunded": false, "creditsRefunded": 0, "createdAt": "2026-11-26T12:21:57.402Z", "endedAt": "2026-11-26T12:22:12.118Z" } } ``` - `400`: The session id is not 24 hex characters. (`error.name`: `BadRequest`) - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `404`: No such session on this account (or, on device endpoints, a wrong secret). (`error.name`: `NotFound`) - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) ### GET /live/sessions List sessions Your account's live sessions started through the API, newest first, with the same fields as Get a session. Use it for usage reports and to reconcile billing: `creditsCharged` is what a session was charged, `refunded` and `creditsRefunded` show what was given back. Pages hold up to `limit` sessions. When `nextCursor` is not `null`, pass it as `cursor` to get the next (older) page. Filters combine with AND. Auth: `Authorization: Bearer YOUR_API_KEY`. Parameters: - `limit` (in query, integer): Sessions per page, from 1 to 100. - `cursor` (in query, string): The `nextCursor` of the previous page. - `status` (in query, string): Only sessions with this status. - `end_reason` (in query, string): Only sessions that ended for this reason. - `api_key_id` (in query, string): Only sessions started with this API key (its id, as in a session's `apiKeyId`). - `refunded` (in query, boolean): `true`: only sessions that were refunded (`refunded: true`). `false` is accepted and doesn't filter. Responses: - `200`: One page of sessions, newest first. ```json { "ok": true, "sessions": [ { "id": "6b0828e5ed117d43a6d10ad1", "status": "ended", "endReason": "user", "seconds": 9, "creditsCharged": 5, "endUserId": "shopper-42", "apiKeyId": "6b0827eba2f220ae7dd7c7aa", "refunded": false, "creditsRefunded": 0, "createdAt": "2026-11-26T12:21:57.402Z", "endedAt": "2026-11-26T12:22:12.118Z" }, { "id": "6b0828a1ed117d43a6d10ac4", "status": "ended", "endReason": "error", "seconds": 0, "creditsCharged": 0, "endUserId": "shopper-17", "apiKeyId": "6b0827eba2f220ae7dd7c7aa", "refunded": true, "creditsRefunded": 0, "createdAt": "2026-11-26T12:20:51.880Z", "endedAt": "2026-11-26T12:21:03.004Z" } ], "nextCursor": "6b0828a1ed117d43a6d10ac4" } ``` - `400`: An invalid query parameter. (`error.name`: `BadRequest`) - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) - `500`: Unexpected server error. Retry after a delay. (`error.name`: `InternalServerError`) The dashboard shows the same list under **Developer API → Requests → Live**. Only sessions started through the API are listed. Use `end_reason=error` to find streams that failed, and `refunded=true` for the ones given back. ### POST /live/sessions/{id}/stop Stop a session Ends a session from your server, for example when the end user leaves the page. Idempotent: stopping an ended session returns it unchanged. Ends with `endReason: "user"`. No request body is needed. The held credit is charged, plus any time the server's clock says is still owed (see Start a session). Auth: `Authorization: Bearer YOUR_API_KEY`. Parameters: - `id` (in path, string, required): A live session `id` from `POST /live/sessions`. Anything other than 24 hex characters is a `400`. Responses: - `200`: The session. ```json { "ok": true, "session": { "id": "6b0828e5ed117d43a6d10ad1", "status": "ended", "endReason": "user", "seconds": 9, "creditsCharged": 5, "endUserId": "shopper-42", "apiKeyId": "6b0827eba2f220ae7dd7c7aa", "refunded": false, "creditsRefunded": 0, "createdAt": "2026-11-26T12:21:57.402Z", "endedAt": "2026-11-26T12:22:12.118Z" } } ``` - `400`: The session id is not 24 hex characters. (`error.name`: `BadRequest`) - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `404`: No such session on this account (or, on device endpoints, a wrong secret). (`error.name`: `NotFound`) - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) Stop a session as soon as you know the shopper has left. A browser that vanishes without ending keeps the session open until it goes `stale`, and the server's clock bills that time. # Live Try-On Browser Endpoints (/docs/api-reference/live-tryon-browser-endpoints) The shopper's device calls these endpoints during a live session: a billing **heartbeat**, a mid-stream **garment switch**, a one-time **failover** to the backup stream, and **end**. They take the session's `clientSecret`, never your API key. The session itself is [started by your server](/docs/api-reference/live-sessions#start-a-session). **The easy path is [`tryiton-live`](https://www.npmjs.com/package/tryiton-live).** `connectLiveTryOn` makes every call on this page for you, with the right timing, retries and page-unload handling. See the [Real-Time Virtual Try-On Quickstart](/docs/guides/live-tryon-quickstart). ## Authentication and CORS [#authentication-and-cors] - Send the `clientSecret` as `secret` in the JSON body, or as the `secret` query parameter. The body wins when both are present. - A missing or wrong secret, or an unknown session, is `404 NotFound`, so the endpoints never reveal whether a session exists. The secret only works for its own session. Don't log or store it. - These endpoints accept cross-origin requests from any site and need no cookies. The server endpoints don't. - Per-IP rate limits are on [Rate Limits & Concurrency](/docs/concepts/rate-limits). Over a limit, the answer is `429 RateLimitExceeded` with no `Retry-After` header. ## Heartbeat timing [#heartbeat-timing] - **Start the billing clock at the first try-on frame**, not when the connection opens. Send the first heartbeat `secondsPerCredit` seconds after that frame, then one every `secondsPerCredit` seconds on a fixed schedule from the first frame, so request time doesn't stretch the ticks. - **Send `seq`** and retrying is always safe: a settled `seq` answers without a charge. Then carry on with `ticks + 1`. - **Retry a failed heartbeat** after about 2 seconds. `tryiton-live` ends the stream after two failures in a row, so it never streams unbilled. - **Stop at once on `stop: true`.** The session has already ended, so there's no need to call end. - **Missing heartbeats** make the session `stale` after 3 missed ticks plus 30 seconds (about 39 seconds at 3 seconds per credit). It is then charged like any other end. ### POST /live/sessions/{id}/heartbeat Billing heartbeat Send one every `secondsPerCredit` seconds once the first try-on frame arrives (`tryiton-live` sends the first one `secondsPerCredit` seconds after that frame). Each heartbeat charges the credit held for the tick that just ended and holds the next one. When the response has `stop: true`, stop streaming at once. Send `seq`, the 1-based number of the tick you are settling (`ticks + 1` from the last response; `1` first). A retried heartbeat with the same `seq` is never charged twice, however late it arrives: it answers `stop: false` with the current `secondsLeft` and `ticks`. Without `seq`, a heartbeat less than 80% of a tick after the previous one is not charged. **Auth:** the session's `clientSecret`, as `secret` in the JSON body (or the `secret` query parameter). No API key. A wrong secret is a `404`, so the endpoint never reveals whether a session exists. Auth: none. Parameters: - `id` (in path, string, required): A live session `id` from `POST /live/sessions`. Anything other than 24 hex characters is a `400`. - `secret` (in query, string): The session's `clientSecret`, when it isn't sent as `secret` in the JSON body. One of the two is required; the body wins when both are present. Meant for the page-unload `end` keepalive, which is sent as `text/plain` (a JSON content type would need a CORS preflight that a closing page can't wait for). Request body (JSON): - `secret` (string, optional): The session's `clientSecret`. Required unless sent as the `secret` query parameter. - `seq` (integer, optional, range 1..): The 1-based tick this heartbeat settles: `ticks + 1` from the previous response, `1` for the first. A repeat is answered without a charge. Optional; invalid values are ignored. - `connect_ms` (number, optional, range 0..): Milliseconds from start to the first frame. Rounded and capped at 120000; invalid values are ignored. ```json { "secret": "3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3", "seq": 1, "connect_ms": 2834 } ``` Responses: - `200`: Keep streaming (`stop: false`) or stop now (`stop: true`). ```json { "ok": true, "stop": false, "secondsLeft": 18, "ticks": 1 } ``` - `400`: The session id is not 24 hex characters, or a JSON body is malformed. (`error.name`: `BadRequest`) - `404`: No such session on this account (or, on device endpoints, a wrong secret). (`error.name`: `NotFound`) - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) ### POST /live/sessions/{id}/garments/{garmentId} Switch garment Returns a prepared garment's stream input for a mid-stream switch and records the switch on the session. The garment must be prepared on the same account. Also use it to load the first garment when the session was started without `garment_id`. Free. **Auth:** the session's `clientSecret`, as `secret` in the JSON body (or the `secret` query parameter). No API key. Auth: none. Parameters: - `id` (in path, string, required): A live session `id` from `POST /live/sessions`. Anything other than 24 hex characters is a `400`. - `garmentId` (in path, string, required): A garment `id` from `POST /live/garments`. - `secret` (in query, string): The session's `clientSecret`, when it isn't sent as `secret` in the JSON body. One of the two is required; the body wins when both are present. Meant for the page-unload `end` keepalive, which is sent as `text/plain` (a JSON content type would need a CORS preflight that a closing page can't wait for). Request body (JSON): - `secret` (string, optional): The session's `clientSecret`. Required unless sent as the `secret` query parameter. ```json { "secret": "3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3" } ``` Responses: - `200`: The garment with its stream input. ```json { "ok": true, "garment": { "id": "6b0827eba2f220ae7dd7c7fb", "category": "clothing", "subcategory": "tops", "description": "a navy short-sleeve pique polo shirt", "prompt": "Substitute the current top with a navy short-sleeve pique polo shirt shown in the reference image, matching its color, material, and fit.", "enhancePrompt": true, "items": null, "createdAt": "2026-11-26T12:20:59.512Z", "input": { "prompt": "Substitute the current top with a navy short-sleeve pique polo shirt shown in the reference image, matching its color, material, and fit.", "enhancePrompt": true, "referenceImage": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD" } } } ``` - `400`: The session or garment id is malformed. (`error.name`: `BadRequest`) - `404`: Unknown session, wrong secret, or a garment not prepared on this account. (`error.name`: `NotFound`) - `409`: The session has already ended, so there's no stream to switch. - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) ### POST /live/sessions/{id}/failover Switch to the backup stream Moves a session whose primary stream failed to connect over to the backup stream: same session, id and secret. Allowed once per session, only when its start response had a `connection.backup` (it wasn't started with `providers: ["decart"]`), before the first frame (no heartbeat yet), and within 60 s of the start. An account can fail over 50 sessions per UTC day. `tryiton-live` 0.4+ calls this for you. Answers the new `connection`. Join it and carry on with heartbeats as usual. Billing starts at the first frame of the backup stream: the failed attempt is not charged, and the 20 s connect allowance counts from the switch. Garment switches work the same way afterwards. **Auth:** the session's `clientSecret`, as `secret` in the JSON body. No API key. Auth: none. Parameters: - `id` (in path, string, required): A live session `id` from `POST /live/sessions`. Anything other than 24 hex characters is a `400`. Request body (JSON): - `secret` (string, required): The session's `clientSecret`. - `garment_id` (string, required): The garment the device is showing (its latest switch, or the start garment). ```json { "secret": "3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3", "garment_id": "6b0827eba2f220ae7dd7c7fb" } ``` Responses: - `200`: The session now uses the backup stream. Connect with this. ```json { "ok": true, "connection": { "provider": "vidu", "model": "vidu-s2-editing", "token": null, "vidu": { "rtc": { "token": "eyJhcHBpZCI6...", "userId": "u_6b0828e5" }, "renderUid": "render_6b0828e5" } } } ``` - `400`: The session id is malformed, or `garment_id` is missing or malformed. (`error.name`: `BadRequest`) - `404`: Unknown session, wrong secret, or a garment not prepared on this account. (`error.name`: `NotFound`) - `409`: `LiveFailoverRefused`: the session has no backup, already streamed or switched, is past the 60 s window, or the account reached its daily limit. `LiveSessionEnded`: it has ended. Either way, end it and start a new session. (`error.name`: `LiveFailoverRefused`, `LiveSessionEnded`) - `429`: The backup stream is full, or rate limited. The session stays open; end it. (`error.name`: `LiveTryonBusy`, `RateLimitExceeded`) - `503`: The backup stream is unavailable right now. The session stays open; end it. After a `409`, `429` or `503` from failover, end the session with `reason: "error"` and `connected: false`, like any failed connect. ### POST /live/sessions/{id}/end End a session Ends the session from the device. Idempotent. Charges the held tick plus any time the server's clock says is still owed (see Start a session). `connected` and `connect_ms` are recorded and don't change the charge, with one exception: a failed connect (`reason: "error"`, `connected: false`, within 20 s of the start or of a failover, no heartbeat yet) gets the held credit back, up to 5 sessions per account per UTC day. **Auth:** the session's `clientSecret`, as `secret` in the JSON body or the `secret` query parameter. No API key. When the page is closing, send a `text/plain` keepalive request with the secret in the URL (`.../end?secret=...`) so no CORS preflight is needed. A `text/plain` body is parsed as JSON, so `reason`, `connected` and `connect_ms` count exactly as in a JSON request. A body that isn't a JSON object (empty, malformed, an array) is treated as `{}`: the session ends with `reason: "unload"` and the held tick is charged. Auth: none. Parameters: - `id` (in path, string, required): A live session `id` from `POST /live/sessions`. Anything other than 24 hex characters is a `400`. - `secret` (in query, string): The session's `clientSecret`, when it isn't sent as `secret` in the JSON body. One of the two is required; the body wins when both are present. Meant for the page-unload `end` keepalive, which is sent as `text/plain` (a JSON content type would need a CORS preflight that a closing page can't wait for). Request body (JSON): - `secret` (string, optional): The session's `clientSecret`. Required unless sent as the `secret` query parameter. - `reason` (string, optional, default "unload", one of "user", "idle", "hidden", "error", "unload"): The reasons a device may report. Anything else is recorded as `unload`. - `connected` (boolean, optional): Whether video ever arrived. Recorded for analytics; it doesn't change what is charged. - `connect_ms` (number, optional, range 0..): Milliseconds from start to the first frame. Rounded and capped at 120000. - `error` (string, optional): What went wrong. Kept only when `reason` is `error`; cut to 300 characters. ```json { "secret": "3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3", "reason": "user", "connected": true, "connect_ms": 2834 } ``` Responses: - `200`: The session. ```json { "ok": true, "session": { "id": "6b0828e5ed117d43a6d10ad1", "status": "ended", "endReason": "user", "seconds": 9, "creditsCharged": 5, "endUserId": "shopper-42", "apiKeyId": "6b0827eba2f220ae7dd7c7aa", "refunded": false, "creditsRefunded": 0, "createdAt": "2026-11-26T12:21:57.402Z", "endedAt": "2026-11-26T12:22:12.118Z" } } ``` - `400`: The session id is not 24 hex characters, or a JSON body is malformed. (`error.name`: `BadRequest`) - `404`: No such session on this account (or, on device endpoints, a wrong secret). (`error.name`: `NotFound`) - `413`: A `text/plain` body over 10 KB. - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) ### Ending when the page closes [#ending-when-the-page-closes] A closing page can't wait for a CORS preflight. Send the end as a `keepalive` request with a `text/plain` body and the secret in the URL: ```js fetch(`https://tryiton.now/api/v1/live/sessions/${sessionId}/end?secret=${encodeURIComponent(clientSecret)}`, { method: "POST", keepalive: true, headers: { "Content-Type": "text/plain" }, body: JSON.stringify({ reason: "unload", connected: true, connect_ms: 2834 }), }); ``` ## Building your own client [#building-your-own-client] 1. Get the start response from your server. Keep `clientSecret` in memory only. 2. Open the camera and connect to the media network with `connection`, sending `garment.input` as the first garment. If `garment` is `null`, load one with [Switch garment](#switch-garment) first. 3. If the stream fails before the first frame and `connection.backup` is set, call [failover](#switch-to-the-backup-stream) and connect again with the answer. 4. At the first try-on frame, start the heartbeat schedule. 5. Close the stream at once when a heartbeat answers `stop: true`. 6. End with `connected` set truthfully, and send the `text/plain` keepalive end on `pagehide`. The media connection (step 2) is what `tryiton-live` does for you. If you need a native client, email [contact@tryiton.now](mailto:contact@tryiton.now) for the connection details. # Live Virtual Try-On API (Real-Time Webcam) (/docs/api-reference/live-tryon) The live virtual try-on API shows shoppers themselves wearing a garment in real time, through their webcam. Your server prepares garments and starts a session with your API key. The shopper's browser streams the video with the [`tryiton-live`](https://www.npmjs.com/package/tryiton-live) package. **Building a storefront?** The [Real-Time Virtual Try-On Quickstart](/docs/guides/live-tryon-quickstart) wires these endpoints to `tryiton-live` end to end. ## How live try-on works [#how-live-try-on-works] 1. **Prepare each garment once** on your server ([`POST /live/garments`](/docs/api-reference/live-garments)). This is the slow step, so do it ahead of time, for example when you sync your catalog. To show several items at once, combine prepared garments into an [outfit](/docs/api-reference/live-garments#prepare-an-outfit). 2. **Start a session per shopper** on your server ([`POST /live/sessions`](/docs/api-reference/live-sessions#start-a-session)) and send the whole response to the browser. 3. **The browser streams.** `tryiton-live` opens the camera and connects to the media network with the short-lived token from the start response. The video goes from the shopper's device to the media network and back. It never passes through TryItOn's servers. 4. **The browser reports usage.** While video flows, it sends billing heartbeats. The session ends when the shopper or your server ends it, at `max_seconds`, or when the balance runs out. ## Two callers [#two-callers] | Caller | Credential | Endpoints | | ------ | ---------- | --------- | | **Your server** | Your API key (`Authorization: Bearer YOUR_API_KEY`) | [Garments & outfits](/docs/api-reference/live-garments), [sessions](/docs/api-reference/live-sessions), [config](#get-the-live-config) | | **The shopper's browser** | The session's `clientSecret` from the start response | [Browser endpoints](/docs/api-reference/live-tryon-browser-endpoints): heartbeat, switch garment, failover, end. `tryiton-live` makes these calls | Keep the API key on your server. The server endpoints are CORS-locked to TryItOn's own sites, so a browser can't call them anyway. The start response only holds credentials for that one session, so it's safe to send to the browser. **Label the video as AI-modified.** The EU AI Act (Article 50) requires sites that show AI-altered video of a person to say so. `tryiton-live` can show the label for you: see [Show the AI disclosure](/docs/guides/live-tryon-quickstart#show-the-ai-disclosure). For the camera notice and privacy policy, see the [Live Try-On Camera & Privacy Guide](/docs/guides/live-tryon-camera-privacy). ## Billing [#billing] Live try-on spends the same credits as photo try-ons. One credit buys `secondsPerCredit` seconds of video (3 by default), counted from the first try-on frame. A partial tick rounds up, and a stream that never connects is normally free. The full rules are in [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## End reasons [#end-reasons] Every ended session has an `endReason`: | `endReason` | Meaning | | ----------- | ------- | | `user` | Ended by the shopper, or by your server with [Stop a session](/docs/api-reference/live-sessions#stop-a-session). | | `time_limit` | Reached `max_seconds`. | | `out_of_credits` | The next tick couldn't be paid. | | `superseded` | The same `end_user_id` started a new session. | | `stale` | The browser stopped sending heartbeats (closed tab, lost network): 3 missed ticks plus 30 seconds. | | `budget` | The service was at capacity. Only for accounts that haven't bought credits or a plan. | | `error` | The stream failed, for example no video arrived in time. | | `idle`, `hidden`, `unload` | Reported by the browser: shopper idle, tab hidden, page closed. | ## Limits [#limits] Up to 3 sessions stream at once per account (`maxConcurrentSessions`; it can be raised on request). Live sessions don't count toward the photo try-on [concurrency limit](/docs/concepts/rate-limits), and photo jobs never block a live start. Rate limits for each endpoint are on [Rate Limits & Concurrency](/docs/concepts/rate-limits). ### GET /live/config Get the live config Whether live try-on is available right now, and its pricing and limits for your account. Free. Auth: `Authorization: Bearer YOUR_API_KEY`. Responses: - `200`: Current live try-on settings. ```json { "ok": true, "enabled": true, "secondsPerCredit": 3, "maxSeconds": 180, "minCredits": 4, "maxConcurrentSessions": 3 } ``` - `403`: Missing, malformed or unknown API key. (`error.name`: `Forbidden`) - `429`: Too many requests from this IP. (`error.name`: `RateLimitExceeded`) ## Related [#related] - [Live Garments & Outfits](/docs/api-reference/live-garments): prepare what the stream shows. - [Live Sessions](/docs/api-reference/live-sessions): start, list, inspect and stop sessions, and the backup stream. - [Live Try-On Browser Endpoints](/docs/api-reference/live-tryon-browser-endpoints): for teams building their own client. - [Virtual Try-On SDKs](/docs/sdks): the Node.js, Python, Go, PHP and Ruby clients. # OpenAPI Specification (/docs/api-reference/openapi) The whole public virtual try-on API (`https://tryiton.now/api/v1`) is described in one OpenAPI 3.1 file: > **GET** [`https://docs.tryiton.now/openapi.yaml`](https://docs.tryiton.now/openapi.yaml) ## What the spec covers [#what-the-spec-covers] The spec describes 14 operations: | Area | Operations | | ---- | ---------- | | Photo try-on | `POST /tryon/fashion`, `POST /tryon/hairstyle`, `POST /tryon/tattoo` | | Jobs and account | `GET /status/{id}`, `GET /credits`, `GET /health` | | Live, server | `GET /live/config`, `POST /live/garments`, `POST /live/outfits`, `POST /live/sessions`, `GET /live/sessions/{id}`, `POST /live/sessions/{id}/stop` | | Live, browser | `POST /live/sessions/{id}/heartbeat`, `POST /live/sessions/{id}/garments/{garmentId}`, `POST /live/sessions/{id}/end` | Each operation comes with its request and response schemas, required fields, defaults, limits, enums, examples, and the `error.name` values it can return. The storefront widget's embed routes and TryItOn's internal routes are not part of the public API, so the spec leaves them out. **Authentication.** Most operations take your API key as `Authorization: Bearer YOUR_API_KEY`. `GET /health` takes no credential. The three live browser endpoints take the session's `clientSecret` instead, so the spec marks them as needing no API key. See [Live Try-On Browser Endpoints](/docs/api-reference/live-tryon-browser-endpoints). ## What you can do with it [#what-you-can-do-with-it] - **Postman or Insomnia.** Import the URL above as a new collection. Set the collection's bearer token to your API key and every request is ready to send. - **Client generation.** Point a generator such as [OpenAPI Generator](https://openapi-generator.tech) at the file to build a client in a language the official SDKs don't cover. - **LLM agents.** Give the URL to an agent or a tool-calling framework. It describes every operation, parameter and error in a form a model can follow, so the agent can call the API without guessing. ## SDKs or a generated client? [#sdks-or-a-generated-client] For Node.js, Python, Go, PHP and Ruby, use the [official virtual try-on SDKs](/docs/sdks) rather than a generated client. They're written by hand on top of the same contract and add what a generator can't: waiting for a job's result with polling and a timeout, one error type that carries `error.name`, and the live session calls shaped for handing the start response to the browser. For the browser side of live try-on, use [`tryiton-live`](https://www.npmjs.com/package/tryiton-live). ## Source of truth [#source-of-truth] The spec lives next to the API's code. A test checks it against the server's routes on every run, all five SDKs run a shared set of contract tests from it, and the reference pages of these docs render from it. When the API changes, the spec, the SDKs and the docs change together. ## Related [#related] - [Virtual Try-On SDKs](/docs/sdks): install and configure an official SDK. - [Authentication & API Keys](/docs/concepts/authentication): create a key and send it. - [Error Codes & Handling](/docs/concepts/errors): every `error.name` the API returns. # Tattoo Try-On API (/docs/api-reference/tattoo-tryon) Show how a design would look as real ink on someone's skin. Send a close-up of bare skin (`body_image`) and the design on its own (`design_image`). Say where it goes with `placement` text, an exact `region`, or both. You get a `jobId` back right away. Then poll [Get Job Status](/docs/api-reference/job-status) until the result images are ready. Each output image costs 1 credit. A failed job is free. See [Pricing & Credits](/docs/concepts/credits-and-pricing). ## Positioning the tattoo [#positioning-the-tattoo] **`placement`** is free text, like `"on the right forearm, small"`. It's enough when the photo shows one obvious area. Left out, the design goes on the most visible skin at about palm size. **`region`** pins the exact spot. It's a rectangle on `body_image`, measured from the top-left corner, with every value from 0 to 1: ```json title="Request body (excerpt)" { "region": { "x": 0.32, "y": 0.18, "w": 0.28, "h": 0.34 }, "placement": "fine-line, black ink" } ``` > Diagram: The tattoo region is a rectangle on body_image. x and y place its top-left corner, w and h set its width and height, all as fractions of the photo from 0 to 1, measured from the top-left corner. The example is x 0.32, y 0.18, w 0.28, h 0.34. A large region, with a side of at least 0.2, is filled by the design. A small region marks the spot, and placement sets the size. With a `region`, `placement` only sets size and style: - **A large region** (either side at least 0.2) is filled. The design is centered and scaled to fit, so a sleeve starts and ends where the rectangle does. - **A small region** marks the spot, and `placement` sets the size, like `"small, about 5 cm wide"`. - Each side must be at least 0.06. A malformed `region` returns 400 `InvalidRegion`. - Only the rectangle and a thin margin change. The rest of the photo comes back as it was. Use `region` when your UI lets people draw a box on the photo. Use `placement` when it doesn't. ## Good to know [#good-to-know] - **Design images.** A white or transparent background around the design is removed, so it isn't inked. - **Photos.** The target skin should be clearly visible and evenly lit. See the [Image Guidelines](/docs/guides/image-guidelines). - **A bad image URL doesn't fail the submit.** The job fails later, and the status shows the reason. - **Results expire** about 72 hours after the submit. Download the ones you want to keep. - **Limits** are shared with the clothing and hairstyle endpoints. See [Rate Limits](/docs/concepts/rate-limits). ### POST /tryon/tattoo Try a tattoo design on skin Inks `design_image` onto the skin in `body_image` and returns a `jobId`. Say where with `placement` (free text), `region` (an exact rectangle), or both. With a `region`, `placement` only describes size and style. Auth: `Authorization: Bearer YOUR_API_KEY`. Request body (JSON): - `body_image` (string, required): A close-up of bare skin (arm, leg, shoulder, back). - `design_image` (string, required): The tattoo design on its own, ideally on a plain background. - `placement` (string, optional): Free-text placement and size, e.g. `on the right forearm, small`. Line breaks are flattened and the text is cut to 140 characters (never rejected). Omitted: placed naturally on the most visible skin, about palm-sized. With a `region`, it only describes size and style. - `region` (object | null, optional): Optional exact rectangle. `null` is the same as leaving it out. - `num_samples` (integer, optional, default 1, range 1..4): Number of output images. Each costs 1 credit. - `output_format` (string, optional, default "png", one of "png", "jpeg"): Format of the output images. ```json { "body_image": "https://example.com/forearm.jpg", "design_image": "https://example.com/design.png", "placement": "on the right forearm, small" } ``` Responses: - `201`: Job accepted. Poll `GET /status/{id}` with `jobId`. ```json { "ok": true, "jobId": "64b7f1a9d9a3b8e5c7f9a123" } ``` - `400`: Invalid request. (`error.name`: `InvalidRegion`, `ImageLoadError`, `InvalidNumSamples`, `InvalidOutputFormat`) - `403`: Missing, malformed or unknown API key, or a disabled account. (`error.name`: `Forbidden`) - `404`: The API key's account no longer exists. (`error.name`: `NotFound`) - `413`: The JSON body is over 12 MB. Send large images as a URL. (`error.name`: `PayloadTooLarge`) - `429`: Not enough credits for `num_samples`, too much in flight, or rate limited. (`error.name`: `OutOfCredits`, `ConcurrencyLimitExceeded`, `RateLimitExceeded`) - `500`: The job could not be queued. Nothing was charged; retry. (`error.name`: `InternalServerError`) # Webhook Events (/docs/api-reference/webhook-events) We POST these events to the endpoint you set up in the dashboard. Set it up, verify signatures and handle retries with the [Webhooks guide](/docs/guides/webhooks). ## Good to know [#good-to-know] - **Verify first.** Check `webhook-signature` against the raw body before you trust any field. - **`id` is stable.** It equals the `webhook-id` header and stays the same on every retry. Use it to skip duplicates. - **`data` matches `GET /status/{id}`** for the job, plus `jobId`. Result URLs last 72 hours, like the [status](/docs/api-reference/job-status) ones. - **Any `2xx` within 10 seconds** counts as delivered. ### Webhook event: tryon.completed (we POST it to your endpoint) Try-on completed Sent once when a photo try-on made with an API key completes. `data` is what `GET /status/{id}` returns for the job, plus its `jobId`. Download the images within 72 hours. Auth: verify the `webhook-signature` header with your `whsec_` signing secret. Parameters: - `webhook-id` (in header, string, required): The event `id`. The same on every retry of an event, so use it to skip events you already handled. - `webhook-timestamp` (in header, string, required): When this attempt was sent, in Unix seconds. Reject requests more than 5 minutes off your clock. - `webhook-signature` (in header, string, required): Space-separated signatures, each `v1,`: HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64-decoded part of your `whsec_` secret after the prefix. Accept the request when any one matches. For 24 hours after a secret rotation there is also one per older secret (at most three in all). Request body (JSON): - `id` (string, required): Unique per event and the same on every retry. Equal to the `webhook-id` header. - `type` ("tryon.completed", required): - `created_at` (string, required): When the event was created. Retries keep this value. - `data` (object, required): - `jobId` (string, required): The `jobId` the submit returned. - `status` (string, required, one of "completed", "failed"): - `output` (string[], required): CDN URLs of the result images when `completed`, otherwise empty. Kept for 72 hours. - `error` (string | null, required): Why the job failed, as a plain string, when `status` is `failed`. Otherwise `null`. ```json { "id": "evt_5f0c8a1e2b3d4c5e6f708192", "type": "tryon.completed", "created_at": "2026-12-04T10:15:30.120Z", "data": { "jobId": "64b7f1a9d9a3b8e5c7f9a123", "status": "completed", "output": [ "https://cdn.tryiton.now/USER_ID/tryons/3f2c9a.png" ], "error": null } } ``` Responses: - `200`: Any `2xx` tells us the event arrived. Any other status, a redirect, or no response within 10 seconds counts as a failure and is retried. ### Webhook event: tryon.failed (we POST it to your endpoint) Try-on failed Sent once when a photo try-on made with an API key fails, including a job that timed out. Its held credits are released and it isn't charged. `error` says why, as text for people. Auth: verify the `webhook-signature` header with your `whsec_` signing secret. Parameters: - `webhook-id` (in header, string, required): The event `id`. The same on every retry of an event, so use it to skip events you already handled. - `webhook-timestamp` (in header, string, required): When this attempt was sent, in Unix seconds. Reject requests more than 5 minutes off your clock. - `webhook-signature` (in header, string, required): Space-separated signatures, each `v1,`: HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64-decoded part of your `whsec_` secret after the prefix. Accept the request when any one matches. For 24 hours after a secret rotation there is also one per older secret (at most three in all). Request body (JSON): - `id` (string, required): Unique per event and the same on every retry. Equal to the `webhook-id` header. - `type` ("tryon.failed", required): - `created_at` (string, required): When the event was created. Retries keep this value. - `data` (object, required): - `jobId` (string, required): The `jobId` the submit returned. - `status` (string, required, one of "completed", "failed"): - `output` (string[], required): CDN URLs of the result images when `completed`, otherwise empty. Kept for 72 hours. - `error` (string | null, required): Why the job failed, as a plain string, when `status` is `failed`. Otherwise `null`. ```json { "id": "evt_9a8b7c6d5e4f30211a2b3c4d", "type": "tryon.failed", "created_at": "2026-12-04T10:18:02.511Z", "data": { "jobId": "64b7f1a9d9a3b8e5c7f9a124", "status": "failed", "output": [], "error": "Timed out." } } ``` Responses: - `200`: Any `2xx` tells us the event arrived. Any other status, a redirect, or no response within 10 seconds counts as a failure and is retried. ### Webhook event: webhook.test (we POST it to your endpoint) Test event Sent when you press **Send test event** in the dashboard. Signed like every other event, so it checks your verification code end to end. It isn't retried. Auth: verify the `webhook-signature` header with your `whsec_` signing secret. Parameters: - `webhook-id` (in header, string, required): The event `id`. The same on every retry of an event, so use it to skip events you already handled. - `webhook-timestamp` (in header, string, required): When this attempt was sent, in Unix seconds. Reject requests more than 5 minutes off your clock. - `webhook-signature` (in header, string, required): Space-separated signatures, each `v1,`: HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64-decoded part of your `whsec_` secret after the prefix. Accept the request when any one matches. For 24 hours after a secret rotation there is also one per older secret (at most three in all). Request body (JSON): - `id` (string, required): Unique per event and the same on every retry. Equal to the `webhook-id` header. - `type` ("webhook.test", required): - `created_at` (string, required): - `data` (object, required): - `message` (string, required): ```json { "id": "evt_0f1e2d3c4b5a69788796a5b4", "type": "webhook.test", "created_at": "2026-12-04T10:00:00.000Z", "data": { "message": "This is a test event from TryItOn." } } ``` Responses: - `200`: Any `2xx` tells us the event arrived. Any other status, a redirect, or no response within 10 seconds counts as a failure and is retried. # TryItOn API Changelog (/docs/resources/changelog) What changed for API users, newest first. The list starts with the first SDK releases in June 2026. Earlier changes aren't listed. To follow changes as they ship: - Watch the [OpenAPI spec](https://docs.tryiton.now/openapi.yaml). It is the source for the [API reference](/docs/api-reference/openapi) and the SDKs. - Read the SDK release notes: each repo has a `CHANGELOG.md`. See [tryiton-node](https://github.com/tryiton-now/tryiton-node), [tryiton-python](https://github.com/tryiton-now/tryiton-python), [tryiton-go](https://github.com/tryiton-now/tryiton-go), [tryiton-php](https://github.com/tryiton-now/tryiton-php), [tryiton-ruby](https://github.com/tryiton-now/tryiton-ruby) and [tryiton-live](https://github.com/tryiton-now/tryiton-live). How we version the API is on [API Versioning & Deprecations](/docs/resources/versioning). ## December 2026 [#december-2026] ### 2026-12-05 [#2026-12-05] - **New haircuts:** eight more `haircut` values for [hairstyle try-on](/docs/api-reference/hairstyle-tryon): `ButterflyCut`, `FrenchBob`, `LowTaperFade`, `MiddlePart`, `ModernMullet`, `SlickBack`, `TexturedCrop` and `WolfCut`. That makes 42. The SDKs' haircut lists include them from the next release. ### 2026-12-04 [#2026-12-04] - **Cheaper live try-on:** 1 credit now buys 3 seconds of live video (was 2), so 1,000 credits buy 50 minutes instead of 33. A start needs 4 credits instead of 5. A session keeps the rate it started with. Read the current values from [`GET /live/config`](/docs/api-reference/live-tryon#get-the-live-config). - **New: webhooks.** Get a signed POST when a photo try-on made with an API key completes or fails (`tryon.completed`, `tryon.failed`), instead of polling. Set up the endpoint, rotate its secret and see every delivery on the API Keys page. Signatures follow Standard Webhooks. See [Webhooks](/docs/guides/webhooks). - **SDKs 2.5.0:** `verifyWebhook` (`verify_webhook`, `VerifyWebhook`, `Webhook::verify`) checks a webhook's signature and returns the event. See [Verify webhooks](/docs/sdks#verify-webhooks). - **New:** `GET /live/sessions` lists your live sessions, newest first. It pages with a cursor and filters by status, end reason, API key and refunded sessions. See [live sessions](/docs/api-reference/live-sessions). - **New fields:** live sessions now have `apiKeyId`, `refunded` and `creditsRefunded`. - **Dashboard:** a low balance email for API accounts. Set the threshold on the API Keys page (150 credits by default, 0 turns it off). The Requests page has a Live tab with your sessions. - **SDKs 2.4.0:** list live sessions and read the new fields. - **Faster timeouts:** a photo try-on still processing after 3 minutes now fails with `"Timed out."` (was 5), and the check runs every minute, so every job has a final status within about 4 minutes. A failed job is free, so you can resubmit right away. Waits of 4 minutes are enough. - **Removed:** `mode` and `moderation_level` on `POST /tryon/fashion`. Requests that still send them keep working: both are ignored like any unknown field, and an unknown `moderation_level` no longer returns `400`. - **Docs:** new layout, with the API reference generated from the OpenAPI spec. Limits corrected on several pages. ### 2026-12-03 [#2026-12-03] - **Live try-on:** sessions now get a backup stream by default. If the primary stream fails to connect, the browser switches the same session to the backup with the new `POST /live/sessions/{id}/failover` endpoint. That works once per session, within 60 seconds of the start, and 50 times per account per UTC day. - **New field:** `providers` on `POST /live/sessions` turns the backup off or lets a session start on the backup. The start response has `connection.backup`. See [backup stream](/docs/api-reference/live-sessions#backup-stream). - **Billing:** after a failover, billing and the failed connect allowance count from the switch. - **SDKs 2.3.0** and **tryiton-live 0.4.0:** support for the backup stream. ### 2026-12-02 [#2026-12-02] - **Higher default limits:** photo try-ons go from 10 to 30 per minute per account, and from 5 to 10 credits held by running jobs. Limits can be raised per account. See [Rate Limits](/docs/concepts/rate-limits). - `GET /live/config` returns your own account's `maxConcurrentSessions`. ## November 2026 [#november-2026] ### 2026-11-30 [#2026-11-30] - **Live billing:** a stream that fails to connect within 20 seconds gets its held credit back, up to 5 times per account per UTC day. See [Live Try-On Billing](/docs/concepts/live-tryon-billing). - **Dashboard:** usage per API key under Developer API, Analytics. - **Embed widget:** site keys can hide TryItOn branding when your plan allows it. See the [embed widget guide](/docs/guides/embed-widget). ### 2026-11-27 [#2026-11-27] - **New:** `POST /live/outfits` combines 2 or 3 prepared garments into one outfit. Its id works anywhere a garment id does. See [outfits](/docs/api-reference/live-garments#outfits). - **New fields:** `POST /live/garments` accepts `detail_images` (up to 3), `description`, `instructions` and `enhance_prompt`. - **SDKs 2.2.0:** live outfits and the new garment options. - **tryiton-live 0.2.0:** an AI disclosure label over the try-on video. - **tryiton-live 0.3.0:** iOS Safari fixes. New `attachStream()`. A session now ends when the page is hidden (`endWhenHidden`, on by default). See [iOS Safari](/docs/guides/live-tryon-quickstart#ios-safari). ### 2026-11-26 [#2026-11-26] - **New:** live (real time camera) try-on. Server endpoints `GET /live/config`, `POST /live/garments`, `POST /live/sessions`, `GET /live/sessions/{id}` and `POST /live/sessions/{id}/stop`, plus [browser endpoints](/docs/api-reference/live-tryon-browser-endpoints) that authenticate with a session secret. Up to 3 live streams per account. - **New:** the [OpenAPI spec](/docs/api-reference/openapi) for `/api/v1`. - **Live billing:** sessions are billed by the server clock. Heartbeats take an optional `seq`, so a retried heartbeat is never charged twice. A session token must start its connection within 60 seconds. - **Live garments:** up to 2000 new garments per account per UTC day (`GarmentLimitExceeded`). Garments unused for 90 days are deleted. - **Deprecated:** `mode` and `moderation_level` on `POST /tryon/fashion`. Both are still accepted. `mode` is ignored, and `moderation_level` is validated but has no effect. - **Errors:** a body that isn't valid JSON returns `400 BadRequest` instead of `500`. A garment switch on an ended session returns `409 LiveSessionEnded`. Live streams no longer count toward the photo concurrency limit. - **Privacy:** input images are removed from finished jobs. Image URLs written as a private IP address (such as `http://10.0.0.5/`) are refused, also after a redirect. - **SDKs 2.1.0:** live try-on methods. Errors now carry the API's `error.name` and `error.message`, and `waitForResult` reports the job's real failure reason. - **tryiton-live 0.1.0:** first release of the browser package for live try-on. - **Docs:** rewritten and restructured. Old URLs redirect. ## October 2026 [#october-2026] ### 2026-10-27 [#2026-10-27] - **Tattoo `region`:** a large rectangle (either side at least 0.2 of the image) is filled by the design. A smaller one marks the spot and `placement` sets the size. See [tattoo try-on](/docs/api-reference/tattoo-tryon). ## July 2026 [#july-2026] ### 2026-07-14 [#2026-07-14] - **Breaking:** `POST /tryon/clothes` is now `POST /tryon/fashion`. It covers clothing, footwear, eyewear, headwear, jewelry and accessories. **SDKs 2.0.0** rename `tryOnClothes` to `tryOnFashion`. - **New field:** `region` on tattoo try-ons pins the design to a rectangle on the body photo. **SDKs 1.1** add it. ## June 2026 [#june-2026] ### 2026-06-24 [#2026-06-24] - `num_samples` (1 to 4) and `output_format` (`png` or `jpeg`) work on every try-on, including hairstyle and tattoo. - **SDKs 1.0.0:** the `seed`, `segmentation_free` and `garment_photo_type` options are removed. ### 2026-06-22 [#2026-06-22] - **SDKs 0.1.0:** first release of the Node.js, Python, Go, PHP and Ruby SDKs. # Troubleshooting & FAQ (/docs/resources/troubleshooting) Find your symptom, then follow the link for the full rules. Every error response has an `error.name`: branch on that, not on the message. The full list is on [Errors](/docs/concepts/errors). ## Requests that fail [#requests-that-fail] ### 403 Forbidden [#403-forbidden] The API key check failed. Check, in order: - The header is exactly `Authorization: Bearer YOUR_API_KEY`. A missing `Bearer ` prefix is refused. - The key still exists. A deleted key is refused right away. A site key for the embed widget is not an API key. - On try-ons and live starts, a 403 with "Your account has been disabled" means the account is off. Contact us. See [Authentication](/docs/concepts/authentication). Don't retry a 403 unchanged. ### 429 Too Many Requests: which one? [#429-too-many-requests-which-one] Read `error.name`: | `error.name` | Cause | What to do | |---|---|---| | `RateLimitExceeded` | Over 300 requests per minute per IP, 30 photo try-ons per minute per account, or a live endpoint limit. | Back off with jitter and retry within the 60 second window. | | `ConcurrencyLimitExceeded` | Running photo jobs already hold 10 or more credits. | Wait for a running job to finish, then resubmit. | | `OutOfCredits` | Not enough spendable credits. Credits held by running jobs don't count. | Buy credits. Retrying won't help. | | `LiveTryonBusy` | 3 live streams already running on the account. | End one first. | These are default limits. They can be raised per account. See [Rate Limits](/docs/concepts/rate-limits) and [Pricing & Credits](/docs/concepts/credits-and-pricing). ### 413 PayloadTooLarge [#413-payloadtoolarge] The JSON body is over 12 MB on `/tryon/*` and `POST /live/garments`, or over 10 KB anywhere else. Send large images as a public URL instead of base64. See [Image Guidelines](/docs/guides/image-guidelines). ### 400 InvalidCategory [#400-invalidcategory] The `category` and `subcategory` pair isn't valid, or you sent a `subcategory` with `category: "auto"`. Use a pair from the [fashion try-on](/docs/api-reference/fashion-tryon) table, or leave `subcategory` out. ### CORS error in the browser [#cors-error-in-the-browser] The photo try-on, status, credits and server-side live endpoints don't allow calls from other sites' browsers. Call them from your server, which also keeps your API key secret. The live [browser endpoints](/docs/api-reference/live-tryon-browser-endpoints) are the exception: they accept any origin and use the session secret. For a no-backend option, use the [embed widget](/docs/guides/embed-widget). ## Jobs and results [#jobs-and-results] ### Job stuck in `processing` [#job-stuck-in-processing] A job still running 3 minutes after you submitted it is marked `failed` with `"Timed out."`. It costs nothing, so resubmit it. If the SDK wait helper gave up first, keep polling the same job id. See [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling). ### Job failed: the image couldn't be loaded [#job-failed-the-image-couldnt-be-loaded] The submit only checks that the image is there. It's fetched when the job runs. Common causes: - The URL isn't public: it needs a login or cookie, or it's a signed link that expired. - The host blocks hotlinking or bot traffic. Host the image yourself or send base64. - The image is over 25 MB, the host took longer than 15 seconds, or the URL redirects more than 5 times. - The URL points at `localhost` or a private network. Test the URL in a private browser window. See [Image Guidelines](/docs/guides/image-guidelines). ### The result URL returns 404 [#the-result-url-returns-404] Result images are deleted about 72 hours after the submit, and `GET /status/{id}` returns `404` after 3 days. Download results you want to keep. See [Data Retention](/docs/concepts/data-retention-and-privacy). ### The result looks wrong or low quality [#the-result-looks-wrong-or-low-quality] Most quality problems come from the input photos. Follow the [Image Guidelines](/docs/guides/image-guidelines). Send an explicit `category` and `subcategory` when you know them: with `auto`, a failed guess falls back to `clothing`. Ask for up to 4 images with `num_samples` and keep the best one. ### I got two jobs for one request [#i-got-two-jobs-for-one-request] A network error on submit can hide a job that was created. See [retries and duplicate jobs](/docs/concepts/jobs-and-polling#retries-and-duplicate-jobs). ## Live try-on [#live-try-on] ### A live session won't start [#a-live-session-wont-start] - `429 OutOfCredits`: a session needs `minCredits` to start. Read it from `GET /live/config`. - `429 LiveTryonBusy`: the account already runs 3 streams. - `409 LiveSessionActive`: a session is running for this `end_user_id`. Stop it or retry. - `503 LiveTryonUnavailable`: live try-on is off for your account or at capacity. Retry later or offer a photo try-on. See [live sessions](/docs/api-reference/live-sessions). ### The camera or video doesn't show [#the-camera-or-video-doesnt-show] The browser needs camera permission and HTTPS. Call `openCamera()` from `tryiton-live` to ask for permission before your server starts a billed session. On iPhone, see [iOS Safari](/docs/guides/live-tryon-quickstart#ios-safari). If your page sets a Content Security Policy, allow the hosts listed in the [quickstart](/docs/guides/live-tryon-quickstart#content-security-policy). If you sent `allowed_origin`, it must match the page's origin. ### A live session stopped [#a-live-session-stopped] Read the session's `endReason` (full list in [end reasons](/docs/api-reference/live-tryon#end-reasons)): - `out_of_credits`: the next tick couldn't be paid. Top up. - `time_limit`: the session reached `max_seconds`. - `hidden`: the page was hidden (another tab, app or a locked phone). `tryiton-live` ends it by default. - `stale`: the device stopped sending heartbeats. - `superseded`: a new session started for the same `end_user_id`. A stream that fails to connect within 20 seconds gets its held credit back, up to 5 times per account per UTC day. See [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Status and help [#status-and-help] ### Is the API up? [#is-the-api-up] `GET https://tryiton.now/api/v1/health` returns `200` with `{ "ok": true }`. It needs no API key, so you can point an uptime monitor at it. There's no public status page. ### Getting help [#getting-help] Use the [contact form](https://tryiton.now/contact). Include the job or session id, the time, the endpoint and the `error.name`. Never send your API key. # API Versioning & Deprecations (/docs/resources/versioning) ## The version is in the path [#the-version-is-in-the-path] Every endpoint lives under `https://tryiton.now/api/v1`. There's no version header and no date to pin. The `v1` in the path is the API version. ## What can change inside v1 [#what-can-change-inside-v1] Changes inside v1 add to the API. They don't remove or rename anything you already use. Expect these over time: - New endpoints. - New optional request fields. - New fields in responses. - New `error.name` values. The spec says it plainly: "New names may be added." - New enum values, such as a new live session `endReason`. Write your client so these don't break it: - **Ignore response fields you don't know.** Don't fail on extra keys. - **Handle unknown error names.** Branch on `error.name` for the ones you care about, and fall back on the HTTP status for the rest. Never match on `error.message`: its wording can change. See [Errors](/docs/concepts/errors). - **Handle unknown enum values.** Treat a status or end reason you don't recognize as a generic case, not a crash. ## Breaking changes [#breaking-changes] A change that would break existing clients would ship under a new path version, such as `/api/v2`, and be announced in the [changelog](/docs/resources/changelog). There's no v2 today. ## Deprecations [#deprecations] A deprecated parameter stays accepted, so old requests keep working. It's marked `deprecated` in the [OpenAPI spec](/docs/api-reference/openapi) and in the API reference, and the deprecation is listed in the changelog. Nothing is deprecated today. ## SDK versions [#sdk-versions] The SDKs follow [semantic versioning](https://semver.org/). A major version can break your code, a minor version adds features, and a patch fixes bugs. - **SDK versions are separate from the API version.** Every 2.x SDK calls `/api/v1`. - **Go** puts the major version in the module path: `github.com/tryiton-now/tryiton-go/v2`. - **tryiton-live**, the browser package for live try-on, is still at 0.x. Read its changelog before you move to a new minor version. Pin the major version in your package manager and read the SDK's `CHANGELOG.md` before you upgrade. Links are on the [changelog](/docs/resources/changelog) page. ## Related [#related] - [API Changelog](/docs/resources/changelog) - [Error Codes & Handling](/docs/concepts/errors) - [OpenAPI Spec](/docs/api-reference/openapi) - [SDKs](/docs/sdks) # Virtual Try-On SDK for Go (/docs/sdks/go) The [`github.com/tryiton-now/tryiton-go/v2`](https://pkg.go.dev/github.com/tryiton-now/tryiton-go/v2) module is the official Go client for the virtual try-on API. It wraps every server endpoint of `https://tryiton.now/api/v1`, returns one error type, and polls jobs for you. New to the API? Run your first try-on with the [Quickstart](/docs/getting-started/quickstart). ```bash go get github.com/tryiton-now/tryiton-go/v2 ``` It needs Go 1.20 or later and uses only the standard library. The import path ends in `/v2`; the package name is `tryiton`. Every method takes a `context.Context` first, so deadlines and cancellation work the usual way. ## Configure the client [#configure-the-client] 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. `tryiton.New(apiKey string, opts ...tryiton.Option)` returns `(*tryiton.Client, error)`. The request timeout, retries, proxies and logging all live on the `*http.Client` you pass in. ```go title="main.go" package main import ( "context" "fmt" "log" "net/http" "os" "time" tryiton "github.com/tryiton-now/tryiton-go/v2" ) // retryGets retries GETs (status, credits, sessions) on gateway errors. It never // retries a POST: a retried submit can create a second job. type retryGets struct{ next http.RoundTripper } func (t retryGets) RoundTrip(req *http.Request) (*http.Response, error) { for attempt := 1; ; attempt++ { res, err := t.next.RoundTrip(req) if req.Method != http.MethodGet || attempt == 3 || err != nil || res.StatusCode < 502 || res.StatusCode > 504 { return res, err } res.Body.Close() time.Sleep(time.Duration(attempt) * time.Second) } } func main() { client, err := tryiton.New( os.Getenv("TRYITON_API_KEY"), tryiton.WithHTTPClient(&http.Client{ Timeout: 30 * time.Second, Transport: retryGets{next: http.DefaultTransport}, }), ) if err != nil { log.Fatal(err) } credits, err := client.GetCredits(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", *credits) } ``` | Option | Default | Description | | ------ | ------- | ----------- | | `apiKey` (argument) | required | Your API key. An empty key returns an error named `ConfigError`. | | `tryiton.WithBaseURL(u string)` | `tryiton.DefaultBaseURL` (`https://tryiton.now/api/v1`) | API base URL. A trailing slash is removed. | | `tryiton.WithHTTPClient(h *http.Client)` | `&http.Client{Timeout: 60 * time.Second}` | Your own client: request timeout, a custom `Transport` for retries, logging or a proxy, or a test server's client. | ## Methods [#methods] Every method takes a `context.Context` first. Try-on and live parameters are structs; zero-value fields are left out of the request, so the API defaults apply. | Method | Endpoint | Returns | | ------ | -------- | ------- | | `TryOnFashion(ctx, FashionParams)` | [`POST /tryon/fashion`](/docs/api-reference/fashion-tryon) | job id (`string`) | | `TryOnHairstyle(ctx, HairstyleParams)` | [`POST /tryon/hairstyle`](/docs/api-reference/hairstyle-tryon) | job id (`string`) | | `TryOnTattoo(ctx, TattooParams)` | [`POST /tryon/tattoo`](/docs/api-reference/tattoo-tryon) | job id (`string`) | | `GetStatus(ctx, jobID)` | [`GET /status/{id}`](/docs/api-reference/job-status) | `*Status` (`Status`, `Output`, `Error`) | | `WaitForResult(ctx, jobID, pollInterval)` | polls `GET /status/{id}` | result URLs (`[]string`) | | `GetCredits(ctx)` | [`GET /credits`](/docs/api-reference/credits-balance) | `*Credits` | | `GetLiveConfig(ctx)` | [`GET /live/config`](/docs/api-reference/live-tryon) | `*LiveConfig` | | `PrepareLiveGarment(ctx, PrepareLiveGarmentParams)` | [`POST /live/garments`](/docs/api-reference/live-garments) | `*LiveGarment` | | `PrepareLiveOutfit(ctx, PrepareLiveOutfitParams)` | [`POST /live/outfits`](/docs/api-reference/live-garments) | `*LiveGarment` | | `StartLiveSession(ctx, StartLiveSessionParams)` | [`POST /live/sessions`](/docs/api-reference/live-sessions) | `*LiveSessionStart` | | `ListLiveSessions(ctx, ListLiveSessionsParams)` | [`GET /live/sessions`](/docs/api-reference/live-sessions) | `*LiveSessionPage` (`Sessions`, `NextCursor`) | | `GetLiveSession(ctx, sessionID)` | [`GET /live/sessions/{id}`](/docs/api-reference/live-sessions) | `*LiveSession` | | `StopLiveSession(ctx, sessionID)` | [`POST /live/sessions/{id}/stop`](/docs/api-reference/live-sessions) | `*LiveSession` | The package also exports `tryiton.Haircuts` (the 42 accepted `Haircut` values) and `tryiton.Bool(v)` for the optional `EnhancePrompt *bool` fields. Images are public URLs or base64 data URLs. The snippets below reuse `client` and a `ctx` from your code. ```go fashionJobID, err := client.TryOnFashion(ctx, tryiton.FashionParams{ ModelImage: "https://example.com/model.jpg", GarmentImage: "https://example.com/tshirt.jpg", Category: "clothing", Subcategory: "tops", }) hairJobID, err := client.TryOnHairstyle(ctx, tryiton.HairstyleParams{ FaceImage: "https://example.com/face.jpg", Haircut: "PixieCut", HairColor: "copper red", }) tattooJobID, err := client.TryOnTattoo(ctx, tryiton.TattooParams{ BodyImage: "https://example.com/forearm.jpg", DesignImage: "https://example.com/rose.png", Region: &tryiton.TattooRegion{X: 0.32, Y: 0.18, W: 0.28, H: 0.34}, }) ``` ## Wait for results [#wait-for-results] `WaitForResult(ctx, jobID, pollInterval)` polls until the job finishes or the context ends. `pollInterval` of `0` means 2 seconds. It has **no timeout of its own**, so give the context a deadline. Every job has a final status within 4 minutes: ```go ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute) defer cancel() urls, err := client.WaitForResult(ctx, fashionJobID, 2*time.Second) ``` It returns the result URLs, or an error named `ProcessingError` (the job failed) or `Timeout` (the context ended between two polls). If the context ends during a request, the name is `NetworkError`. In an HTTP handler, derive the context from `r.Context()` so the wait stops when the caller leaves. Ending the wait doesn't stop the job, so poll it later instead of resubmitting. To check a stored job id from a worker, call `GetStatus` yourself: ```go job, err := client.GetStatus(ctx, fashionJobID) if err != nil { log.Fatal(err) } switch job.Status { case "completed": fmt.Println(job.Output) case "failed": if job.Error != nil { fmt.Println("failed:", job.Error.Message) } } ``` For a failed job, `Error` is a `*tryiton.JobError` whose `Message` is the failure reason. It is `nil` while the job runs. See [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) for job lifetimes. ## Errors [#errors] Every method returns a `*tryiton.Error` for API errors and failed jobs. Unwrap it with `errors.As` and branch on `Name`, not on the message. | Field | Type | Description | | ----- | ---- | ----------- | | `Status` | `int` | HTTP status. `0` for errors raised by the SDK. | | `Name` | `string` | The API error name, such as `OutOfCredits`, or an SDK name below. Empty for a non-JSON error page. | | `Message` | `string` | Human-readable text. For `ProcessingError`, the job's failure reason. | ```go urls, err := client.WaitForResult(ctx, fashionJobID, 0) var apiErr *tryiton.Error switch { case err == nil: fmt.Println(urls[0]) case !errors.As(err, &apiErr): log.Fatal(err) case apiErr.Name == "ProcessingError": log.Printf("failed, not charged: %s", apiErr.Message) case apiErr.Name == "Timeout": log.Print("still running; poll it later") default: log.Printf("%d %s: %s", apiErr.Status, apiErr.Name, apiErr.Message) } ``` `err.Error()` formats as `tryiton: ()`. The SDK adds these names, all with `Status` `0`: `ProcessingError`, `Timeout`, `NetworkError` (no response, including an `http.Client` timeout), `ConfigError`, and `EncodeError`, `RequestError` and `DecodeError` for a request or response it can't build or read. `RateLimitExceeded`, `ConcurrencyLimitExceeded`, `500` and `503` are worth retrying with backoff. `OutOfCredits`, `400`, `403`, `404` and `413` are not. See [when to retry](/docs/concepts/errors#when-to-retry) and the full list of [error codes](/docs/concepts/errors). ## Verify webhooks [#verify-webhooks] `VerifyWebhook` (SDK 2.5 or later) checks that a [webhook](/docs/guides/webhooks) request came from TryItOn and returns the event. Pass the raw body exactly as it arrived. ```go http.HandleFunc("/webhooks/tryiton", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } event, err := tryiton.VerifyWebhook(body, r.Header, os.Getenv("TRYITON_WEBHOOK_SECRET")) if err != nil { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) if event.Type == "tryon.completed" { data, _ := event.TryOnData() log.Println(data.JobID, data.Output) } }) ``` `VerifyWebhook` returns a `*tryiton.WebhookEvent` whose `Data` is raw JSON; `TryOnData()` decodes it for the `tryon.*` events. On failure it returns a `*tryiton.Error` with `Name` `WebhookVerificationFailed` and `Status` 0. `VerifyWebhookWithOptions` takes a `VerifyWebhookOptions{Tolerance, Now}`. ## Live try-on from your server [#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`](/docs/sdks#live-try-on-in-the-browser) package and never sees the key. `*tryiton.LiveSessionStart` carries the API's JSON tags, so encoding it sends the response through unchanged. ```go title="main.go" package main import ( "context" "encoding/json" "log" "net/http" "os" tryiton "github.com/tryiton-now/tryiton-go/v2" ) func main() { client, err := tryiton.New(os.Getenv("TRYITON_API_KEY")) if err != nil { log.Fatal(err) } // Once per product, for example at catalog sync. Store garment.ID. garment, err := client.PrepareLiveGarment(context.Background(), tryiton.PrepareLiveGarmentParams{ GarmentImage: "https://example.com/tshirt.jpg", Category: "clothing", Subcategory: "tops", }) if err != nil { log.Fatal(err) } log.Println("prepared", garment.ID) // The browser POSTs {"garmentId": "..."} and passes the response to connectLiveTryOn. http.HandleFunc("/live-session", func(w http.ResponseWriter, r *http.Request) { var body struct { GarmentID string `json:"garmentId"` } _ = json.NewDecoder(r.Body).Decode(&body) // a missing body starts without a garment start, err := client.StartLiveSession(r.Context(), tryiton.StartLiveSessionParams{ GarmentID: body.GarmentID, EndUserID: "shopper-42", // your signed-in shopper's id, from your session AllowedOrigin: "https://shop.example.com", }) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(start) // unchanged }) log.Fatal(http.ListenAndServe(":3000", nil)) } ``` `EndUserID` gives each shopper one stream: starting again ends the previous one. `AllowedOrigin` locks the media token to your site. Sessions start on the primary stream and switch to the backup stream if it fails to connect. `PrepareLiveOutfit` with `GarmentIDs` 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](/docs/guides/live-tryon-quickstart), and billing in [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Testing [#testing] Point the client at an `httptest.Server` to test your code without network calls or credits: ```go title="tryon_test.go" package main import ( "context" "net/http" "net/http/httptest" "testing" tryiton "github.com/tryiton-now/tryiton-go/v2" ) func TestTryOnFashion(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost || r.URL.Path != "/tryon/fashion" { t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) } w.WriteHeader(http.StatusCreated) w.Write([]byte(`{"ok":true,"jobId":"job_123"}`)) })) defer srv.Close() client, _ := tryiton.New("YOUR_API_KEY", tryiton.WithBaseURL(srv.URL), tryiton.WithHTTPClient(srv.Client())) jobID, err := client.TryOnFashion(context.Background(), tryiton.FashionParams{ ModelImage: "https://example.com/model.jpg", GarmentImage: "https://example.com/tshirt.jpg", }) if err != nil || jobID != "job_123" { t.Fatalf("got %q, %v", jobID, err) } } ``` Answer `{"ok":false,"error":{"name":"...","message":"..."}}` with a `4xx` status to test your error handling. # Virtual Try-On SDKs for Node.js, Python, Go, PHP & Ruby (/docs/sdks) TryItOn publishes an official virtual try-on SDK for Node.js, Python, Go, PHP and Ruby. Each one wraps every server endpoint of `https://tryiton.now/api/v1`, sends your API key, turns error responses into one error class, and has a wait helper that polls a job until it finishes. This page compares them. Each language page is the full reference. To run your first try-on, follow the [Quickstart](/docs/getting-started/quickstart). ## Packages [#packages] | Language | Package | Latest | Install | Minimum runtime | Source | | -------- | ------- | ------ | ------- | --------------- | ------ | | Node.js / TypeScript | [`tryiton`](https://www.npmjs.com/package/tryiton) (npm) | 2.5.1 | `npm install tryiton` | Node.js 18 | [tryiton-now/tryiton-node](https://github.com/tryiton-now/tryiton-node) | | Python | [`tryiton`](https://pypi.org/project/tryiton/) (PyPI) | 2.5.1 | `pip install tryiton` | Python 3.8 | [tryiton-now/tryiton-python](https://github.com/tryiton-now/tryiton-python) | | Go | [`github.com/tryiton-now/tryiton-go/v2`](https://pkg.go.dev/github.com/tryiton-now/tryiton-go/v2) | 2.5.1 | `go get github.com/tryiton-now/tryiton-go/v2` | Go 1.20 | [tryiton-now/tryiton-go](https://github.com/tryiton-now/tryiton-go) | | PHP | [`tryiton/tryiton`](https://packagist.org/packages/tryiton/tryiton) (Packagist) | 2.5.1 | `composer require tryiton/tryiton` | PHP 7.4, `ext-curl`, `ext-json` | [tryiton-now/tryiton-php](https://github.com/tryiton-now/tryiton-php) | | Ruby | [`tryiton`](https://rubygems.org/gems/tryiton) (RubyGems) | 2.5.1 | `gem install tryiton` | Ruby 2.6 | [tryiton-now/tryiton-ruby](https://github.com/tryiton-now/tryiton-ruby) | The Python SDK depends on `requests`. The others use only their standard library (and `ext-curl` in PHP). Every SDK sends `User-Agent: tryiton-/`, so we can tell versions apart when you ask for help. ## Client options [#client-options] Every client takes your API key and three optional settings: the base URL, a request timeout, and your own HTTP layer (for retries, logging, a proxy or a test stub). | Language | Constructor | Base URL | Request timeout (default) | Custom HTTP layer | | -------- | ----------- | -------- | ------------------------- | ----------------- | | Node.js | `new TryItOn({ apiKey, ... })` | `baseUrl` | `timeoutMs`, ms (60000) | `fetch`: a `fetch`-compatible function | | Python | `TryItOn(api_key, ...)` | `base_url=` | `timeout=`, seconds (60) | `session=`: a `requests.Session` | | Go | `tryiton.New(apiKey, opts...)` returns `(*Client, error)` | `tryiton.WithBaseURL(u)` | set on your `*http.Client` (60 s) | `tryiton.WithHTTPClient(h)`: an `*http.Client` | | PHP | `new Client($apiKey, $baseUrl, $timeout, $transport)` | 2nd argument | 3rd argument, seconds (60) | 4th argument: a `TryItOn\HttpTransport` | | Ruby | `Tryiton::Client.new(api_key:, ...)` | `base_url:` | `timeout:`, seconds (60) | `transport:`: any object with `call(request)` | The default base URL is `https://tryiton.now/api/v1`. The request timeout applies to each HTTP request, not to a whole wait. A missing API key fails at construction with the error name `ConfigError`. ## Methods [#methods] Method names follow each language's convention. The photo try-on methods return the job id as a string. | Endpoint | Node.js / PHP | Python / Ruby | Go | | -------- | ------------- | ------------- | -- | | `POST /tryon/fashion` | `tryOnFashion` | `try_on_fashion` | `TryOnFashion` | | `POST /tryon/hairstyle` | `tryOnHairstyle` | `try_on_hairstyle` | `TryOnHairstyle` | | `POST /tryon/tattoo` | `tryOnTattoo` | `try_on_tattoo` | `TryOnTattoo` | | `GET /status/{id}` | `getStatus` | `get_status` | `GetStatus` | | polls `GET /status/{id}` | `waitForResult` | `wait_for_result` | `WaitForResult` | | `GET /credits` | `getCredits` | `get_credits` | `GetCredits` | | `GET /live/config` | `getLiveConfig` | `get_live_config` | `GetLiveConfig` | | `POST /live/garments` | `prepareLiveGarment` | `prepare_live_garment` | `PrepareLiveGarment` | | `POST /live/outfits` | `prepareLiveOutfit` | `prepare_live_outfit` | `PrepareLiveOutfit` | | `POST /live/sessions` | `startLiveSession` | `start_live_session` | `StartLiveSession` | | `GET /live/sessions` | `listLiveSessions` | `list_live_sessions` | `ListLiveSessions` | | `GET /live/sessions/{id}` | `getLiveSession` | `get_live_session` | `GetLiveSession` | | `POST /live/sessions/{id}/stop` | `stopLiveSession` | `stop_live_session` | `StopLiveSession` | Parameter names match the API's, in each language's casing: `modelImage` in Node.js and Go (`ModelImage`), `model_image` in Python, PHP and Ruby. Unset options are left out of the request, so the API defaults apply. Every SDK raises (or, in Go, returns) one error type with the HTTP status and the API's error name; see [Errors in the SDKs](/docs/concepts/errors#errors-in-the-sdks). ## Wait helpers [#wait-helpers] The wait helper calls `GET /status/{id}` until the job is `completed` (it returns the result URLs) or `failed` (it raises `ProcessingError`). It polls every 2 seconds by default and gives up after 120 seconds with `Timeout`. | Language | Signature | Wait for a final status | | -------- | --------- | ----------------------- | | Node.js | `waitForResult(jobId, { pollIntervalMs, timeoutMs, signal })` | `{ timeoutMs: 240_000 }` (ms) | | Python | `wait_for_result(job_id, *, poll_interval=2.0, timeout=120.0)` | `timeout=240` (seconds) | | Go | `WaitForResult(ctx, jobID, pollInterval)` | `context.WithTimeout(ctx, 4*time.Minute)` | | PHP | `waitForResult($jobId, $pollInterval = 2.0, $timeout = 120.0)` | `waitForResult($jobId, 2.0, 240.0)` (seconds) | | Ruby | `wait_for_result(job_id, poll_interval: 2.0, timeout: 120.0)` | `timeout: 240` (seconds) | Go's `WaitForResult` has no timeout of its own: it polls until the job finishes or the context ends. A wait timeout only stops waiting; the job keeps running. See [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling). ## Verify webhooks [#verify-webhooks] From 2.5, every SDK verifies [webhook](/docs/guides/webhooks) signatures and returns the event. Pass the raw request body and your `whsec_` signing secret. A request that fails raises the SDK's error type with the name `WebhookVerificationFailed`: answer it with `400`. | Language | Call | | -------- | ---- | | Node.js | `await verifyWebhook(rawBody, req.headers, secret)` | | Python | `verify_webhook(raw_body, request.headers, secret)` | | Go | `tryiton.VerifyWebhook(body, r.Header, secret)` | | PHP | `Webhook::verify($rawBody, $_SERVER, $secret)` | | Ruby | `Tryiton.verify_webhook(raw_body, request.env, secret)` | ## Live try-on in the browser [#live-try-on-in-the-browser] The server SDKs only run the server side of [live try-on](/docs/api-reference/live-tryon): they prepare garments and start, read and stop sessions with your API key. The shopper's browser streams with a separate npm package, [`tryiton-live`](https://www.npmjs.com/package/tryiton-live) (an ES module for bundlers, latest 0.4.1): ```bash npm install tryiton-live ``` It exports `openCamera` and `connectLiveTryOn`. You pass `connectLiveTryOn` the `startLiveSession` response from your server, and the returned session object has `switchGarment` and `end`. The browser never sees your API key. See the [Real-Time Virtual Try-On Quickstart](/docs/guides/live-tryon-quickstart) and [Live Try-On Browser Endpoints](/docs/api-reference/live-tryon-browser-endpoints). # Virtual Try-On SDK for Node.js (/docs/sdks/node) The [`tryiton`](https://www.npmjs.com/package/tryiton) package is the official Node.js and TypeScript client for the virtual try-on API. It wraps every server endpoint of `https://tryiton.now/api/v1`, throws one error class, and polls jobs for you. New to the API? Run your first try-on with the [Quickstart](/docs/getting-started/quickstart). ```bash npm install tryiton ``` It needs Node.js 18 or later (it uses the global `fetch`) and ships TypeScript types, an ES module build and a CommonJS build (`const { TryItOn } = require("tryiton");`). The samples use `import` and top-level `await`, so save them as `.mjs` or set `"type": "module"` in `package.json`. ## Configure the client [#configure-the-client] 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. ```js title="client.mjs" import { TryItOn } from "tryiton"; // Retry GETs (status, credits, sessions) on gateway errors. Never retry a POST: // a retried submit can create a second job. async function fetchWithRetry(url, init = {}) { for (let attempt = 1; ; attempt++) { const res = await fetch(url, init); const isRetryable = (init.method ?? "GET") === "GET" && [502, 503, 504].includes(res.status); if (!isRetryable || attempt === 3) return res; await res.body?.cancel(); // free the connection before the next attempt await new Promise((resolve) => setTimeout(resolve, attempt * 1000)); } } const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY, timeoutMs: 30_000, fetch: fetchWithRetry, }); console.log(await client.getCredits()); ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `apiKey` | `string` | required | Your API key. A missing key throws `TryItOnError` with `errorName: "ConfigError"`. | | `baseUrl` | `string` | `https://tryiton.now/api/v1` | API base URL. A trailing slash is removed. | | `timeoutMs` | `number` | `60000` | Timeout for each HTTP request, in milliseconds. A wait has its own timeout. | | `fetch` | `(url, init) => Promise` | `globalThis.fetch` | Your own `fetch`, for retries, logging, a proxy or a test stub. | ## Methods [#methods] Every method is `async`. Parameters are one object with camelCase keys; unset keys are left out of the request, so the API defaults apply. | Method | Endpoint | Resolves to | | ------ | -------- | ----------- | | `tryOnFashion(params)` | [`POST /tryon/fashion`](/docs/api-reference/fashion-tryon) | job id (`string`) | | `tryOnHairstyle(params)` | [`POST /tryon/hairstyle`](/docs/api-reference/hairstyle-tryon) | job id (`string`) | | `tryOnTattoo(params)` | [`POST /tryon/tattoo`](/docs/api-reference/tattoo-tryon) | job id (`string`) | | `getStatus(jobId)` | [`GET /status/{id}`](/docs/api-reference/job-status) | `StatusResponse` (`status`, `output`, `error`) | | `waitForResult(jobId, opts)` | polls `GET /status/{id}` | result URLs (`string[]`) | | `getCredits()` | [`GET /credits`](/docs/api-reference/credits-balance) | `Credits` | | `getLiveConfig()` | [`GET /live/config`](/docs/api-reference/live-tryon) | `LiveConfig` | | `prepareLiveGarment(params)` | [`POST /live/garments`](/docs/api-reference/live-garments) | `LiveGarment` | | `prepareLiveOutfit(params)` | [`POST /live/outfits`](/docs/api-reference/live-garments) | `LiveGarment` | | `startLiveSession(params)` | [`POST /live/sessions`](/docs/api-reference/live-sessions) | `LiveSessionStart` | | `listLiveSessions(params)` | [`GET /live/sessions`](/docs/api-reference/live-sessions) | `LiveSessionPage` (`sessions`, `nextCursor`) | | `getLiveSession(sessionId)` | [`GET /live/sessions/{id}`](/docs/api-reference/live-sessions) | `LiveSession` | | `stopLiveSession(sessionId)` | [`POST /live/sessions/{id}/stop`](/docs/api-reference/live-sessions) | `LiveSession` | The package also exports `HAIRCUTS` (the 42 accepted `haircut` values), `VERSION`, and a type for every parameter object and response. Images are public URLs or base64 data URLs. The snippets below reuse the `client` from above. ```js const fashionJobId = await client.tryOnFashion({ modelImage: "https://example.com/model.jpg", garmentImage: "https://example.com/tshirt.jpg", category: "clothing", subcategory: "tops", }); const hairJobId = await client.tryOnHairstyle({ faceImage: "https://example.com/face.jpg", haircut: "PixieCut", hairColor: "copper red", }); const tattooJobId = await client.tryOnTattoo({ bodyImage: "https://example.com/forearm.jpg", designImage: "https://example.com/rose.png", region: { x: 0.32, y: 0.18, w: 0.28, h: 0.34 }, }); ``` ## Wait for results [#wait-for-results] `waitForResult(jobId, { pollIntervalMs, timeoutMs, signal })` polls every 2000 ms and gives up after 120000 ms. It resolves with the result URLs, or throws `ProcessingError` (the job failed), `Timeout` or `Aborted` (the `signal` fired). Every job has a final status within 4 minutes, so a 4-minute wait never gives up early: ```js const urls = await client.waitForResult(fashionJobId, { timeoutMs: 240_000 }); ``` `Timeout` and `Aborted` only stop the wait. The job keeps running, so poll it later instead of resubmitting. To check a stored job id from a worker, call `getStatus` yourself: ```js const job = await client.getStatus(fashionJobId); if (job.status === "completed") console.log(job.output); else if (job.status === "failed") console.error(job.error); ``` `error` is the failure reason as a string, or `null`. See [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) for job lifetimes. ## Errors [#errors] Every API error and failed job throws `TryItOnError`. Branch on `errorName`, not on the message. | Field | Type | Description | | ----- | ---- | ----------- | | `status` | `number` or `null` | HTTP status. `null` for errors raised by the SDK. | | `errorName` | `string` or `null` | The API error name, such as `OutOfCredits`, or an SDK name below. `null` for a non-JSON error page. | | `message` | `string` | Human-readable text. For `ProcessingError`, the job's failure reason. | ```js import { TryItOnError } from "tryiton"; try { const urls = await client.waitForResult(fashionJobId, { timeoutMs: 240_000 }); console.log(urls[0]); } catch (err) { if (!(err instanceof TryItOnError)) throw err; if (err.errorName === "ProcessingError") console.error("Failed, not charged:", err.message); else if (err.errorName === "Timeout") console.error("Still running. Poll it later."); else console.error(`${err.status} ${err.errorName}: ${err.message}`); } ``` The SDK adds these names, all with `status: null`: `ProcessingError`, `Timeout` (the wait gave up, or one request hit `timeoutMs`), `Aborted`, `NetworkError` (no response) and `ConfigError`. `RateLimitExceeded`, `ConcurrencyLimitExceeded`, `500` and `503` are worth retrying with backoff. `OutOfCredits`, `400`, `403`, `404` and `413` are not. See [when to retry](/docs/concepts/errors#when-to-retry) and the full list of [error codes](/docs/concepts/errors). ## Verify webhooks [#verify-webhooks] `verifyWebhook` (SDK 2.5 or later) checks that a [webhook](/docs/guides/webhooks) request came from TryItOn and returns the event. Pass the raw body exactly as it arrived. ```js import express from "express"; import { verifyWebhook, TryItOnError } from "tryiton"; const app = express(); // express.raw keeps the exact bytes that were signed. app.post("/webhooks/tryiton", express.raw({ type: "application/json" }), async (req, res) => { let event; try { event = await verifyWebhook(req.body, req.headers, process.env.TRYITON_WEBHOOK_SECRET); } catch (err) { if (err instanceof TryItOnError) return res.sendStatus(400); throw err; } res.sendStatus(200); if (event.type === "tryon.completed") console.log(event.data.jobId, event.data.output); }); ``` `verifyWebhook(payload, headers, secret, { toleranceSeconds, now })` is async. `payload` is a string, `Buffer` or `Uint8Array`; `headers` is `req.headers` or a `Headers` object. It throws `TryItOnError` with `errorName: "WebhookVerificationFailed"` and `status: null`. It uses Web Crypto, so it also runs on edge runtimes, Deno and Bun. ## Live try-on from your server [#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`](/docs/sdks#live-try-on-in-the-browser) package and never sees the key. ```js title="server.mjs" import express from "express"; import { TryItOn, TryItOnError } from "tryiton"; const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY }); // Once per product, for example at catalog sync. Store garment.id. const garment = await client.prepareLiveGarment({ garmentImage: "https://example.com/tshirt.jpg", category: "clothing", subcategory: "tops", }); const app = express(); app.use(express.json()); // The browser POSTs { garmentId } and passes the response to connectLiveTryOn. app.post("/live-session", async (req, res) => { try { const start = await client.startLiveSession({ garmentId: req.body.garmentId, endUserId: "shopper-42", // your signed-in shopper's id, from your session allowedOrigin: "https://shop.example.com", }); res.json(start); // unchanged } catch (err) { const status = err instanceof TryItOnError && err.status ? err.status : 502; res.status(status).json({ ok: false, error: { name: err.errorName, message: err.message } }); } }); app.listen(3000); ``` `endUserId` gives each shopper one stream: starting again ends the previous one. `allowedOrigin` locks the media token to your site. Sessions start on the primary stream and switch to the backup stream if it fails to connect. `prepareLiveOutfit({ garmentIds })` 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](/docs/guides/live-tryon-quickstart), and billing in [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Testing [#testing] Pass a stub `fetch` to test your code without network calls or credits: ```js title="client.test.mjs" import assert from "node:assert"; import { TryItOn } from "tryiton"; const calls = []; const client = new TryItOn({ apiKey: "YOUR_API_KEY", fetch: async (url, init) => { calls.push({ url, method: init.method, body: JSON.parse(init.body) }); return new Response(JSON.stringify({ ok: true, jobId: "job_123" }), { status: 201 }); }, }); const jobId = await client.tryOnFashion({ modelImage: "https://example.com/model.jpg", garmentImage: "https://example.com/tshirt.jpg", }); assert.equal(jobId, "job_123"); assert.equal(calls[0].url, "https://tryiton.now/api/v1/tryon/fashion"); assert.equal(calls[0].body.model_image, "https://example.com/model.jpg"); ``` Return `{ ok: false, error: { name, message } }` with a `4xx` status to test your error handling. # Virtual Try-On SDK for PHP (/docs/sdks/php) The [`tryiton/tryiton`](https://packagist.org/packages/tryiton/tryiton) Composer package is the official PHP client for the virtual try-on API. It wraps every server endpoint of `https://tryiton.now/api/v1`, throws one exception class, and polls jobs for you. New to the API? Run your first try-on with the [Quickstart](/docs/getting-started/quickstart). ```bash composer require tryiton/tryiton ``` It needs PHP 7.4 or later with the `curl` and `json` extensions. Classes live in the `TryItOn` namespace and load through Composer's autoloader. ## Configure the client [#configure-the-client] 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. `new Client($apiKey, $baseUrl, $timeout, $transport)` takes positional arguments; only the key is required. A transport is any class that implements `TryItOn\HttpTransport`: it sends one request and returns the status and raw body. ```php title="client.php" inner = $inner; } public function send(string $method, string $url, array $headers, ?string $body): array { for ($attempt = 1; ; $attempt++) { $response = $this->inner->send($method, $url, $headers, $body); $isRetryable = $method === 'GET' && in_array($response['status'], [502, 503, 504], true); if (!$isRetryable || $attempt === 3) { return $response; } sleep($attempt); } } } $client = new Client( getenv('TRYITON_API_KEY'), 'https://tryiton.now/api/v1', 60, new RetryGetsTransport(new CurlTransport(30)) ); print_r($client->getCredits()); ``` | Argument | Type | Default | Description | | -------- | ---- | ------- | ----------- | | `$apiKey` | `string` | required | Your API key. An empty key throws `TryItOnException` with `errorName` `ConfigError`. | | `$baseUrl` | `string` | `https://tryiton.now/api/v1` | API base URL. A trailing slash is removed. | | `$timeout` | `int` | `60` | Timeout for each request, in seconds, for the default cURL transport. Ignored when you pass `$transport`. | | `$transport` | `?TryItOn\HttpTransport` | `CurlTransport` | Your own transport for retries, logging, a proxy, a PSR-18 client or a test stub. `send()` returns `['status' => int, 'body' => string]`. | ## Methods [#methods] Parameters are one array with the API's snake_case keys; `null` values are left out, so the API defaults apply. The live methods also accept camelCase keys (`garmentId`, `endUserId`). Responses are plain arrays, with the API's camelCase keys for the live methods. | Method | Endpoint | Returns | | ------ | -------- | ------- | | `tryOnFashion(array $params)` | [`POST /tryon/fashion`](/docs/api-reference/fashion-tryon) | job id (`string`) | | `tryOnHairstyle(array $params)` | [`POST /tryon/hairstyle`](/docs/api-reference/hairstyle-tryon) | job id (`string`) | | `tryOnTattoo(array $params)` | [`POST /tryon/tattoo`](/docs/api-reference/tattoo-tryon) | job id (`string`) | | `getStatus(string $jobId)` | [`GET /status/{id}`](/docs/api-reference/job-status) | `['status', 'output', 'error']` | | `waitForResult($jobId, $pollInterval, $timeout)` | polls `GET /status/{id}` | result URLs (`list`) | | `getCredits()` | [`GET /credits`](/docs/api-reference/credits-balance) | credit balance array | | `getLiveConfig()` | [`GET /live/config`](/docs/api-reference/live-tryon) | config array | | `prepareLiveGarment(array $params)` | [`POST /live/garments`](/docs/api-reference/live-garments) | garment array | | `prepareLiveOutfit(array $params)` | [`POST /live/outfits`](/docs/api-reference/live-garments) | garment array | | `startLiveSession(array $params = [])` | [`POST /live/sessions`](/docs/api-reference/live-sessions) | full response array | | `listLiveSessions(array $params = [])` | [`GET /live/sessions`](/docs/api-reference/live-sessions) | `['sessions', 'nextCursor']` | | `getLiveSession(string $sessionId)` | [`GET /live/sessions/{id}`](/docs/api-reference/live-sessions) | session array | | `stopLiveSession(string $sessionId)` | [`POST /live/sessions/{id}/stop`](/docs/api-reference/live-sessions) | session array | `Client::HAIRCUTS` lists the 42 accepted `haircut` values, and `Client::VERSION` is the SDK version. Response shapes are declared as PHPStan types on `Client`. Images are public URLs or base64 data URLs. The snippets below reuse the `$client` from above. ```php $fashionJobId = $client->tryOnFashion([ 'model_image' => 'https://example.com/model.jpg', 'garment_image' => 'https://example.com/tshirt.jpg', 'category' => 'clothing', 'subcategory' => 'tops', ]); $hairJobId = $client->tryOnHairstyle([ 'face_image' => 'https://example.com/face.jpg', 'haircut' => 'PixieCut', 'hair_color' => 'copper red', ]); $tattooJobId = $client->tryOnTattoo([ '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-results] `waitForResult(string $jobId, float $pollInterval = 2.0, float $timeout = 120.0)` polls every 2 seconds and gives up after 120 seconds. It returns the result URLs, or throws `ProcessingError` (the job failed) or `Timeout`. Every job has a final status within 4 minutes, so a 4-minute wait never gives up early. Check `max_execution_time` too when you wait inside a web request. ```php $urls = $client->waitForResult($fashionJobId, 2.0, 240.0); ``` `Timeout` only stops the wait. The job keeps running, so poll it later instead of resubmitting. To check a stored job id from a cron job or queue worker, call `getStatus` yourself: ```php $job = $client->getStatus($fashionJobId); if ($job['status'] === 'completed') { print_r($job['output']); } elseif ($job['status'] === 'failed') { echo 'Failed: ', $job['error'], PHP_EOL; } ``` `output` is an empty array until the job completes, and `error` is the failure reason as a string, or `null`. See [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) for job lifetimes. ## Errors [#errors] Every API error and failed job throws `TryItOn\TryItOnException`. Branch on `errorName`, not on the message. | Property | Type | Description | | -------- | ---- | ----------- | | `$e->status` | `?int` | HTTP status. `null` for errors raised by the SDK. | | `$e->errorName` | `?string` | The API error name, such as `OutOfCredits`, or an SDK name below. `null` for a non-JSON error page. | | `$e->getMessage()` | `string` | Human-readable text. For `ProcessingError`, the job's failure reason. | ```php use TryItOn\TryItOnException; try { $urls = $client->waitForResult($fashionJobId, 2.0, 240.0); echo $urls[0], PHP_EOL; } catch (TryItOnException $e) { if ($e->errorName === 'ProcessingError') { echo 'Failed, not charged: ', $e->getMessage(), PHP_EOL; } elseif ($e->errorName === 'Timeout') { echo 'Still running. Poll it later.', PHP_EOL; } else { echo "{$e->status} {$e->errorName}: {$e->getMessage()}", PHP_EOL; } } ``` The SDK adds these names, all with `status` `null`: `ProcessingError`, `Timeout` (the wait gave up), `NetworkError` (no response, including a cURL timeout, or any exception your transport throws), `ConfigError`, `InvalidRequest` (the body can't be encoded as JSON) and `InvalidResponse` (a success response without the expected field). `RateLimitExceeded`, `ConcurrencyLimitExceeded`, `500` and `503` are worth retrying with backoff. `OutOfCredits`, `400`, `403`, `404` and `413` are not. See [when to retry](/docs/concepts/errors#when-to-retry) and the full list of [error codes](/docs/concepts/errors). ## Verify webhooks [#verify-webhooks] `Webhook::verify` (SDK 2.5 or later) checks that a [webhook](/docs/guides/webhooks) request came from TryItOn and returns the event. Pass the raw body exactly as it arrived. ```php use TryItOn\TryItOnException; use TryItOn\Webhook; try { $event = Webhook::verify(file_get_contents('php://input'), $_SERVER, getenv('TRYITON_WEBHOOK_SECRET')); } catch (TryItOnException $e) { http_response_code(400); exit; } http_response_code(200); if ($event['type'] === 'tryon.completed') { error_log($event['data']['jobId']); } ``` `Webhook::verify($payload, $headers, $secret, $toleranceSeconds = 300, $now = null)` returns the event as an array. Headers can be `$_SERVER`, `getallheaders()` or a PSR-7 request's `getHeaders()`. It throws `TryItOnException` with `errorName` `"WebhookVerificationFailed"` and a `null` status. ## Live try-on from your server [#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`](/docs/sdks#live-try-on-in-the-browser) package and never sees the key. Prepare each garment once, for example at catalog sync, and store its `id`: ```php $garment = $client->prepareLiveGarment([ 'garment_image' => 'https://example.com/tshirt.jpg', 'category' => 'clothing', 'subcategory' => 'tops', ]); ``` Then start a session per shopper and send the response to the browser unchanged: ```php title="live-session.php" startLiveSession([ 'garment_id' => $body['garmentId'] ?? null, 'end_user_id' => 'shopper-42', // your signed-in shopper's id, from your session 'allowed_origin' => 'https://shop.example.com', ]); echo json_encode($start); // unchanged } catch (TryItOnException $e) { http_response_code($e->status ?? 502); echo json_encode(['ok' => false, 'error' => ['name' => $e->errorName, 'message' => $e->getMessage()]]); } ``` `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. `prepareLiveOutfit(['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](/docs/guides/live-tryon-quickstart), and billing in [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Testing [#testing] Pass a stub transport to test your code without network calls or credits: ```php title="tests/TryOnTest.php" requests[] = ['method' => $method, 'url' => $url, 'body' => json_decode((string) $body, true)]; return ['status' => 201, 'body' => '{"ok":true,"jobId":"job_123"}']; } } final class TryOnTest extends TestCase { public function testTryOnFashion(): void { $transport = new StubTransport(); $client = new Client('YOUR_API_KEY', 'https://tryiton.now/api/v1', 60, $transport); $jobId = $client->tryOnFashion([ 'model_image' => 'https://example.com/model.jpg', 'garment_image' => 'https://example.com/tshirt.jpg', ]); $this->assertSame('job_123', $jobId); $this->assertSame('https://tryiton.now/api/v1/tryon/fashion', $transport->requests[0]['url']); } } ``` Return `{"ok":false,"error":{"name":"...","message":"..."}}` with a `4xx` status to test your error handling. # Virtual Try-On SDK for Python (/docs/sdks/python) The [`tryiton`](https://pypi.org/project/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](/docs/getting-started/quickstart). ```bash pip install tryiton ``` It needs Python 3.8 or later and uses [`requests`](https://pypi.org/project/requests/) for HTTP. The client is synchronous: each call blocks until the response arrives. The package ships type hints (`py.typed`). ## Configure the client [#configure-the-client] 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. ```python title="client.py" 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 [#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`](/docs/api-reference/fashion-tryon) | job id (`str`) | | `try_on_hairstyle(**kwargs)` | [`POST /tryon/hairstyle`](/docs/api-reference/hairstyle-tryon) | job id (`str`) | | `try_on_tattoo(**kwargs)` | [`POST /tryon/tattoo`](/docs/api-reference/tattoo-tryon) | job id (`str`) | | `get_status(job_id)` | [`GET /status/{id}`](/docs/api-reference/job-status) | `Status` dataclass (`status`, `output`, `error`) | | `wait_for_result(job_id, ...)` | polls `GET /status/{id}` | result URLs (`list[str]`) | | `get_credits()` | [`GET /credits`](/docs/api-reference/credits-balance) | `Credits` dataclass | | `get_live_config()` | [`GET /live/config`](/docs/api-reference/live-tryon) | `dict` | | `prepare_live_garment(garment_image, ...)` | [`POST /live/garments`](/docs/api-reference/live-garments) | garment `dict` | | `prepare_live_outfit(garment_ids, ...)` | [`POST /live/outfits`](/docs/api-reference/live-garments) | garment `dict` | | `start_live_session(**kwargs)` | [`POST /live/sessions`](/docs/api-reference/live-sessions) | full response `dict` | | `list_live_sessions(**kwargs)` | [`GET /live/sessions`](/docs/api-reference/live-sessions) | `dict` with `sessions`, `nextCursor` | | `get_live_session(session_id)` | [`GET /live/sessions/{id}`](/docs/api-reference/live-sessions) | session `dict` | | `stop_live_session(session_id)` | [`POST /live/sessions/{id}/stop`](/docs/api-reference/live-sessions) | session `dict` | The live methods return plain dicts with the API's camelCase keys, typed as `TypedDict`s (`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. ```python 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-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: ```python 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: ```python 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](/docs/concepts/jobs-and-polling) for job lifetimes. ## Errors [#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. | ```python 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](/docs/concepts/errors#when-to-retry) and the full list of [error codes](/docs/concepts/errors). ## Verify webhooks [#verify-webhooks] `verify_webhook` (SDK 2.5 or later) checks that a [webhook](/docs/guides/webhooks) request came from TryItOn and returns the event. Pass the raw body exactly as it arrived. ```python 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 "", 200 ``` `verify_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 [#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`](/docs/sdks#live-try-on-in-the-browser) package and never sees the key. ```python title="server.py" 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](/docs/guides/live-tryon-quickstart), and billing in [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Testing [#testing] Pass a mock `session` to test your code without network calls or credits. The client calls `session.request(method, url, headers=..., json=..., timeout=...)`: ```python title="test_tryon.py" 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`. # Virtual Try-On SDK for Ruby (/docs/sdks/ruby) The [`tryiton`](https://rubygems.org/gems/tryiton) gem is the official Ruby 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](/docs/getting-started/quickstart). ```bash gem install tryiton ``` Or add `gem "tryiton"` to your Gemfile. It needs Ruby 2.6 or later and uses only the standard library (`net/http` and `json`). ## Configure the client [#configure-the-client] 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. A transport is any object with `call(request)`. It gets a `Tryiton::Request` (`http_method`, `url`, `headers`, `body`) and returns an object with `status` and `body`, such as `Tryiton::Response`. ```ruby title="client.rb" require "tryiton" # Retry GETs (status, credits, sessions) on gateway errors. Never retry a POST: # a retried submit can create a second job. class RetryGetsTransport def initialize(inner) @inner = inner end def call(request) (1..3).each do |attempt| response = @inner.call(request) retryable = request.http_method == "GET" && [502, 503, 504].include?(response.status) return response if !retryable || attempt == 3 sleep(attempt) end end end client = Tryiton::Client.new( api_key: ENV["TRYITON_API_KEY"], transport: RetryGetsTransport.new(Tryiton::NetHTTPTransport.new(timeout: 30)) ) p client.get_credits ``` | Keyword | Type | Default | Description | | ------- | ---- | ------- | ----------- | | `api_key:` | `String` | required | Your API key. An empty or `nil` key raises `Tryiton::Error` with `error_name` `"ConfigError"`. | | `base_url:` | `String` | `"https://tryiton.now/api/v1"` | API base URL. A trailing slash is removed. | | `timeout:` | `Integer` | `60` | Open and read timeout for each request, in seconds. Ignored when you pass `transport:`. | | `transport:` | object with `call(request)` | `Tryiton::NetHTTPTransport` | Your own HTTP layer for retries, logging, a proxy or a test stub. | ## Methods [#methods] Parameters are snake_case keyword arguments; `nil` values are left out, so the API defaults apply. Responses are hashes with string keys, camelCase for the live methods. | Method | Endpoint | Returns | | ------ | -------- | ------- | | `try_on_fashion(**params)` | [`POST /tryon/fashion`](/docs/api-reference/fashion-tryon) | job id (`String`) | | `try_on_hairstyle(**params)` | [`POST /tryon/hairstyle`](/docs/api-reference/hairstyle-tryon) | job id (`String`) | | `try_on_tattoo(**params)` | [`POST /tryon/tattoo`](/docs/api-reference/tattoo-tryon) | job id (`String`) | | `get_status(job_id)` | [`GET /status/{id}`](/docs/api-reference/job-status) | `{ "status", "output", "error" }` | | `wait_for_result(job_id, ...)` | polls `GET /status/{id}` | result URLs (`Array`) | | `get_credits` | [`GET /credits`](/docs/api-reference/credits-balance) | credit balance hash | | `get_live_config` | [`GET /live/config`](/docs/api-reference/live-tryon) | config hash | | `prepare_live_garment(garment_image:, ...)` | [`POST /live/garments`](/docs/api-reference/live-garments) | garment hash | | `prepare_live_outfit(garment_ids:, ...)` | [`POST /live/outfits`](/docs/api-reference/live-garments) | garment hash | | `start_live_session(**params)` | [`POST /live/sessions`](/docs/api-reference/live-sessions) | full response hash | | `list_live_sessions(**params)` | [`GET /live/sessions`](/docs/api-reference/live-sessions) | `{ "sessions", "nextCursor" }` | | `get_live_session(session_id)` | [`GET /live/sessions/{id}`](/docs/api-reference/live-sessions) | session hash | | `stop_live_session(session_id)` | [`POST /live/sessions/{id}/stop`](/docs/api-reference/live-sessions) | session hash | `Tryiton::HAIRCUTS` lists the 42 accepted `haircut` values, and `Tryiton::VERSION` is the gem version. Images are public URLs or base64 data URLs. The snippets below reuse the `client` from above. ```ruby 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-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: ```ruby 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 background job (Sidekiq, Active Job), call `get_status` yourself: ```ruby job = client.get_status(fashion_job_id) case job["status"] when "completed" then p job["output"] when "failed" then warn "Failed: #{job["error"]}" end ``` `output` is an empty array until the job completes, and `error` is the failure reason as a string, or `nil`. See [Jobs, Polling & Retries](/docs/concepts/jobs-and-polling) for job lifetimes. ## Errors [#errors] Every API error and failed job raises `Tryiton::Error`. Branch on `error_name`, not on the message. | Method | Type | Description | | ------ | ---- | ----------- | | `status` | `Integer` or `nil` | HTTP status. `nil` for errors raised by the SDK. | | `error_name` | `String` or `nil` | The API error name, such as `OutOfCredits`, or an SDK name below. `nil` for a non-JSON error page. | | `message` | `String` | Human-readable text. For `ProcessingError`, the job's failure reason. | ```ruby begin urls = client.wait_for_result(fashion_job_id, timeout: 240) puts urls.first rescue Tryiton::Error => e case e.error_name when "ProcessingError" then warn "Failed, not charged: #{e.message}" when "Timeout" then warn "Still running. Poll it later." else warn "#{e.status} #{e.error_name}: #{e.message}" end end ``` The SDK adds these names, all with `status` `nil`: `ProcessingError`, `Timeout` (the wait gave up), `NetworkError` (no response, including a request timeout, or any exception your transport raises) and `ConfigError`. `RateLimitExceeded`, `ConcurrencyLimitExceeded`, `500` and `503` are worth retrying with backoff. `OutOfCredits`, `400`, `403`, `404` and `413` are not. See [when to retry](/docs/concepts/errors#when-to-retry) and the full list of [error codes](/docs/concepts/errors). ## Verify webhooks [#verify-webhooks] `Tryiton.verify_webhook` (SDK 2.5 or later) checks that a [webhook](/docs/guides/webhooks) request came from TryItOn and returns the event. Pass the raw body exactly as it arrived. ```ruby require "sinatra" require "tryiton" post "/webhooks/tryiton" do begin event = Tryiton.verify_webhook(request.body.read, request.env, ENV.fetch("TRYITON_WEBHOOK_SECRET")) rescue Tryiton::Error halt 400 end puts event["data"]["jobId"] if event["type"] == "tryon.completed" status 200 end ``` `Tryiton.verify_webhook(payload, headers, secret, tolerance_seconds: 300, now: Time.now)` returns the event as a Hash with String keys. `headers` can be a Hash in any key case or a Rack env. It raises `Tryiton::Error` with `error_name` `"WebhookVerificationFailed"` and a `nil` status. ## Live try-on from your server [#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`](/docs/sdks#live-try-on-in-the-browser) package and never sees the key. ```ruby title="server.rb" require "json" require "sinatra" require "tryiton" client = Tryiton::Client.new(api_key: ENV["TRYITON_API_KEY"]) # Once per product, for example at catalog sync. Store garment["id"]. garment = client.prepare_live_garment( garment_image: "https://example.com/tshirt.jpg", category: "clothing", subcategory: "tops" ) # The browser POSTs {"garmentId": "..."} and passes the response to connectLiveTryOn. post "/live-session" do content_type :json body = JSON.parse(request.body.read) rescue {} begin start = client.start_live_session( garment_id: body["garmentId"], end_user_id: "shopper-42", # your signed-in shopper's id, from your session allowed_origin: "https://shop.example.com" ) JSON.generate(start) # unchanged rescue Tryiton::Error => e status(e.status || 502) JSON.generate(ok: false, error: { name: e.error_name, message: e.message }) end end ``` `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](/docs/guides/live-tryon-quickstart), and billing in [Live Try-On Billing](/docs/concepts/live-tryon-billing). ## Testing [#testing] A lambda has `call`, so it works as a stub transport. Test your code without network calls or credits: ```ruby title="test/tryon_test.rb" require "json" require "minitest/autorun" require "tryiton" class TryOnTest < Minitest::Test def test_try_on_fashion requests = [] transport = lambda do |request| requests << request Tryiton::Response.new(status: 201, body: '{"ok":true,"jobId":"job_123"}') end client = Tryiton::Client.new(api_key: "YOUR_API_KEY", transport: transport) job_id = client.try_on_fashion( model_image: "https://example.com/model.jpg", garment_image: "https://example.com/tshirt.jpg" ) assert_equal "job_123", job_id assert_equal "https://tryiton.now/api/v1/tryon/fashion", requests.first.url assert_equal "https://example.com/model.jpg", JSON.parse(requests.first.body)["model_image"] end end ``` Return `{"ok":false,"error":{"name":"...","message":"..."}}` with a `4xx` status to test your error handling.