Skip to Content
TryItOn
DocsAPI ReferenceSDKsResources

Virtual Try-On SDK for Go

Reference for the tryiton-go/v2 module: client options, every method, context timeouts, *tryiton.Error handling, live sessions in net/http and httptest stubs.

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

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

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.

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.

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)
}
OptionDefaultDescription
apiKey (argument)requiredYour 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

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.

MethodEndpointReturns
TryOnFashion(ctx, FashionParams)POST /tryon/fashionjob id (string)
TryOnHairstyle(ctx, HairstyleParams)POST /tryon/hairstylejob id (string)
TryOnTattoo(ctx, TattooParams)POST /tryon/tattoojob id (string)
GetStatus(ctx, jobID)GET /status/{id}*Status (Status, Output, Error)
WaitForResult(ctx, jobID, pollInterval)polls GET /status/{id}result URLs ([]string)
GetCredits(ctx)GET /credits*Credits
GetLiveConfig(ctx)GET /live/config*LiveConfig
PrepareLiveGarment(ctx, PrepareLiveGarmentParams)POST /live/garments*LiveGarment
PrepareLiveOutfit(ctx, PrepareLiveOutfitParams)POST /live/outfits*LiveGarment
StartLiveSession(ctx, StartLiveSessionParams)POST /live/sessions*LiveSessionStart
ListLiveSessions(ctx, ListLiveSessionsParams)GET /live/sessions*LiveSessionPage (Sessions, NextCursor)
GetLiveSession(ctx, sessionID)GET /live/sessions/{id}*LiveSession
StopLiveSession(ctx, sessionID)POST /live/sessions/{id}/stop*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.

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

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:

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:

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

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.

FieldTypeDescription
StatusintHTTP status. 0 for errors raised by the SDK.
NamestringThe API error name, such as OutOfCredits, or an SDK name below. Empty for a non-JSON error page.
MessagestringHuman-readable text. For ProcessingError, the job's failure reason.
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: <message> (<name>). 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 and the full list of error codes.

Verify webhooks

VerifyWebhook (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.

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

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. *tryiton.LiveSessionStart carries the API's JSON tags, so encoding it sends the response through unchanged.

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

Testing

Point the client at an httptest.Server to test your code without network calls or credits:

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.

On this page