Blog

Tutorial

How to Use Google Virtual Try-On via the HiAPI API: curl and Python Guide

Nov 10, 2026 11 min read
Abstract flat geometric prisms bisected into sage and pine-green planes on a deep green field; cover art for a developer tutorial.
On this page

What the google-virtual-try-on model expects

Before you write any code, it helps to understand the input contract. The google-virtual-try-on model is a two-image composition task: it takes one person/model image and one garment image, and produces an image of the person wearing that garment.

That means your preparation step is always the same shape:

  • A person image where the subject is clearly visible and reasonably framed — a full or upper-body shot works best, since the model needs to understand body geometry.
  • A garment image, ideally on a clean or plain background, showing the item you want transferred onto the person.

Both inputs are supplied as image URLs rather than raw binary in the request body. This keeps the request payload small and lets you keep your own storage layer (S3, GCS, a CDN) as the source of truth. Your job, then, is to make sure each URL is publicly reachable — or signed with a long-enough expiry — before you fire the call.

A few practical constraints to plan for:

  • Resolution and aspect ratio matter for the output quality. Very small thumbnails or heavily cropped inputs tend to produce poor results.
  • One garment per call. If your product page has multiple colorways, issue multiple calls rather than trying to pack several items into one request.
  • Pairing is your responsibility. The model does not validate that the garment "fits" the person; it composes what you give it. Good pairing (a full-body shot with a dress, an upper-body shot with a jacket) yields noticeably better output.

Think of this step as an asset contract: if you can reliably produce two good URLs per job, the rest of the integration is straightforward plumbing.

Setting up your HiAPI request

All HiAPI model calls follow the same shape, so once you have one working, the others are a parameter swap. Here is what you need for google-virtual-try-on.

Endpoint and method

Requests are sent as POST to the HiAPI model invocation endpoint for google-virtual-try-on. You use a single base URL and a single set of credentials across models, which is the main reason to route through HiAPI rather than wiring up each provider separately.

Authentication

Authenticate with your HiAPI API key in the Authorization header, using the standard bearer token format:

Authorization: Bearer $HIAPI_API_KEY

Keep the key server-side. Never ship it in a browser bundle or a mobile app — proxying through your own backend is both safer and gives you a place to add rate limiting and logging.

Content type

Send the body as JSON:

Content-Type: application/json

Request body

The body carries your model identifier and the two image URLs from the previous section — the person image and the garment image — along with any optional parameters the model exposes. The exact parameter names are the ones documented alongside the model; copy them verbatim rather than guessing, since a typo in a field name usually surfaces as a validation error rather than a helpful message.

Store your configuration

Put the base URL, model identifier, and key into environment variables so the same script works in staging and production without edits:

export HIAPI_API_KEY="your-key-here"
export HIAPI_BASE_URL="https://api.hiapi.ai"

That is the whole setup. No SDK, no per-provider onboarding.

A working curl request

The fastest way to confirm your key and payload are correct is a single curl call. Here is the anatomy of a request to google-virtual-try-on:

curl -X POST "$HIAPI_BASE_URL/v1/models/google-virtual-try-on" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google-virtual-try-on",
    "input": {
      "model_image": "https://your-cdn.example.com/person-001.jpg",
      "garment_image": "https://your-cdn.example.com/jacket-front.jpg"
    }
  }'

A few things to notice:

  • The two image fields sit inside an input object, keeping model-specific parameters namespaced and separate from routing fields.
  • The URLs must be reachable from the service, not from your laptop. A localhost or VPN-only address will fail.
  • There is no file upload step in this call. If your assets are not already on a CDN, upload them first and use the resulting URLs.

Run this once and inspect the raw JSON that comes back before you build anything on top of it. Piping the output through a formatter makes it easier to read:

curl -s -X POST "$HIAPI_BASE_URL/v1/models/google-virtual-try-on" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d @request.json | python -m json.tool

Keeping the body in a request.json file also avoids shell-quoting mistakes once your payload grows.

The same request in Python

For anything beyond a one-off test, move to Python. The example below uses only the standard library plus requests, so it drops into a script, a Lambda, or a small service with no extra framework.

import os
import requests

API_KEY = os.environ["HIAPI_API_KEY"]
BASE_URL = os.environ.get("HIAPI_BASE_URL", "https://api.hiapi.ai")


def try_on(person_url: str, garment_url: str, timeout: int = 120) -> dict:
    payload = {
        "model": "google-virtual-try-on",
        "input": {
            "model_image": person_url,
            "garment_image": garment_url,
        },
    }
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }
    response = requests.post(
        f"{BASE_URL}/v1/models/google-virtual-try-on",
        json=payload,
        headers=headers,
        timeout=timeout,
    )
    response.raise_for_status()
    return response.json()


if __name__ == "__main__":
    result = try_on(
        "https://your-cdn.example.com/person-001.jpg",
        "https://your-cdn.example.com/jacket-front.jpg",
    )
    print(result)

Notes on adapting this:

  • Set an explicit timeout. Image generation is not instantaneous; the default requests timeout is too aggressive for this class of call. Pick a value comfortably above your p99 latency.
  • Use json=payload, not data=json.dumps(payload). It sets the content type for you and avoids double-encoding bugs.
  • Return the parsed JSON, not the response object, so callers do not accidentally depend on HTTP internals. If you need status codes for metrics, capture them before returning.
  • Separate the client from the workflow. In a real service, the function above belongs in a thin client module; queueing, storage, and retries live a layer above it.

If you are already using httpx or an async framework, the translation is mechanical — the payload and headers are identical.

Reading the response

The response is JSON. Treat it as a small envelope with two concerns: did the job succeed, and where is the output?

Broadly, you should check:

  1. Transport status. A 2xx means the request was accepted and processed. A 4xx means your request was wrong; a 5xx means the service had a problem. Log the status code on every call — it is the cheapest observability you will ever add.
  2. Body fields. The payload carries the result of the generation. Image results are returned as URLs pointing at generated assets. The exact field names are the ones in the model's response schema; parse defensively rather than assuming a single string.
  3. Metadata. Any usage or timing fields in the response are worth capturing. Billing is metered by the platform, so persisting per-request metadata lets you reconcile your own logs against the dashboard later.

A robust parse looks like this:

data = try_on(person_url, garment_url)
outputs = data.get("output") or {}
image_url = outputs.get("image")
if not image_url:
    raise RuntimeError(f"No image in response: {data}")

What to do with the result

The returned URL is a generated asset, not a permanent one. Do not hand it straight to your frontend and forget about it. Instead:

  • Download and re-host. Fetch the bytes immediately and write them to your own bucket with a content-addressed key. This decouples your product from the generator's retention policy.
  • Record provenance. Store the input URLs, the model identifier, and a timestamp alongside the output. When a merchant asks why a try-on looks a certain way, you will want to reproduce the exact job.
  • Normalize the format. Resize and convert to your storefront's canonical format once, at ingestion, rather than on every page view.

Treating the response as an ephemeral handoff — parse, download, store, discard — is the pattern that scales.

Failure modes and retry strategy

Not all failures deserve a retry. Blindly retrying is how you turn a small upstream hiccup into a queue full of duplicate jobs and a surprising bill.

Classify before you retry

Do not retry — fix the request:

  • 400-class validation errors: malformed JSON, missing or misnamed fields, a body that is not the shape the model expects.
  • 401/403: bad or missing API key, or a key without access to the model. Retrying will never help.
  • 404: wrong model identifier or endpoint path.
  • Unreachable image URLs. If the person or garment URL 404s or times out at fetch time, the generation cannot proceed. Validate URLs before submitting.

Retry with backoff:

  • 429: you are being rate limited. Back off and respect the signal.
  • 5xx: transient service or upstream errors.
  • Network-level failures: connection resets, read timeouts.

Bounded retries with jitter

Cap the attempts — three is a common ceiling — and use exponential backoff with random jitter so a fleet of workers does not retry in lockstep:

import random, time

def with_retry(fn, attempts=3, base=1.0):
    for i in range(attempts):
        try:
            return fn()
        except requests.HTTPError as e:
            status = e.response.status_code if e.response is not None else None
            if status is not None and 400 <= status < 500 and status != 429:
                raise  # client error: do not retry
            if i == attempts - 1:
                raise
            time.sleep(base * (2 ** i) + random.uniform(0, 0.5))

Production guardrails

  • Idempotency at the job level. Hash the pair of input URLs into a job key. If the same key is already in flight or completed, return the stored result instead of resubmitting.
  • Dead-letter queue. After retries are exhausted, park the job with its full context instead of dropping it silently.
  • Circuit breaking. If the error rate crosses a threshold, stop submitting for a cooling period rather than hammering a struggling service.
  • Alert on shape, not just volume. A spike in 4xx after a deploy usually means someone renamed a field.

Validate inputs early

Most "model failures" are actually bad inputs. Do a cheap pre-flight: HEAD each URL, check content type and rough dimensions, and reject obviously unusable assets before you spend a metered call on them. This one habit removes the majority of your retry traffic.

Fitting it into a real pipeline

A single successful curl call is a demo. A reliable product feature needs a little more structure around it.

Structure the flow as stages

A workable decomposition:

  1. Ingest. Merchant or internal user submits a person image and a garment image. Store both in your object store and generate stable, signed URLs.
  2. Validate. Check reachability, format, and dimensions. Reject early with a clear message.
  3. Submit. Call google-virtual-try-on through the client module. Record the job key, model identifier, and input URLs in your database.
  4. Materialize. On success, download the generated image, convert to your canonical format, and write it to your CDN with a deterministic key.
  5. Publish. Update the job record to point at your hosted asset, and let the storefront read only from your own storage.

Each stage is independently retryable, which is what makes the whole thing debuggable. If step 4 fails, you do not need to re-run the generation.

Keep the client thin

Put the HTTP call in one small module, and put policy (retries, concurrency, timeouts, logging) around it. When HiAPI adds parameters to the model or you want to A/B a different image-gen route, you change one file.

Operational habits worth adopting

  • Async by default. Generation takes seconds, sometimes longer. Submit from a worker, not from a request handler that a user is waiting on.
  • Cache aggressively. The same person-plus-garment pair should never be generated twice. Content-address your outputs and check before submitting.
  • Budget with visibility. Because usage is metered by the platform, log per-request metadata and reconcile against your HiAPI dashboard on a schedule. Catch a runaway retry loop in hours, not at the end of the month.
  • Version your prompts and parameters. Store the parameter object with each job so you can reproduce results after a change.
  • Fail visibly to the user. A spinner that never resolves is worse than an honest "we could not generate this, try a different photo."

Where to go next

The same request shape works for other HiAPI image models, so the client you build here becomes the template for the rest of your pipeline. Once the two-image call is stable, browse the model catalog to see what else fits your workflow — the auth, error handling, and storage patterns all carry over unchanged.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs