Node.js · Sanal Giyim Deneme API'si

Node.js ile Sanal Giyim Deneme API'si

Henüz bir @photta/node paketi yok — ve ihtiyacınız da yok. Node 18+ sürümü `fetch` özelliğini native olarak sunar ve 20 satırlık bir yardımcı fonksiyon sizi yaklaşık beş dakika içinde ilk model üzerindeki görselinize ulaştırır.

Tek cümlede

Ortam değişkenlerinde `PHOTTA_API_KEY` değerini ayarlayın, `Authorization: Bearer photta_live_xxx` ile `https://ai.photta.app/api/v1` adresini çağıran küçük bir `phottaFetch()` yardımcısı yazın, bir ürün görseli URL'si, manken ID'si ve poz ID'si ile `/tryon/apparel` adresine POST yapın, ardından `status === 'completed'` olana kadar her 3 saniyede bir `/tryon/apparel/:id` adresini sorgulayın — genellikle 1.5–4 dakika sürer.

Güncellendi · 2026-04-19

İlk isteğiniz

Node.jsPythoncURLcURL
import { phottaFetch } from "./photta.js";

// 1. Submit the job — returns a generation ID immediately.
const created = await phottaFetch("/tryon/apparel", {
  method: "POST",
  body: JSON.stringify({
    product_type: "dress",
    product_images: ["https://example.com/dress.jpg"],
    mannequin_id: "mnq_athena_ts",
    pose_id: "pose_standing_front",
    resolution: "2K",
    aspect_ratio: "3:4",
  }),
});
const generationId = created.data.id;

// 2. Poll every 3 seconds until processing completes. Typical
// completion is 1.5–4 minutes; put an upper bound so a stuck
// job can't hang your request forever.
const pollInterval = 3000;
const maxAttempts = 120;     // 120 × 3s = 6 minutes
let result;

for (let i = 0; i < maxAttempts; i++) {
  result = await phottaFetch(`/tryon/apparel/${generationId}`);
  if (result.data.status === "completed") break;
  if (result.data.status === "failed") {
    throw new Error(result.data.error_message);
  }
  await new Promise((r) => setTimeout(r, pollInterval));
}

console.log("Result:", result.data.output_url);

Neler beklenmeli

Typical completion

1.5–4min

2K / 4K credits

5 / 7

Aspect ratios

5

Product types

6

Nasıl çalışır

Node.js ile Sanal Giyim Deneme API'si

Beş adım, kayıttan ilk görsele yaklaşık beş dakika.

  1. 01

    Adım 1

    Kaydolun ve bir anahtar oluşturun

    ai.photta.app adresinde bir hesap oluşturun. Panelin Geliştiriciler bölümünü açın, Generate API key butonuna tıklayın ve canlı anahtarı alın. `photta_live_` ile başlar ve ardından 32 onaltılık karakter gelir.

  2. 02

    Adım 2

    Anahtarı kaynak kodda değil, env'de saklayın

    `.env` dosyanıza (veya platformunuzun secret deposuna) `PHOTTA_API_KEY=...` ekleyin ve `process.env` üzerinden yükleyin. Anahtarı asla commit etmeyin; asla `'use client'` işaretli bir dosyaya import etmeyin — bundler onu tarayıcıya çekecektir.

  3. 03

    Adım 3

    Küçük bir fetch yardımcısı yazın

    `fetch()` etrafındaki 20 satırlık bir wrapper; temel URL'yi, Authorization header'ını, JSON gövdesini ve hata normalizasyonunu halleder. Resmi bir SDK çıkana kadar ihtiyacınız olan tek soyutlama budur.

  4. 04

    Adım 4

    Bir deneme gönderin ve poll edin

    `product_type`, `product_images`, `mannequin_id`, `pose_id`, `resolution` ve `aspect_ratio` ile `/tryon/apparel` adresine POST gönderin. API anında bir generation ID döndürür. `status === 'completed'` olana kadar her 3 saniyede bir `/tryon/apparel/:id` adresini sorgulayın.

  5. 05

    Adım 5

    Sonucu kalıcı hale getirin

    Tamamlanan payload `output_url` ve `thumbnail_url` içerir. Byte'ları bir kez çekin ve kendi nesne depolama alanınızda saklayın — URL'ler sabittir ancak ürününüz render işlemi için Photta'nın CDN'ine bağımlı olmamalıdır.

Uçtan uca kod

Copy, paste, done.

Four snippets — install prerequisites, wrap the REST call, submit + poll, then handle the errors that actually happen in production.

01No SDK required — use native fetch in Node 18+
bash
# Node 18+ ships fetch natively. No install step needed.
node --version   # ensure v18 or later

# Optional: keep your API key out of source control
echo "PHOTTA_API_KEY=photta_live_xxxxx" >> .env
02Wrap the REST call in a tiny client helper
javascript
// photta.js — a 20-line wrapper you can reuse across your app.
const PHOTTA_BASE_URL = "https://ai.photta.app/api/v1";

export async function phottaFetch(path, init = {}) {
  const res = await fetch(`${PHOTTA_BASE_URL}${path}`, {
    ...init,
    headers: {
      "Authorization": `Bearer ${process.env.PHOTTA_API_KEY}`,
      "Content-Type": "application/json",
      ...init.headers,
    },
  });
  const body = await res.json();
  if (!res.ok) {
    const err = new Error(body?.error?.message ?? res.statusText);
    err.status = res.status;
    err.code = body?.error?.code;
    throw err;
  }
  return body;
}
03Submit a try-on job and poll until it lands
javascript
import { phottaFetch } from "./photta.js";

// 1. Submit the job — returns a generation ID immediately.
const created = await phottaFetch("/tryon/apparel", {
  method: "POST",
  body: JSON.stringify({
    product_type: "dress",
    product_images: ["https://example.com/dress.jpg"],
    mannequin_id: "mnq_athena_ts",
    pose_id: "pose_standing_front",
    resolution: "2K",
    aspect_ratio: "3:4",
  }),
});
const generationId = created.data.id;

// 2. Poll every 3 seconds until processing completes. Typical
// completion is 1.5–4 minutes; put an upper bound so a stuck
// job can't hang your request forever.
const pollInterval = 3000;
const maxAttempts = 120;     // 120 × 3s = 6 minutes
let result;

for (let i = 0; i < maxAttempts; i++) {
  result = await phottaFetch(`/tryon/apparel/${generationId}`);
  if (result.data.status === "completed") break;
  if (result.data.status === "failed") {
    throw new Error(result.data.error_message);
  }
  await new Promise((r) => setTimeout(r, pollInterval));
}

console.log("Result:", result.data.output_url);
04Handle 402 credit exhaustion and 429 rate limits
javascript
try {
  await phottaFetch("/tryon/apparel", {
    method: "POST",
    body: JSON.stringify({ /* … */ }),
  });
} catch (err) {
  if (err.status === 402) {
    // Out of credits — surface a top-up CTA to the user.
    // err.code === "insufficient_credits"
  } else if (err.status === 429) {
    // Rate-limited. Honour the Retry-After header.
    const retryAfter = err.retryAfter ?? 30;
    await new Promise((r) => setTimeout(r, retryAfter * 1000));
    // Then retry…
  } else if (err.status >= 500) {
    // Server-side issue — backoff + retry.
  }
  throw err;
}

Neden bu yapı

Neden bir yardımcı fonksiyon şu an için istemci kütüphanesinden daha iyidir

  • Node 18+ ships native fetch — no runtime deps required
  • Same helper works inside Next.js route handlers, API routes, server actions and edge functions
  • Keep API keys in env; never import the helper from a 'use client' module or the bundler will leak them
  • Works with any queue/cron: BullMQ, Inngest, Trigger.dev, Vercel Cron, Cloudflare Queues

Neleri yapmaz

Honest caveats

  • No official @photta/node SDK yet — REST is the only path today
  • No built-in webhook delivery; polling is the documented pattern (3–5s interval)
  • Bearer token lives in env; the API doesn't support OAuth client credentials yet

Diğer geliştiricilerin sorduğu sorular

Questions other developers ask

Resmi bir Photta Node.js SDK'sı var mı?+

Henüz değil. Photta dokümanları açıkça kullanım eşiklerinden sonra SDK planlamaktadır: On API kullanıcısına ulaşıldığında Python, yirmi olduğunda Node.js. O zamana kadar dokümante edilen yol; cURL, Node'un native fetch'i veya Python requests kütüphanesi üzerinden ham REST'tir. Bu sayfadaki 20 satırlık yardımcı, en çok kullanacağınız endpoint'ler için bir istemciye eşdeğerdir.

Hangi Node.js sürümleri destekleniyor?+

Native `fetch` destekleyen her şey — yani Node 18 ve sonrası. Node 16'da ya `node-fetch` ile polyfill yaparsınız ya da yükseltirsiniz. Kodun geri kalanı düz ECMAScript 2020'dir (async/await, template literals, dynamic imports), bu nedenle başka bir runtime gereksinimi yoktur.

Node üzerinden nasıl kimlik doğrularım?+

Her istekte `Authorization: Bearer photta_live_xxx` gönderin. Anahtar üretimde `photta_live_`, sandbox modu çıktığında ise `photta_test_` ile başlar. Bunu bir ortam değişkenine koyun ve `process.env.PHOTTA_API_KEY` üzerinden yükleyin. API henüz OAuth istemci kimlik bilgilerini veya oturum bazlı kimlik doğrulamayı desteklememektedir.

1.5–4 dakikalık üretim penceresini nasıl yönetirim?+

Deneme endpoint'i tamamen asenkrondur. POST işlemi anında `status: 'processing'` ile bir generation ID döndürür. `status` değeri `completed` veya `failed` olana kadar her 3–5 saniyede bir `GET /tryon/apparel/:id` yapın. Hatalı bir işin isteğinizi sonsuza kadar askıda bırakmaması için deneme sayısına bir üst sınır koyun — 3 saniyede 120 deneme, dokümante edilen pencereyi marjla kapsar.

API'yi Next.js içinde çağırabilir miyim?+

Evet — bir route handler (`app/**/route.ts`), bir server action (`'use server'`) veya middleware içinden çağırabilirsiniz. API anahtarını sunucuda tutun; yardımcıyı asla bir `'use client'` dosyasından import etmeyin. Vercel'in fonksiyon zaman aşımını aşan uzun süreli işler için polling işlemini bir kuyruğa (Inngest, Trigger.dev, BullMQ) devredin ve tarayıcıya generation ID'yi döndürerek kendi durum endpoint'inizi veya bir webhook'u sorgulamasını sağlayın.

API hataları nasıl bildirir?+

2xx olmayan yanıtlar bir `error` nesnesi içeren bir JSON gövdesi taşır: `type`, `code`, `message` ve destek için bir istek ID'si. Yaygın durumlar: Hatalı alanı işaret eden `param` ile 400 invalid_request_error; `required` ve `available` sayılarını içeren 402 insufficient_credits; saniye cinsinden `retry_after` ve eşleşen bir Retry-After header'ı ile 429 rate_limit_exceeded. 5xx hataları eksponansiyel geri çekilme ile güvenle tekrar denenebilir.

Node.js · Sanal Giyim Deneme API'si

Hesap oluşturun ve bir API anahtarı alın

Ortam değişkenlerinde `PHOTTA_API_KEY` değerini ayarlayın, `Authorization: Bearer photta_live_xxx` ile `https://ai.photta.app/api/v1` adresini çağıran küçük bir `phottaFetch()` yardımcısı yazın, bir ürün görseli URL'si, manken ID'si ve poz ID'si ile `/tryon/apparel` adresine POST yapın, ardından `status === 'completed'` olana kadar her 3 saniyede bir `/tryon/apparel/:id` adresini sorgulayın — genellikle 1.5–4 dakika sürer.

Node.js için Sanal Giyim Deneme API'si — Photta | Photta