fashn

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

FASHN API & SDKs

FASHN API 与 SDK

FASHN is an AI-first company specializing in human-centric generative image models tailored for fashion applications: virtual try-on, AI models, product photography, editing, and image-to-video. Everything runs through one prediction endpoint that takes a
model_name
plus an
inputs
object.
This skill helps you do two things:
  1. Integrate FASHN into a project: write production code against the REST API, the TypeScript SDK (
    fashn
    on npm), or the Python SDK (
    fashn
    on PyPI).
  2. Run a one-off generation inline: execute a single call and hand the result back to the user (see Inline quickstart).
When the user asks to add FASHN to their app / repo, integrate (write code into their project). When they ask to just do a try-on / generate an image now, run it inline.
Full per-endpoint parameter tables, the error catalog, webhooks, and credits live in reference.md. Load it when you need exact
inputs
for a given
model_name
.
FASHN是一家以AI为核心的公司,专注于打造以人为中心的生成式图像模型,专为时尚领域应用设计:包括虚拟试穿、AI模特、商品摄影、编辑以及图像转视频等。所有功能都通过一个预测端点实现,只需传入
model_name
inputs
对象即可。
本技能可帮助你完成两类操作:
  1. 将FASHN集成到项目中:基于REST API、TypeScript SDK(npm上的
    fashn
    包)或Python SDK(PyPI上的
    fashn
    包)编写生产级代码。
  2. 直接在线运行单次生成任务:执行单次调用并将结果返回给用户(详见在线快速入门)。
当用户要求将FASHN添加到他们的应用/代码库时,执行集成操作(将代码写入他们的项目)。当用户要求立即进行试穿/生成图像时,执行在线运行操作。
完整的端点参数表、错误目录、Webhook说明以及积分相关信息请查看**reference.md**。当你需要特定
model_name
对应的准确
inputs
参数时,请加载该文档。

Authentication

身份验证

  • Get an API key from the Developer API dashboard: https://app.fashn.ai/api
  • All FASHN calls are server-side: never hard-code the key or expose it client-side.
  • REST: send
    Authorization: Bearer $FASHN_API_KEY
    . Both SDKs read
    FASHN_API_KEY
    from the environment by default.
Resolve the key (check in order; prompt only if all fail):
  1. FASHN_API_KEY
    env var (preferred, used by integration code, CI, and deploys). Check:
    echo "${FASHN_API_KEY:+set}"
    .
  2. Cache file
    ~/.fashn/.env
    . Load, then re-check:
    set -a; [ -f ~/.fashn/.env ] && . ~/.fashn/.env; set +a
    .
  3. Otherwise, ask the user, then cache it (next bullet).
Caching (inline use only). When you had to ask the user for the key, save it to
~/.fashn/.env
by default
(right after you receive it) so later inline runs don't re-prompt, then tell the user it's cached there and that
rm ~/.fashn/.env
removes it. Only skip if they decline. Run:
bash
umask 077; mkdir -p ~/.fashn; printf 'FASHN_API_KEY=%s\n' '<key>' > ~/.fashn/.env; chmod 600 ~/.fashn/.env
Never echo the key back, write it to a shell profile, or commit it.
Integrations differ: pull the key from the project's own env (gitignored
.env
) or secret manager, never
~/.fashn/.env
or anywhere in the repo.
  • 从开发者API控制台获取API密钥:https://app.fashn.ai/api
  • 所有FASHN调用均需在服务端执行:切勿硬编码密钥或在客户端暴露密钥
  • REST方式:请求头中携带
    Authorization: Bearer $FASHN_API_KEY
    。两个SDK默认会从环境变量中读取
    FASHN_API_KEY
密钥获取优先级(按顺序检查;仅当所有方式都失败时才询问用户):
  1. FASHN_API_KEY
    环境变量(推荐,集成代码、CI流程和部署均使用此方式)。检查方式:
    echo "${FASHN_API_KEY:+set}"
  2. 缓存文件
    ~/.fashn/.env
    。加载该文件后重新检查:
    set -a; [ -f ~/.fashn/.env ] && . ~/.fashn/.env; set +a
  3. 若以上方式均失败,则询问用户获取密钥,然后进行缓存(见下一点)。
缓存(仅在线运行时使用)。当你需要向用户询问密钥时,默认将其保存到
~/.fashn/.env
(获取后立即执行),以便后续在线运行无需重复询问,然后告知用户密钥已缓存至该路径,执行
rm ~/.fashn/.env
可删除缓存。仅当用户拒绝时才跳过缓存。执行命令:
bash
umask 077; mkdir -p ~/.fashn; printf 'FASHN_API_KEY=%s\n' '<key>' > ~/.fashn/.env; chmod 600 ~/.fashn/.env
切勿回显密钥、写入shell配置文件或提交到代码仓库。
集成场景不同:从项目自身的环境变量(已加入git忽略的
.env
文件)或密钥管理工具中获取密钥,切勿使用
~/.fashn/.env
或代码仓库中的任何路径。

Core concepts (apply to every path)

核心概念(适用于所有使用方式)

One endpoint, many models. Every request is
{ model_name, inputs }
. Available
model_name
s:
Category
model_name
Required inputs
Virtual try-on (flagship)
tryon-max
model_image
,
product_image
Virtual try-on (legacy/fast)
tryon-v1.6
model_image
,
garment_image
Product → person wearing it
product-to-model
product_image
Generate a model from a prompt
model-create
prompt
Change a model's identity
model-swap
model_image
Headshot → upper-body avatar
face-to-model
face_image
Freeform edit
edit
image
,
prompt
Change aspect ratio (outpaint/crop)
reframe
image
,
aspect_ratio
Remove background → transparent PNG
background-remove
image
Animate an image → video
image-to-video
image
Prediction lifecycle. Two ways to get a result:
  • subscribe
    (recommended)
    : submit and auto-poll until a terminal state, then return the final result. Both SDKs expose this; for raw REST you implement the poll loop yourself.
  • Manual
    run
    +
    status
    :
    run
    returns a prediction
    id
    immediately; poll
    status(id)
    until
    completed
    /
    failed
    . Use this for fire-and-forget, your own queue, or when pairing with webhooks.
Response envelope. A terminal prediction looks like:
json
{ "id": "...", "status": "completed", "output": ["https://cdn.fashn.ai/.../output_0.png"], "error": null }
  • status
    :
    starting
    in_queue
    processing
    completed
    |
    failed
    (SDK
    subscribe
    may also return
    canceled
    /
    time_out
    ).
  • output
    : array of CDN image URLs (or base64 if
    return_base64: true
    ); MP4 URLs for
    image-to-video
    .
  • error
    :
    null
    on success, else
    { name, message }
    .
Credits. Spend is returned in the
x-fashn-credits-used
response header (REST) and as
creditsUsed
(TS) /
credits_used
(Python) on the result. Failed predictions are not charged. Cost scales with
generation_mode
and
resolution
; see reference.md. Check the balance with
GET /v1/credits
.
Errors (two kinds):
  • API errors (HTTP 4xx/5xx, before the job runs): SDKs throw (
    APIError
    subclasses); REST returns
    { "error": "<Code>", "message": "..." }
    .
  • Runtime errors (job ran but failed): HTTP 200 with
    status: "failed"
    and
    error: { name, message }
    , e.g.
    ImageLoadError
    ,
    ContentModerationError
    ,
    PoseError
    . Always branch on
    status
    even when no exception is thrown.
Limits: handle
429
responses with backoff when batching.

一个端点,多类模型。每个请求的格式均为
{ model_name, inputs }
。可用的
model_name
如下:
分类
model_name
必填输入参数
虚拟试穿(旗舰版)
tryon-max
model_image
,
product_image
虚拟试穿(旧版/快速版)
tryon-v1.6
model_image
,
garment_image
商品转模特上身
product-to-model
product_image
通过提示词生成模特
model-create
prompt
更换模特身份
model-swap
model_image
头像转上半身虚拟模特
face-to-model
face_image
自由编辑
edit
image
,
prompt
修改宽高比(扩图/裁剪)
reframe
image
,
aspect_ratio
移除背景生成透明PNG
background-remove
image
图像转视频
image-to-video
image
预测生命周期。获取结果有两种方式:
  • subscribe
    (推荐)
    :提交请求后自动轮询直至进入终态,然后返回最终结果。两个SDK均提供此方法;原生REST方式需自行实现轮询逻辑。
  • 手动
    run
    +
    status
    run
    会立即返回预测任务
    id
    ;轮询
    status(id)
    直至状态变为
    completed
    /
    failed
    。适用于无需等待结果的场景、自定义队列或搭配Webhook使用。
响应结构。终态预测结果示例:
json
{ "id": "...", "status": "completed", "output": ["https://cdn.fashn.ai/.../output_0.png"], "error": null }
  • status
    :状态流转为
    starting
    in_queue
    processing
    completed
    |
    failed
    (SDK的
    subscribe
    方法还可能返回
    canceled
    /
    time_out
    )。
  • output
    :CDN图像URL数组(若设置
    return_base64: true
    则返回base64格式);
    image-to-video
    模型返回MP4 URL。
  • error
    :成功时为
    null
    ,失败时为
    { name, message }
积分。消耗的积分会在响应头
x-fashn-credits-used
(REST方式)中返回,SDK中则通过
creditsUsed
(TypeScript)/
credits_used
(Python)字段返回。失败的预测任务不扣费。费用根据
generation_mode
resolution
有所不同;详见reference.md。可通过
GET /v1/credits
查询余额。
错误类型(两类)
  • API错误(HTTP 4xx/5xx,任务运行前发生):SDK会抛出异常(
    APIError
    子类);REST方式返回
    { "error": "<Code>", "message": "..." }
  • 运行时错误(任务已执行但失败):HTTP状态码200,
    status: "failed"
    error: { name, message }
    ,例如
    ImageLoadError
    ContentModerationError
    PoseError
    。即使未抛出异常,也需始终根据
    status
    分支处理。
限制:批量处理时遇到
429
响应需进行退避重试。

Path A: TypeScript SDK (
fashn
)

方式A:TypeScript SDK(
fashn

Install into the user's project:
npm install fashn
ts
import Fashn from 'fashn';

const client = new Fashn(); // reads FASHN_API_KEY from env

// Recommended: submit + auto-poll to completion
const result = await client.predictions.subscribe({
  model_name: 'tryon-max',
  inputs: {
    model_image: 'https://example.com/person.jpg',
    product_image: 'https://example.com/garment.jpg',
  },
  // optional: pollInterval (ms, default 1000), timeout (ms, default 300000),
  onEnqueued: (id) => console.log('queued', id),
  onQueueUpdate: (s) => console.log('status', s.status),
});

if (result.status === 'completed') {
  console.log(result.output, 'credits:', result.creditsUsed);
} else {
  console.error('failed:', result.status, result.error?.name, result.error?.message);
}
Manual lifecycle:
ts
const { id } = await client.predictions.run({ model_name: 'tryon-max', inputs: { /* ... */ } });
const status = await client.predictions.status(id); // poll until terminal
Error handling (API vs runtime):
ts
try {
  const r = await client.predictions.subscribe({ model_name: 'tryon-max', inputs: { /* ... */ } });
  if (r.status !== 'completed') console.error('runtime error:', r.error?.name, r.error?.message);
} catch (err) {
  if (err instanceof Fashn.APIError) console.error('API error:', err.status, err.message);
  else throw err;
}
安装到用户项目中:
npm install fashn
ts
import Fashn from 'fashn';

const client = new Fashn(); // 从环境变量读取FASHN_API_KEY

// 推荐方式:提交请求并自动轮询至完成
const result = await client.predictions.subscribe({
  model_name: 'tryon-max',
  inputs: {
    model_image: 'https://example.com/person.jpg',
    product_image: 'https://example.com/garment.jpg',
  },
  // 可选参数:pollInterval(毫秒,默认1000)、timeout(毫秒,默认300000),
  onEnqueued: (id) => console.log('已加入队列', id),
  onQueueUpdate: (s) => console.log('状态', s.status),
});

if (result.status === 'completed') {
  console.log(result.output, '积分消耗:', result.creditsUsed);
} else {
  console.error('失败:', result.status, result.error?.name, result.error?.message);
}
手动生命周期管理:
ts
const { id } = await client.predictions.run({ model_name: 'tryon-max', inputs: { /* ... */ } });
const status = await client.predictions.status(id); // 轮询直至进入终态
错误处理(API错误 vs 运行时错误):
ts
try {
  const r = await client.predictions.subscribe({ model_name: 'tryon-max', inputs: { /* ... */ } });
  if (r.status !== 'completed') console.error('运行时错误:', r.error?.name, r.error?.message);
} catch (err) {
  if (err instanceof Fashn.APIError) console.error('API错误:', err.status, err.message);
  else throw err;
}

Path B: Python SDK (
fashn
)

方式B:Python SDK(
fashn

Install into the user's project:
pip install fashn
python
import fashn
from fashn import Fashn

client = Fashn()  # reads FASHN_API_KEY from env

result = client.predictions.subscribe(
    model_name="tryon-max",
    inputs={
        "model_image": "https://example.com/person.jpg",
        "product_image": "https://example.com/garment.jpg",
    },
)

if result.status == "completed":
    print(result.output, "credits:", result.credits_used)
else:
    print("failed:", result.status, result.error)
Manual lifecycle:
client.predictions.run(...)
client.predictions.status(prediction_id)
. Async: use
from fashn import AsyncFashn
and
await client.predictions.subscribe(...)
. API errors raise
fashn.APIError
(
e.status_code
,
e.message
); runtime failures arrive as
result.status == "failed"
with
result.error
.
安装到用户项目中:
pip install fashn
python
import fashn
from fashn import Fashn

client = Fashn()  # 从环境变量读取FASHN_API_KEY

result = client.predictions.subscribe(
    model_name="tryon-max",
    inputs={
        "model_image": "https://example.com/person.jpg",
        "product_image": "https://example.com/garment.jpg",
    },
)

if result.status == "completed":
    print(result.output, "积分消耗:", result.credits_used)
else:
    print("失败:", result.status, result.error)
手动生命周期管理:
client.predictions.run(...)
client.predictions.status(prediction_id)
。 异步方式:使用
from fashn import AsyncFashn
并调用
await client.predictions.subscribe(...)
。 API错误会抛出
fashn.APIError
(包含
e.status_code
e.message
);运行时失败会返回
result.status == "failed"
并附带
result.error

Path C: REST (any language)

方式C:REST(支持任意语言)

Base URL
https://api.fashn.ai/v1
. Submit, then poll.
bash
undefined
基础URL为
https://api.fashn.ai/v1
。提交请求后进行轮询。
bash
undefined

Submit → returns {"id": "...", "error": null}

提交请求 → 返回{"id": "...", "error": null}

curl -s -X POST https://api.fashn.ai/v1/run
-H "Authorization: Bearer $FASHN_API_KEY"
-H "Content-Type: application/json"
-d '{"model_name":"tryon-max","inputs":{ "model_image":"https://example.com/person.jpg", "product_image":"https://example.com/garment.jpg"}}'
curl -s -X POST https://api.fashn.ai/v1/run
-H "Authorization: Bearer $FASHN_API_KEY"
-H "Content-Type: application/json"
-d '{"model_name":"tryon-max","inputs":{ "model_image":"https://example.com/person.jpg", "product_image":"https://example.com/garment.jpg"}}'

Poll → repeat until status is "completed" or "failed"

轮询 → 重复调用直至状态变为"completed"或"failed"

curl -s https://api.fashn.ai/v1/status/<id> -H "Authorization: Bearer $FASHN_API_KEY" -i
curl -s https://api.fashn.ai/v1/status/<id> -H "Authorization: Bearer $FASHN_API_KEY" -i

read x-fashn-credits-used from the response headers

从响应头读取x-fashn-credits-used字段

Balance

查询余额

curl -s https://api.fashn.ai/v1/credits -H "Authorization: Bearer $FASHN_API_KEY"

**Webhooks** (skip polling): append `?webhook_url=` to `/run`. FASHN POSTs the terminal payload (`completed`/`failed`) to that URL, retrying up to 5 times over ~5 min. There's no signature header, so make the handler idempotent and respond 2xx fast. Details in reference.md.

---
curl -s https://api.fashn.ai/v1/credits -H "Authorization: Bearer $FASHN_API_KEY"

**Webhook**(跳过轮询):在`/run`接口后追加`?webhook_url=`参数。FASHN会将终态结果(`completed`/`failed`)POST到该URL,在约5分钟内最多重试5次。该请求没有签名头,因此请确保处理接口具备幂等性并快速返回2xx状态码。详细说明见reference.md。

---

Inline quickstart

在线快速入门

For a one-off generation (not an integration), run the TS SDK from
~/.fashn
so you don't touch the user's project:
  1. Install if needed:
    ls ~/.fashn/node_modules/fashn 2>/dev/null || npm install --prefix ~/.fashn fashn
  2. Resolve the key:
    [ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; }
    . If still unset, see Authentication.
  3. Run it. Pipe the script via a single-quoted heredoc so the shell leaves backticks/
    $
    /quotes alone, and
    cd ~/.fashn
    first so ESM resolves the
    fashn
    import (it ignores
    NODE_PATH
    ):
bash
[ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; }
cd ~/.fashn && node --input-type=module <<'NODE'
import Fashn from 'fashn';
const r = await new Fashn().predictions.subscribe({
  model_name: 'tryon-max',
  inputs: {
    model_image: 'https://example.com/person.jpg',
    product_image: 'https://example.com/garment.jpg',
  },
  timeout: 120000, // ms
});
if (r.status !== 'completed') { console.error('Failed:', r.status, r.error); process.exit(1); }
console.log(JSON.stringify({ output: r.output, creditsUsed: r.creditsUsed }, null, 2));
NODE
  • Local image inputs: read the file as base64 (
    readFile(path, { encoding: 'base64' })
    from
    node:fs/promises
    ) and pass it as
    product_image: 'data:image/jpeg;base64,' + b64
    . Save a result with
    fetch(r.output[0])
    .
  • Don't write script files or put the key on the command line (use step 2's cache); back off on
    429
    when batching.
对于单次生成任务(非集成场景),从
~/.fashn
目录运行TypeScript SDK,避免影响用户项目:
  1. 若未安装则执行安装:
    ls ~/.fashn/node_modules/fashn 2>/dev/null || npm install --prefix ~/.fashn fashn
  2. 获取密钥:
    [ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; }
    。若仍未获取到密钥,请查看身份验证部分。
  3. 运行任务。通过单引号 heredoc 传递脚本,避免shell解析反引号/
    $
    /引号,并且**先执行
    cd ~/.fashn
    **确保ESM能正确解析
    fashn
    导入(ESM会忽略
    NODE_PATH
    ):
bash
[ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; }
cd ~/.fashn && node --input-type=module <<'NODE'
import Fashn from 'fashn';
const r = await new Fashn().predictions.subscribe({
  model_name: 'tryon-max',
  inputs: {
    model_image: 'https://example.com/person.jpg',
    product_image: 'https://example.com/garment.jpg',
  },
  timeout: 120000, // 毫秒
});
if (r.status !== 'completed') { console.error('失败:', r.status, r.error); process.exit(1); }
console.log(JSON.stringify({ output: r.output, creditsUsed: r.creditsUsed }, null, 2));
NODE
  • 本地图像输入:将文件读取为base64格式(使用
    node:fs/promises
    中的
    readFile(path, { encoding: 'base64' })
    ),并以
    product_image: 'data:image/jpeg;base64,' + b64
    的形式传入。可通过
    fetch(r.output[0])
    保存结果。
  • 请勿编写脚本文件或在命令行中传入密钥(使用步骤2的缓存);批量处理时遇到
    429
    响应需进行退避重试。

Reference

参考文档

See reference.md for every endpoint's full
inputs
(types, allowed values, defaults), the complete error catalog, credit/pricing notes, webhook payloads, and rate limits.
请查看**reference.md**获取所有端点的完整
inputs
参数(类型、允许值、默认值)、完整错误目录、积分/定价说明、Webhook payload以及速率限制信息。

User's request

用户请求

$ARGUMENTS
$ARGUMENTS