> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bitstudio.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate your first product photo

> Upload a garment, submit one generation, and retrieve the result with a complete Node.js example.

You need **Node.js 22 or later**, a JPEG, PNG, or WebP product photo, and a [Studio API key](https://docs.bitstudio.ai/api-reference/authentication.md) with access and credits for image generation. Running this example submits one generation and uses credits.

## 1. Set your API key

Set this variable in your server environment. Keep it out of source control:

```bash theme={null}
export BITSTUDIO_API_KEY='YOUR_API_KEY'
```

## 2. Save the example

Save the following as `generate.mjs`. It uploads your photo, submits to `POST /v1/images/generate` with an idempotency key, then checks the returned ID until the photo is ready. No npm packages are needed.

```javascript generate.mjs theme={null}
import { readFile, writeFile } from 'node:fs/promises';
import { basename, extname } from 'node:path';
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';

const key = process.env.BITSTUDIO_API_KEY;
const base = (process.env.BITSTUDIO_API_BASE_URL || 'https://api.bitstudio.ai').replace(/\/$/, '');
if (!key) throw new Error('Set BITSTUDIO_API_KEY on your server.');

async function request(path, { method = 'GET', body, idempotencyKey } = {}) {
  const isForm = body instanceof FormData;
  const response = await fetch(`${base}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${key}`,
      ...(!body || isForm ? {} : { 'Content-Type': 'application/json' }),
      ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
    },
    body: body ? (isForm ? body : JSON.stringify(body)) : undefined,
    signal: AbortSignal.timeout(60_000),
  });
  const text = await response.text();
  let data;
  try { data = JSON.parse(text); } catch { data = { message: text }; }
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${data.code || ''} ${data.message || data.error || 'Request failed'} (request ${data.request_id || 'unknown'})`);
  }
  return data;
}

async function waitForJob(id) {
  const deadline = Date.now() + 5 * 60_000;
  while (Date.now() < deadline) {
    const job = await request(`/v1/jobs/${encodeURIComponent(id)}`);
    if (job.status === 'completed') {
      if (!job.result?.url) throw new Error(`Job ${id} completed without a URL. Contact support.`);
      return job;
    }
    if (['failed', 'policy_blocked'].includes(job.status)) {
      throw new Error(`Job ${id}: ${job.error?.message || job.error?.code || job.status}`);
    }
    await sleep(5_000);
  }
  throw new Error(`Still processing. Resume: node generate.mjs --resume ${id}`);
}

let id;
if (process.argv[2] === '--resume') {
  id = process.argv[3];
  if (!id) throw new Error('Usage: node generate.mjs --resume JOB_ID');
} else {
  let saved;
  let receiptFile;
  if (process.argv[2] === '--retry') {
    receiptFile = process.argv[3];
    if (!receiptFile) throw new Error('Usage: node generate.mjs --retry REQUEST_FILE');
    saved = JSON.parse(await readFile(receiptFile, 'utf8'));
    // This example is intentionally conservative: finalized receipts may
    // expire after 24 hours. Resolve older or uncertain requests with support.
    if (Date.now() - saved.createdAt > 23 * 60 * 60_000) {
      throw new Error('This request is too old for automatic replay. Check Studio or contact support.');
    }
  } else {
    const filename = process.argv[2];
    if (!filename) throw new Error('Usage: node generate.mjs ./shirt.jpg');
    const types = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp' };
    const type = types[extname(filename).toLowerCase()];
    if (!type) throw new Error('Choose a JPEG, PNG, or WebP product photo.');
    const file = await readFile(filename);
    if (file.length > 15 * 1024 * 1024) throw new Error('Image must be no larger than 15 MiB.');
    const form = new FormData();
    form.append('file', new Blob([file], { type }), basename(filename));
    form.append('type', 'outfit');
    const upload = await request('/v1/images', { method: 'POST', body: form });
    if (upload.status !== 'completed') throw new Error(`Upload ${upload.id} is not ready.`);
    saved = {
      idempotencyKey: randomUUID(),
      createdAt: Date.now(),
      body: {
        model: 'nano-banana-2.1',
        model_text: 'An adult fashion model',
        outfit_image_ids: [upload.id],
        prompt: 'Full-length front view in a white studio, soft shadows.',
        aspect_ratio: '3:4',
      },
    };
    receiptFile = `bitstudio-request-${saved.idempotencyKey}.json`;
    // Persist before the paid POST. This file contains references, never the API key.
    await writeFile(receiptFile, JSON.stringify(saved, null, 2), { flag: 'wx', mode: 0o600 });
  }
  console.log(`If submission is interrupted: node generate.mjs --retry ${receiptFile}`);
  const { jobs } = await request('/v1/images/generate', {
    method: 'POST', body: saved.body, idempotencyKey: saved.idempotencyKey,
  });
  if (!Array.isArray(jobs) || jobs.length !== 1 || !jobs[0].id) {
    throw new Error(`Unexpected response. Retain ${receiptFile} and contact support.`);
  }
  id = jobs[0].id;
  console.log(`Job accepted: ${id}\nResume polling: node generate.mjs --resume ${id}`);
}

const result = await waitForJob(id);
console.log(`Result ID: ${result.result.id}\nResult: ${result.result.url}`);
```

## 3. Run it with a product photo

```bash theme={null}
node generate.mjs ./shirt.jpg
```

The script saves a request file before submission, then prints the accepted job ID and completed result URL. Open the result and compare the garment with your source before using it.

The five-minute polling deadline is a client choice, not a completion guarantee. If the image is still processing, resume with its saved ID:

```bash theme={null}
node generate.mjs --resume JOB_ID
```

If submission is interrupted before an ID is printed, use the saved request file to retry the same creation safely:

```bash theme={null}
node generate.mjs --retry bitstudio-request-REQUEST_KEY.json
```

Keep the same API key, workspace, base URL, and request file. The example allows replay within 23 hours of saving the request; older or uncertain submissions need investigation. A `request_in_progress` response means to retry the same request later or contact support. Do not generate a new key to bypass it.

For a specific person instead of a generated model, start with the [single-item try-on example](https://docs.bitstudio.ai/api-reference/try-on/single-item.md).

## Reuse a specific avatar or scene

The example describes an adult person in text. For a reusable identity, replace `model_text` with an avatar ID in `asset_ids`. Add a preset ID to the same array for a saved visual setup. Use `outfit_asset_ids` instead of an uploaded image when the product is saved in your wardrobe.

[Build a reusable asset workflow →](https://docs.bitstudio.ai/api-reference/assets-workflow.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.