Skip to Content
TryItOn
DocsAPI ReferenceSDKsResources

Virtual Try-On SDK for Ruby

Reference for the tryiton Ruby gem: client options, every method, wait helpers, Tryiton::Error handling, live sessions in Sinatra and transport stubs for tests.

The 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.

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

Retry GET requests only

A retried POST /tryon/* can create a second job and hold credits twice. The client below retries GET requests on 502, 503 and 504, and leaves every POST alone.

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.

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
KeywordTypeDefaultDescription
api_key:StringrequiredYour 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:Integer60Open and read timeout for each request, in seconds. Ignored when you pass transport:.
transport:object with call(request)Tryiton::NetHTTPTransportYour own HTTP layer for retries, logging, a proxy or a test stub.

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.

MethodEndpointReturns
try_on_fashion(**params)POST /tryon/fashionjob id (String)
try_on_hairstyle(**params)POST /tryon/hairstylejob id (String)
try_on_tattoo(**params)POST /tryon/tattoojob id (String)
get_status(job_id)GET /status/{id}{ "status", "output", "error" }
wait_for_result(job_id, ...)polls GET /status/{id}result URLs (Array<String>)
get_creditsGET /creditscredit balance hash
get_live_configGET /live/configconfig hash
prepare_live_garment(garment_image:, ...)POST /live/garmentsgarment hash
prepare_live_outfit(garment_ids:, ...)POST /live/outfitsgarment hash
start_live_session(**params)POST /live/sessionsfull response hash
list_live_sessions(**params)GET /live/sessions{ "sessions", "nextCursor" }
get_live_session(session_id)GET /live/sessions/{id}session hash
stop_live_session(session_id)POST /live/sessions/{id}/stopsession 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.

fashion_job_id = client.try_on_fashion(
  model_image: "https://example.com/model.jpg",
  garment_image: "https://example.com/tshirt.jpg",
  category: "clothing",
  subcategory: "tops"
)

hair_job_id = client.try_on_hairstyle(
  face_image: "https://example.com/face.jpg",
  haircut: "PixieCut",
  hair_color: "copper red"
)

tattoo_job_id = client.try_on_tattoo(
  body_image: "https://example.com/forearm.jpg",
  design_image: "https://example.com/rose.png",
  region: { x: 0.32, y: 0.18, w: 0.28, h: 0.34 }
)

Wait for results

wait_for_result(job_id, poll_interval: 2.0, timeout: 120.0) polls every 2 seconds and gives up after 120 seconds. It returns the result URLs, or raises ProcessingError (the job failed) or Timeout. Every job has a final status within 4 minutes, so a 4-minute wait never gives up early:

urls = client.wait_for_result(fashion_job_id, timeout: 240)

Timeout only stops the wait. The job keeps running, so poll it later instead of resubmitting. To check a stored job id from a background job (Sidekiq, Active Job), call get_status yourself:

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 for job lifetimes.

Errors

Every API error and failed job raises Tryiton::Error. Branch on error_name, not on the message.

MethodTypeDescription
statusInteger or nilHTTP status. nil for errors raised by the SDK.
error_nameString or nilThe API error name, such as OutOfCredits, or an SDK name below. nil for a non-JSON error page.
messageStringHuman-readable text. For ProcessingError, the job's failure reason.
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 and the full list of error codes.

Verify webhooks

Tryiton.verify_webhook (SDK 2.5 or later) checks that a webhook request came from TryItOn and returns the event. Pass the raw body exactly as it arrived.

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

Your server prepares garments and starts sessions with the API key. The shopper's browser streams with the tryiton-live package and never sees the key.

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, and billing in Live Try-On Billing.

Testing

A lambda has call, so it works as a stub transport. Test your code without network calls or credits:

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.

On this page