---
title: FASHN API: Fashion AI Agent
description: FASHN API docs. The FASHN Agent API turns a prompt and reference images into fashion content, and virtual try-on endpoints power real-time shopping experiences.
---

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

# FASHN API: Fashion AI Agent

FASHN API docs. The FASHN Agent API turns a prompt and reference images into fashion content, and virtual try-on endpoints power real-time shopping experiences.

## Welcome to the FASHN API

FASHN is an AI-first company specializing in human-centric generative image models tailored for fashion applications. The FASHN API gives developers and product teams two ways to use them:

- **The FASHN Agent API**, for fashion content creation. Describe the images you need in plain language and attach up to six reference images, and the FASHN Agent plans and runs the steps, such as try-on, model swap, edits, upscaling, and background removal. Call it from your own code, or let a coding agent such as Claude Code, Codex, or Cursor call it for you.
- **Virtual try-on and single-task endpoints**, for real-time shopping experiences and for direct control over one task at a time.

## FASHN Agent API

- [🤖 Agent Images](/api-reference/agent-images): Describe the images you need, attach up to six references, and get back every image the FASHN Agent made
- [🚀 Agent API Quickstart](/getting-started/agent-quickstart): Make your first request, then try prompts for on-model photos, packshots, catalog images, and lookbooks
- [📸 Lookbook Recipe](/recipes/lookbook.md): Paste one line into Claude Code to make a four-look lookbook from six photos in one call
- [🧑‍💻 Coding Agents](/getting-started/agent-skill): Use FASHN from Claude Code, Codex, Cursor, and other coding agents

One request to the Agent can cover several steps that would otherwise take a chain of calls:

- **On-model product photos:** a product on a model, from several angles.
- **Packshots:** a clean product image on a plain or transparent background.
- **Catalog images:** several products on the same model, in the same setting.
- **Lookbooks:** one model in one location across several looks.

```bash
curl -X POST https://api.fashn.ai/v1/agent/images \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -d '{
           "prompt": "Show the jacket in the first image on a model in a bright studio, full body, front view",
           "images": ["https://example.com/jacket.jpg"]
         }'
```

Agent Images is in the [Experimental](/api-overview/model-lifecycle) lifecycle stage, so its behavior and parameters may still change.

## Virtual try-on for shopping experiences

Our **Virtual Try-On (VTON)** technology shows how clothing would look on a person without them physically wearing it. The API takes a photo of a person and a product, then generates a realistic image showing how it would appear on that person. Use it for real-time shopping experiences, such as a try-on button on a product page or an AI shopping assistant. [Try-On Max](/api-reference/tryon-max) is the recommended try-on endpoint for most applications, while [Try-On v1.6](/api-reference/tryon-v1-6) remains available for real-time, cost-sensitive integrations.

- [🪞 Clothing Virtual Try-On](/api-reference/tryon-max): Premium virtual try-on with enhanced fidelity for fashion photoshoots and publishable e-commerce content.
- [⚡ Try-On v1.6](/api-reference/tryon-v1-6): Fast, lightweight virtual try-on optimized for real-time e-commerce experiences

## Single-task endpoints

Each single-task endpoint does one job, such as try-on or reframing, through `POST /v1/run`. The FASHN Agent covers most of these tasks in one request. Call a single-task endpoint directly when you need its specific parameters, or for video.

- [📦 Product to Model](/api-reference/product-to-model): Transform product-only images into realistic visuals of people wearing those products
- [👤 Model Create](/api-reference/model-create): Generate realistic fashion models using simple textual prompts or reference images
- [🎭 Face to Model](/api-reference/face-to-model): Transform face images into try-on ready upper-body avatars for virtual try-on applications
- [🔄 Model Swap](/api-reference/model-swap): Replace existing models in images while preserving garments
- [🪄 Edit](/api-reference/edit): Versatile post-processing to restyle shots, adjust views, and fix details while preserving identity
- [📐 Reframe](/api-reference/reframe): Adjust image aspect ratios by expanding or cropping based on smart content analysis
- [✂️ Background Remove](/api-reference/background-remove): Remove image backgrounds to create transparent PNG cutouts of foreground subjects
- [🎬 Image to Video](/api-reference/image-to-video): Create short videos from a single image with tasteful camera work and model movements tailored for fashion.

## Built for production

- [🛠️ Developer Friendly](/api-overview/api-fundamentals): Simple REST API with comprehensive guides and multiple language examples
- [🔒 Enterprise Grade](/api-overview/data-retention-privacy): Secure, scalable infrastructure with robust data privacy controls

---

Ready to get started? Set up your account with [API Setup](/getting-started/api-setup), then make your first request with the [FASHN Agent API Quickstart](/getting-started/agent-quickstart).

---

---
title: API Setup
description: Set up your FASHN API account, buy credits, create an API key, and make your first FASHN Agent API request
---

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

# API Setup

Set up your FASHN API account, buy credits, create an API key, and make your first FASHN Agent API request

Follow these steps to get started with the FASHN API and make your first successful request.

    ### Create Your Account

    Sign up at [app.fashn.ai](https://app.fashn.ai) to access the [Developer API dashboard](https://app.fashn.ai/api).

    ### Purchase Credits

    You must purchase API credits before you can create an API key.

    Go to [Billing](https://app.fashn.ai/billing) and select the **FASHN API** tab. 
    API credits are bought on demand: buy the amount you need, and top up whenever your balance runs low.

    ### Generate an API Key

    After purchasing credits, go to the [Developer API dashboard](https://app.fashn.ai/api) and click **Create new API key**.
    You won't be able to view it again after closing the window.

    ### Make Your First Agent Request

    Start with the [FASHN Agent API](/api-reference/agent-images): describe the images you need in plain language, attach up to six reference images, and the FASHN Agent returns the finished images. The [Agent API Quickstart](/getting-started/agent-quickstart) walks through a first request and example prompts for on-model photos, packshots, catalog images, and lookbooks.

    Working in Claude Code, Codex, or Cursor? See [Coding Agents](/getting-started/agent-skill) to let your coding agent make the calls.

    ### Understand the Fundamentals

    Review [API Fundamentals](/api-overview/api-fundamentals) to understand authentication, request patterns, and error handling.

    ### Add Virtual Try-On

    Building a real-time shopping experience? Use [Try-On Max](/api-reference/tryon-max), our most capable virtual try-on model with the highest quality output. Our [Python](/guides/tryon-python-quickstart-guide) and [JavaScript](/guides/tryon-javascript-quickstart-guide) try-on quickstarts show complete examples.

If you encounter any issues during setup, check our [Troubleshooting
  Guide](/guides/troubleshooting-guide) or contact support@fashn.ai.

---

**Next:** Ready to make your first API call? Start with the [FASHN Agent API Quickstart](/getting-started/agent-quickstart), or jump directly to the [Agent Images reference](/api-reference/agent-images).

---

---
title: FASHN Agent API Quickstart
description: Make your first FASHN Agent API request, then try example prompts for on-model product photos, packshots, catalog images, and lookbooks.
---

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

# FASHN Agent API Quickstart

Make your first FASHN Agent API request, then try example prompts for on-model product photos, packshots, catalog images, and lookbooks.

The FASHN Agent API is the main way to make fashion images with FASHN. You send one request with a plain-language prompt and up to six reference images, and the FASHN Agent plans the steps, runs them, and returns every image it made. It can run try-on, product-to-model, model creation and swap, edits, background changes, packshots, transparent images, upscaling, and background removal.

This page takes you from an API key to your first images, then shows prompts for common fashion content. For every parameter, limit, and error, see the [Agent Images reference](/api-reference/agent-images).

See it in action: this video makes a four-look lookbook from six photos with Claude Code and one FASHN Agent API call.

[Video: FASHN Agent API: Getting Started (with Claude Code)](https://www.youtube.com/watch?v=ntmiR0oU7oc)

## Make your first request

### Get an API key

Create an account, buy credits, and create a key by following [API Setup](/getting-started/api-setup). Then store the key in an environment variable:

```bash
export FASHN_API_KEY="your-api-key"
```

### Send a prompt and your images

Send the prompt and the image URLs to `POST /v1/agent/images`. In the prompt, refer to the images by their position or by what they show. This example turns a product photo into an on-model photo:

```bash
curl -X POST https://api.fashn.ai/v1/agent/images \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer $FASHN_API_KEY" \
     -d '{
           "prompt": "Show the jacket in the first image on a model in a bright studio, full body, front view",
           "images": ["https://example.com/jacket.jpg"]
         }'
```

```javascript
const response = await fetch("https://api.fashn.ai/v1/agent/images", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${process.env.FASHN_API_KEY}`,
  },
  body: JSON.stringify({
    prompt: "Show the jacket in the first image on a model in a bright studio, full body, front view",
    images: ["https://example.com/jacket.jpg"],
  }),
});

const result = await response.json();
for (const prediction of result.predictions) {
  console.log(prediction.tool, prediction.results);
}
```

```python
import os
import requests

response = requests.post(
    "https://api.fashn.ai/v1/agent/images",
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {os.environ['FASHN_API_KEY']}",
    },
    json={
        "prompt": "Show the jacket in the first image on a model in a bright studio, full body, front view",
        "images": ["https://example.com/jacket.jpg"],
    },
)

result = response.json()
for prediction in result["predictions"]:
    print(prediction["tool"], prediction["results"])
```

The request stays open until the Agent finishes: about 40 seconds for one image at the default settings, and longer for requests with several steps.

### Use the images

The response lists every operation that produced images, in the order the Agent ran them, intermediate steps included. Each entry's `results` holds the image URLs, and `credits_used` gives the cost:

```json
{
  "id": "3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18",
  "predictions": [
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "tool": "generate-image",
      "results": [
        "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
      ],
      "credits_used": 1
    }
  ],
  "credits_used": 1
}
```

Download the images you want to keep. See [Data Retention & Privacy](/api-overview/data-retention-privacy) for how long outputs stay available.

## Run longer requests in the background

Requests with several steps, such as a lookbook, can take a few minutes. Instead of holding the connection open, start a run with `POST /v1/agent/images/run`. It takes the same body and returns a run ID right away. Then poll the run's status with that ID until `status` is `completed` or `failed`:

```bash
# Start the run
curl -X POST https://api.fashn.ai/v1/agent/images/run \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer $FASHN_API_KEY" \
     -d '{
           "prompt": "Show the jacket in the first image on a model in a bright studio, full body, front view",
           "images": ["https://example.com/jacket.jpg"]
         }'
# Returns {"id": "3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18", "error": null}

# Check on it
curl https://api.fashn.ai/v1/agent/status/3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18 \
     -H "Authorization: Bearer $FASHN_API_KEY"
```

A completed run returns the same `predictions` and `credits_used` as the synchronous response. To get the result on your server instead of polling, add a `webhook_url` query parameter when you start the run. See [Asynchronous runs](/api-reference/agent-images#asynchronous-runs) and [Webhooks](/api-overview/webhooks).

## Example prompts for fashion content

Each example below is a request body for `/v1/agent/images` or `/v1/agent/images/run`. Replace the image URLs with your own, or send base64 data URIs.

### On-model product photos

Turn a product photo into photos of a model wearing it:

```json
{
  "prompt": "Show the dress in the first image on a model in a bright studio. Make three images from different angles: front, three-quarter, and side, full body.",
  "images": ["https://example.com/dress.jpg"],
  "aspect_ratio": "3:4"
}
```

A request for several images, such as three angles, makes one image per generation and is billed per image.

### Packshots

Make a clean product image from a photo of the product:

```json
{
  "prompt": "Make a packshot of the bag in the first image, alone on a plain white background with a soft studio shadow",
  "images": ["https://example.com/bag-photo.jpg"],
  "aspect_ratio": "1:1"
}
```

For a cutout, ask for a transparent background instead.

### Catalog images

Put several products on the same model in the same setting, one image per product:

```json
{
  "prompt": "Put each garment from images 2 to 4 on the model from image 1, one image per garment. Full body, front view, plain light gray studio background, the same pose and lighting in every image.",
  "images": [
    "https://example.com/model.jpg",
    "https://example.com/shirt.jpg",
    "https://example.com/trousers.jpg",
    "https://example.com/coat.jpg"
  ],
  "aspect_ratio": "3:4",
  "resolution": "2k"
}
```

A request takes up to six images and runs up to eight operations, so a larger catalog takes several requests. They can run in parallel up to your [concurrency limit](/api-overview/api-fundamentals#concurrency-limits).

### Lookbooks

A lookbook keeps one model and one location across several looks. The [lookbook recipe](https://docs.fashn.ai/recipes/lookbook.md) makes four looks from a face photo, a location photo, and four outfits in one call, with a prompt worded to keep the face the same in every look:

```json
{
  "prompt": "Make a lookbook of four full body photos. Image 1 is the model, image 2 is the location, and images 3 to 6 are four outfits, one per look. Make look 1 first. Then make looks 2, 3 and 4, each one directly from look 1, in a different pose, head angle and expression. In every look, use the face from image 1, so the model matches image 1 exactly.",
  "images": [
    "https://example.com/face.jpg",
    "https://example.com/location.jpg",
    "https://example.com/outfit-1.jpg",
    "https://example.com/outfit-2.jpg",
    "https://example.com/outfit-3.jpg",
    "https://example.com/outfit-4.jpg"
  ],
  "resolution": "2k",
  "aspect_ratio": "2:3",
  "generation_mode": "quality"
}
```

Run it in the background: it takes about five minutes and, at these settings, 12 credits for the four looks.

## Use it from Claude Code or Codex

A coding agent can run these requests for you. It finds the photos, sends the request, and saves the results, and the FASHN Agent makes the images: your agent is the producer, and the FASHN Agent is the photographer.

**Claude Code.** Open Claude Code in a folder with a face photo, a location photo, and four outfit photos, and paste:

```text
Download https://docs.fashn.ai/recipes/lookbook.md with curl and follow it exactly
```

The recipe sets up your API key in a `.env` file, confirms which photo is which, and saves the four looks in a new folder. [How to make an AI lookbook with Claude Code ↗](https://fashn.ai/blog/fashn-agent-api-getting-started) walks through a full run.

**Codex, Cursor, and other agents.** Every page of these docs is also available as Markdown. Ask your agent to read the Agent Images reference, then describe what you need, for example:

```text
Read https://docs.fashn.ai/api-reference/agent-images.md.
Then turn every product photo in ./products into an on-model photo
with the FASHN Agent API, and save the results in ./on-model.
```

See [Coding Agents](/getting-started/agent-skill) for more ways to use FASHN from a coding agent.

## Tips for better results

- Refer to the images by their position ("the first image") or by what they show ("the dress").
- The Agent never asks a question back. When a prompt is unclear, it makes its best guess, so say what you want: framing, background, pose, and how many images.
- The Agent adds no steps you did not ask for, such as an upscale or a variation. Ask for them in the prompt.
- Use `generation_mode: "fast"` for drafts, and `"quality"` with a higher `resolution` for final assets. See [Credit cost](/api-reference/agent-images#credit-cost).
- Each request runs at most 8 operations, so it costs at most 32 credits.
- The Agent makes images only. For video, use [Image to Video](/api-reference/image-to-video).

For virtual try-on in a shopping experience, such as a "try it on" button on
  a product page, call [Try-On Max](/api-reference/tryon-max) or the faster
  [Try-On v1.6](/api-reference/tryon-v1-6) directly.

---

**Next:** Read the full [Agent Images reference](/api-reference/agent-images), or set up [Webhooks](/api-overview/webhooks) for background runs.

---

---
title: Use FASHN with Claude Code, Codex, and Cursor
description: Use FASHN from coding agents like Claude Code, Codex, and Cursor. Make fashion images with the FASHN Agent API, or integrate FASHN with the official agent skill.
---

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

# Use FASHN with Claude Code, Codex, and Cursor

Use FASHN from coding agents like Claude Code, Codex, and Cursor. Make fashion images with the FASHN Agent API, or integrate FASHN with the official agent skill.

Coding agents such as **Claude Code, Codex, and Cursor** can work with FASHN in two ways:

- **Make images with the [FASHN Agent API](/api-reference/agent-images).** Your agent finds the photos, sends the request, and saves the results, and the FASHN Agent makes the images. Your agent is the producer, and the FASHN Agent is the photographer.
- **Integrate FASHN into your project** with the official FASHN [agent skill](#integrate-fashn-with-the-agent-skill), which teaches your agent the FASHN single-task endpoints and SDKs.

## Make images with the FASHN Agent API

The FASHN Agent API is a plain REST endpoint: one request with a prompt and up to six reference images returns every image the Agent made. A coding agent can call it with curl or a short script, so you describe the content you need and your agent runs it.

You need a FASHN API key. Generate one from [API Setup](/getting-started/api-setup). Keep it in an environment variable or a `.env` file, and never paste it into the chat.

### Claude Code: follow a recipe

A recipe is a file of instructions your agent follows step by step. The [lookbook recipe](https://docs.fashn.ai/recipes/lookbook.md) makes a four-look lookbook of one model in one location from six photos, in one call. Open Claude Code in a folder with a face photo, a location photo, and four outfit photos, and paste:

```text
Download https://docs.fashn.ai/recipes/lookbook.md with curl and follow it exactly
```

The recipe sets up your API key in a `.env` file, confirms which photo is which, and saves the looks in a new folder. [How to make an AI lookbook with Claude Code ↗](https://fashn.ai/blog/fashn-agent-api-getting-started) walks through a full run, and this video shows it from start to finish:

[Video: FASHN Agent API: Getting Started (with Claude Code)](https://www.youtube.com/watch?v=ntmiR0oU7oc)

### Any agent: point it at the docs

Every page of these docs is also available as Markdown. Ask your agent to read the Agent Images reference, then describe what you need:

On-model photos from several angles:

```text
Read https://docs.fashn.ai/api-reference/agent-images.md.
Then use the FASHN Agent API to make three on-model photos of ./dress.jpg
from different angles, and save them in ./on-model.
```

Packshots for a folder of products:

```text
Read https://docs.fashn.ai/api-reference/agent-images.md.
Then make a white-background packshot of every photo in ./bags
with the FASHN Agent API.
```

A reusable script for your catalog:

```text
Read https://docs.fashn.ai/api-reference/agent-images.md.
Then write a script that sends each product photo in ./products
to the FASHN Agent API and saves the results.
```

For more prompts, see the [Agent API Quickstart](/getting-started/agent-quickstart#example-prompts-for-fashion-content).

## Integrate FASHN with the agent skill

FASHN publishes an [agent skill](https://www.skills.sh/docs) that teaches coding agents how to integrate the FASHN single-task endpoints through the REST API or the official [TypeScript](/sdk/typescript) and [Python](/sdk/python) SDKs. Once installed, your agent can wire FASHN into your project, or run a one-off generation, without you pasting documentation into the chat.

It works with **Claude Code, Codex, Cursor, and many others**.

### Install

Install the skill with [skills.sh](https://www.skills.sh/docs). The CLI auto-detects which coding agents you have installed and configures the skill for each:

```bash
npx skills add fashn-ai/fashn-skill
```

The skill reads a `FASHN_API_KEY` from the environment. If it isn't set, the
  skill asks for your key and helps you configure it, caching it for future
  runs. Generate one from [API Setup](/getting-started/api-setup).

### What the skill knows

- Every FASHN single-task endpoint (`/v1/run`) and its inputs.
- The prediction lifecycle: `subscribe` (submit and auto-poll) versus the manual `run` plus `status` polling flow.
- The response envelope, the [error catalog](/api-overview/error-handling), credit usage, and [webhooks](/api-overview/webhooks).
- Both integration paths (REST and the TypeScript or Python SDKs), plus a one-off inline run.

The skill covers the single-task endpoints. To use the FASHN Agent API from a coding agent, point your agent at the Agent Images docs as described in [Make images with the FASHN Agent API](#make-images-with-the-fashn-agent-api).

### Usage

After installing, your agent loads the skill automatically (restart the agent if a session is already open). Mention FASHN in your request so the skill activates, then describe the outcome you want and it chooses the right model and wires up the call.

**Build FASHN into your app**

```text
Add a FASHN virtual try-on route to my Next.js app: accept a model photo
and a garment image, and return the result URL.
```

```text
Use FASHN to write a Python worker that runs every garment in ./products
through a model.
```

```text
Integrate FASHN API into my PHP project.
```

**Generate something on the spot**

In Claude Code and Codex, run a one-off generation by invoking the skill directly with `/fashn`:

Product to model:

```text
/fashn generate three on-model shots of this product for our product page
```

A one-off try-on:

```text
/fashn do a try-on with this model photo and this jacket
```

With other agents, describe the same task in chat and the skill activates automatically.

### Links

- Skill repository: [github.com/fashn-AI/fashn-skill](https://github.com/fashn-AI/fashn-skill)
- skills.sh documentation: [skills.sh/docs](https://www.skills.sh/docs)

---

**Next:** Make your first request with the [Agent API Quickstart](/getting-started/agent-quickstart), pick an integration path with the [TypeScript](/sdk/typescript) or [Python](/sdk/python) SDK, or browse the [API Reference](/api-reference).

---

---
title: API Fundamentals
description: Common patterns, authentication, and workflows shared across all FASHN API endpoints
---

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

# API Fundamentals

Common patterns, authentication, and workflows shared across all FASHN API endpoints

This page explains the fundamental concepts that apply across the FASHN API. Authentication, content delivery, error handling, credits, rate limits, and webhooks work the same for every endpoint, including the [FASHN Agent API](/api-reference/agent-images). The request and response patterns describe the [single-task endpoints](/api-reference#single-task-endpoints), which run through `/v1/run`. The Agent API's own request and response formats are on [Agent Images](/api-reference/agent-images).

Install the [FASHN agent skill](/getting-started/agent-skill) and Claude Code, Codex, Cursor, or another agent can wire these patterns into your project for you: `npx skills add fashn-ai/fashn-skill`.

## Authentication

All API requests require authentication using a `Bearer` token in the `Authorization` header:

```http
Authorization: Bearer YOUR_API_KEY
```

You can obtain your API key from the [Developer API Dashboard ↗](https://app.fashn.ai/api).

## Single-Task Request Pattern

All FASHN single-task endpoints follow a consistent request pattern to the same `/v1/run` endpoint:

[Agent Images](/api-reference/agent-images) takes a prompt and images as top-level fields at `POST /v1/agent/images` (or `/v1/agent/images/run` with status at `/v1/agent/status`), instead of a `model_name` and `inputs` at `/v1/run`. It uses the same authentication, credits, and concurrency limits.

    #### Request Examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "endpoint-specific-model-name",
                   "inputs": {
                     // endpoint-specific parameters
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "endpoint-specific-model-name",
            inputs: {
              // endpoint-specific parameters
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "endpoint-specific-model-name",
            "inputs": {
              # endpoint-specific parameters
            }
          }
        )
        ```

### Universal Request Properties

**model_name** (`string`) *required*

Specifies which model/endpoint to use for processing. Each endpoint has its
  own unique model name.

**inputs** (`object`) *required*

Contains all the input parameters for the selected model. The structure of
  this object varies by endpoint.

## Single-Task Response Pattern

### Initial Response

When you submit a request to `/v1/run`, you'll receive an immediate response with a prediction ID:

  **Example Response:**

    ```json
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "error": null
    }
    ```

### Status Polling

Use the prediction ID to poll for status and results:

#### Response States

Poll for the status of a specific prediction using its ID.

**status** (`starting | in_queue | processing | completed | failed`)

The current state of your prediction:

- `starting` - Prediction is being initialized
- `in_queue` - Prediction is waiting to be processed
- `processing` - Model is actively generating your result
- `completed` - Generation finished successfully, output available
- `failed` - Generation failed, check error details

#### Response Headers

- `x-fashn-credits-used`: Indicates how many credits were consumed for that prediction.

#### Example Status Responses

**In Progress:**

  **Example Response:**

    ```json
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "status": "processing",
      "error": null
    }
    ```

**Completed:**

  **Example Response:**

    ```json
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "status": "completed",
      "output": [
        "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
      ],
      "error": null
    }
    ```

- **CDN URLs** (default): Outputs are scheduled for expiry after **three days**
- **Base64 outputs** (when `return_base64: true`): Available through the status endpoint for **60 minutes** after completion instead of the standard three-day window

Learn more in the [Data Retention & Privacy](/api-overview/data-retention-privacy) section.

**Failed:**

  **Example Response:**

    ```json
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "status": "failed",
      "error": {
        "name": "ImageLoadError",
        "message": "Error loading model image: Invalid URL format"
      }
    }
    ```

## Content Delivery

By default, output URLs are served from FASHN's content delivery network. Single-task endpoints return them in the `output` array, and the FASHN Agent API returns them in each prediction's `results`.* Depending on routing, outputs may be delivered from **either** of these domains:

- `https://cdn.fashn.ai/...`
- `https://media.fashn.ai/...`

Both are official FASHN delivery domains and are interchangeable. The outputs for a given prediction may be served from either one, and the serving domain can differ between requests. API outputs are scheduled for expiry after three days.

* This applies to the default delivery method. When you set `return_base64: true`, outputs are returned as base64-encoded strings instead of CDN URLs, so no `cdn.fashn.ai` or `media.fashn.ai` URL is produced.

## Error Handling

At a high level there are two kinds of errors you may see. For detailed guidance and the full list of error codes, see the [Error Handling](/api-overview/error-handling) page.

### API-Level Errors

These errors return an HTTP error code and a short payload. They can result from authentication, validation, quota, or server failures. Example:

  **Example Response:**

    ```json
    // HTTP 401 UnauthorizedAccess
    {
      "error": "UnauthorizedAccess",
      "message": "Unauthorized: Invalid token"
    }
    ```

No `id` or prediction `status` is returned.

### Runtime Errors

These happen **during** model execution after a prediction ID was returned. You’ll see them when polling `/v1/status/` with `status: "failed"`. Some runtime errors are common across endpoints (for example, malformed image URLs), while others are endpoint-specific validations; see [Error Handling](/api-overview/error-handling) for details. Example:

  **Example Response:**

    ```json
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "status": "failed",
      "error": {
        "name": "ImageLoadError",
        "message": "Error loading model image: Invalid URL format"
      }
    }
    ```

## Credits & Pricing

Credits are the billing unit for all FASHN API endpoints. Pricing is charged per successful output, and the exact cost depends on the endpoint and selected options.

### Billing Basics

- Failed predictions do **not** consume credits.
- Pricing is applied per output. If you request multiple outputs, the per-output cost is multiplied accordingly.
- Depending on the endpoint, pricing may be fixed per output, vary based on parameters such as `resolution`, `generation_mode`, or `duration`, or include optional surcharges such as `face_reference`.

Each endpoint page includes its own **Credit Cost** section. For a centralized overview, see the [API pricing guide: Credit Costs ↗](https://help.fashn.ai/plans-and-pricing/api-pricing#credit-costs).

## Rate Limits

These are the default rate limits that apply to all endpoints unless stated otherwise in the specific endpoint documentation:

| Endpoint                                     | Limit                       |
| -------------------------------------------- | --------------------------- |
| `/v1/run`                                    | 100 requests per 60 seconds |
| `/v1/status`                                 | 50 requests per 10 seconds  |
| `/v1/agent/images` and `/v1/agent/images/run` | 100 requests per 60 seconds |
| `/v1/agent/status`                           | 50 requests per 10 seconds  |

### Concurrency Limits

The API has a default concurrency limit of 6 requests per limit. This means you can have up to 6 concurrent requests being processed at any given time.

Our API rate limits are in place to ensure fair usage and prevent misuse of
  our services. However, we understand that legitimate applications may require
  higher limits as they grow. If your app's usage nears the specified rate
  limits, and this usage is justified by your application's needs, we will
  gladly increase your rate limit. Please reach out to our support@fashn.ai to
  discuss your specific requirements.

## Endpoint Lifecycle

Every FASHN API model has a lifecycle stage that describes its stability and integration guidance. See [Model Lifecycle](/api-overview/model-lifecycle) for stage definitions, release dates, and the current status of every model.

## Webhooks

Instead of polling for status, you can configure webhooks to receive notifications when predictions complete. See the [Webhooks Guide](/api-overview/webhooks) for setup instructions.

---

---
title: Model Lifecycle
description: Lifecycle stages and release dates for FASHN API models
---

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

# Model Lifecycle

Lifecycle stages and release dates for FASHN API models

Each FASHN API model has a lifecycle stage that indicates its stability and how changes are managed. Check this page when choosing a model or planning an upgrade.

## Lifecycle stages

| Stage            | What it means                                                                                               | Integration guidance                                                                 |
| ---------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| **Stable**       | Mature and supported for long-term use. Changes maintain backwards compatibility.                           | Recommended for production integrations that prioritize stability.                   |
| **Preview**      | Supported and approaching stable status. Output behavior may continue to improve before the stable release. | Suitable for production use when you can review output changes as the model evolves. |
| **Experimental** | Supported but still evolving. Behavior, parameters, or response schema may change.                          | Evaluate before production use and allow time to adapt to changes.                   |
| **Deprecated**   | Scheduled for discontinuation in favor of a newer model or workflow.                                        | Migrate to the recommended replacement before the stated retirement date.            |

## Current models

| Model                                                  | `model_name`        | Released           | Lifecycle        |
| ------------------------------------------------------ | ------------------- | ------------------ | ---------------- |
| [Agent Images](/api-reference/agent-images)            | —                   | October 26, 2026   | **Experimental** |
| [Try-On Max](/api-reference/tryon-max)                 | `tryon-max`         | January 26, 2026   | **Preview**      |
| [Product to Model](/api-reference/product-to-model)    | `product-to-model`  | September 2, 2025  | **Preview**      |
| [Face to Model](/api-reference/face-to-model)          | `face-to-model`     | September 19, 2025 | **Experimental** |
| [Model Create](/api-reference/model-create)            | `model-create`      | August 11, 2025    | **Experimental** |
| [Model Swap](/api-reference/model-swap)                | `model-swap`        | August 13, 2025    | **Experimental** |
| [Edit](/api-reference/edit)                            | `edit`              | December 1, 2025   | **Experimental** |
| [Reframe](/api-reference/reframe)                      | `reframe`           | August 14, 2025    | **Experimental** |
| [Image to Video](/api-reference/image-to-video)        | `image-to-video`    | October 15, 2025   | **Experimental** |
| [Background Remove](/api-reference/background-remove)  | `background-remove` | August 15, 2025    | **Experimental** |
| [FASHN Virtual Try-On v1.6](/api-reference/tryon-v1-6) | `tryon-v1.6`        | June 25, 2025      | **Stable**       |

Agent Images has its own endpoints (`/v1/agent/images`) and takes no `model_name`. The other models run through `/v1/run`.

A model can move between lifecycle stages without changing its `model_name`.

When a model is deprecated, this page will list its retirement date and recommended replacement.

---

---
title: Error Handling
description: Interpret and resolve API-level and runtime errors when calling the FASHN API.
---

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

# Error Handling

Interpret and resolve API-level and runtime errors when calling the FASHN API.

Understanding how the API reports errors helps you respond quickly and keep your integration resilient. There are two categories:

- **API-level errors:** The API returns an HTTP error instead of a prediction result.
- **Runtime errors:** The request was accepted, but the model failed during execution while you were polling or waiting on a webhook.

## API-Level Errors

These errors return an HTTP error status and do **not** include an `id` or prediction `status`. They can result from authentication, validation, quota, or server failures.

  **Example Response:**

    ```json
    // HTTP 401 UnauthorizedAccess
    {
      "error": "UnauthorizedAccess",
      "message": "Unauthorized: Invalid token"
    }
    ```

| Code | Error                    | Cause                           | How to fix                                                 |
| ---- | ------------------------ | ------------------------------- | ---------------------------------------------------------- |
| 400  | BadRequest               | Invalid request format          | Check JSON structure and required parameters.              |
| 401  | UnauthorizedAccess       | Invalid or missing API key      | Verify the `Authorization: Bearer YOUR_API_KEY` header.    |
| 404  | NotFound                 | Resource not found              | Confirm the endpoint URL and prediction ID.                |
| 429  | RateLimitExceeded        | Too many requests in the window | Add client-side throttling or backoff.                     |
| 429  | ConcurrencyLimitExceeded | Too many concurrent predictions | Wait for in-flight jobs to finish before sending new ones. |
| 429  | OutOfCredits             | No API credits remaining        | Refill credits before retrying.                            |
| 500  | InternalServerError      | Server-side error               | Retry with backoff; contact support if it persists.        |

## Runtime Errors

Runtime errors appear with `status: "failed"` when you poll `/v1/status/` (HTTP 200) or receive webhook payloads. The response includes the prediction ID and an `error` object.

  **Example Response:**

    ```json
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "status": "failed",
      "error": {
        "name": "ImageLoadError",
        "message": "Error loading model image: Invalid URL format"
      }
    }
    ```

### Common runtime errors

Most runtime issues fall into a handful of shared cases across endpoints. Start with these before checking model-specific validation rules.

| Name                     | Cause                                                                              | How to fix                                                                                                                                                                                                                                         |
| ------------------------ | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ImageLoadError`         | The API could not fetch or decode an input image or asset.                         | Use publicly accessible URLs with correct image Content-Type, or prefix base64 with `data:image/;base64,` and confirm the data is valid.                                                                                                   |
| `ContentModerationError` | An input image or text prompt violated content policies.                           | Replace or adjust the input to comply with [content policies ↗](https://fashn.ai/legal/terms-of-service). If the endpoint supports moderation controls (for example, `moderation_level`), choose the lowest level that still meets your safety requirements. |
| `InputValidationError`   | Parameters were invalid or inconsistent.                                           | Follow the error message to correct field values or required combinations before retrying.                                                                                                                                                         |
| `ThirdPartyError`        | An upstream provider refused or failed the request.                                | Retry with backoff. Some upstream services (e.g. captioning, translation) may silently block content; if retries continue to fail, treat it like a content policy block and adjust inputs accordingly.                                             |
| `UnavailableError`       | A service needed to fulfill the request was temporarily overloaded or unavailable. | Retry with backoff.                                                                                                                                                                                                                                |
| `PipelineError`          | An unexpected failure occurred inside the pipeline.                                | Retry with backoff.                                                                                                                                                                                                                                |

### Endpoint-specific runtime errors

Some models add extra validation tied to their workflow (for example, pose detection on virtual try-on or LoRA loading for variation). Refer to the Runtime Errors section on each endpoint page for those model-specific names and fixes.

### Retries and support

- Failed predictions do not consume credits.
- If you still see runtime failures after aligning inputs to the schema and retrying with backoff, contact support@fashn.ai with the prediction ID so we can investigate.

---

---
title: Webhooks
description: Stay informed in real time with FASHN webhooks. Receive instant notifications when a process completes, allowing seamless integration with your systems.
---

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

# Webhooks

Stay informed in real time with FASHN webhooks. Receive instant notifications when a process completes, allowing seamless integration with your systems.

Webhooks allow you to receive asynchronous notifications when a process completes. Instead of polling an endpoint to check the status, webhooks push updates directly to your specified URL.

## How to Use Webhooks

To use webhooks with our API, simply append the `webhook_url` parameter to your `/run` request:

```shellscript
POST https://api.fashn.ai/v1/run?webhook_url=https://your-server.com/webhook
```

When the process completes, our system will send a POST request to your specified webhook URL with the complete response payload.

## Webhook Retry Mechanism

Our system implements a robust retry mechanism to ensure webhook delivery:

- If a webhook delivery fails (non-2xx response), we automatically retry
- The system attempts up to 5 retries
- Retries occur within a timespan of approximately 5 minutes

## Example: Using Webhooks with the /run Endpoint

Based on the `/run` endpoint from the [Try-On Max API](/api-reference/tryon-max), here's how to implement webhooks:

```javascript
// Request to start a process with webhook notification
fetch(
  "https://api.fashn.ai/v1/run?webhook_url=https://your-server.com/webhook",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer YOUR_API_KEY",
    },
    body: JSON.stringify({
      model_name: "tryon-max",
      inputs: {
        model_image: "http://example.com/path/to/model.jpg",
        product_image: "http://example.com/path/to/garment.jpg",
      },
    }),
  },
);
```

### Success Webhook Payload

When the process completes successfully, your webhook URL will receive a POST request with a payload similar to:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.staging.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

### Error Webhook Payload

When the process has failed, your webhook URL will receive a POST request with a payload similar to:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "failed",
  "error": {
    "name": "ImageLoadError",
    "message": "Error loading model image: The URL's Content-Type is not an image. Content-Type: text/plain;charset=UTF-8"
  }
}
```

To learn more about runtime errors and how to handle them, check out our
  [Runtime Errors](/api-overview/error-handling#common-runtime-errors) guide.

## Best Practices

1. **Implement Idempotency**: Your webhook handler should be idempotent to handle potential duplicate deliveries.
2. **Respond Quickly**: Your webhook endpoint should respond with a 2xx status code as quickly as possible. Process the webhook data asynchronously if needed.
3. **Verify Webhooks**: Consider implementing a verification mechanism to ensure webhooks are coming from our service.
4. **Monitor Webhook Failures**: Set up monitoring for webhook failures to detect any issues with your endpoint.

## Troubleshooting

If you're not receiving webhook notifications:

- Verify your webhook URL is publicly accessible
- Check that your server responds with a 2xx status code
- Test your webhook endpoint with a tool like [Webhook.site ↗](https://webhook.site)

For additional support, contact our team at [support@fashn.ai](mailto:support@fashn.ai).

---

---
title: Data Retention & Privacy
description: What the FASHN API retains from each request, for how long, and how to minimize it.
---

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

# Data Retention & Privacy

What the FASHN API retains from each request, for how long, and how to minimize it.

The FASHN API keeps a record of each request for usage analytics, monitoring, and debugging, and holds generated outputs for a limited time so you can retrieve them. Request records store request details such as parameters and URLs, not copies of your images, and outputs expire within days. This page lists what is retained and for how long, then shows how to limit retention further with short-lived signed URLs or base64 inputs.

## What is retained, and for how long

| Data                                         | What is kept                                                                                                                                                 | How long                                                                                                      |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| **Request record**                           | Timestamp, model, parameters, submitted input URLs, `` placeholders for base64 inputs, output references, and status and error information           | Not deleted automatically                                                                                     |
| **Input image sent as a URL**                | The image is fetched only to process the request. The request record stores the submitted URL, not a copy of the image                                       | The URL string stays with the request record                                                                  |
| **Input image sent as base64**               | Used only to process the request                                                                                                                             | The temporary processing copy is deleted when the request finishes, with a one-day automatic cleanup backstop |
| **Output as a CDN URL** (default)            | The output file on FASHN's CDN                                                                                                                               | Scheduled for deletion after three days                                                                       |
| **Output as base64** (`return_base64: true`) | The output, returned by the status endpoint                                                                                                                  | Available for 60 minutes after completion, after which the status endpoint returns `"_expired"`       |
| **AI provider processing**                   | Images and prompts, processed by FASHN's AI and infrastructure providers ([Subprocessor List](https://fashn.ai/legal/subprocessors)) only to run the request | Governed by provider data-processing agreements                                                               |

FASHN does not use Customer Content to train, fine-tune, or improve its own or
  third-party AI models unless you expressly opt in through a separate
  agreement. This commitment is set out in the [Terms of
  Service](https://fashn.ai/legal/terms-of-service).

### What a request record can reveal

Request records power your [API analytics](https://app.fashn.ai/api/analytics), such as how many requests you made in the last 30 days, to which endpoints, how many succeeded or failed, and how many credits they used. You can also browse them in [request history](https://app.fashn.ai/api/requests) for monitoring and debugging. A record contains no image data of its own:

- **Base64 inputs and outputs** appear only as `` placeholders.
- **Submitted URLs** link to the image, which stays viewable only while the URL remains publicly accessible. A short-lived signed URL stops working once it expires.
- **Output URLs** stop serving the image once the output expires, although a CDN cache can briefly outlast deletion. Download any outputs you need to keep.

### Deleting request records

There is currently no deletion endpoint. To have request records deleted, contact [legal@fashn.ai](mailto:legal@fashn.ai) and include your Organization and the relevant prediction IDs.

## Minimizing what is retained

The examples below use [Try-On Max](/api-reference/tryon-max). The same approaches apply to all other endpoints where applicable.

| Strategy                                  | Send inputs as                                                                                  | Request record shows                                               |
| ----------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| **Short-lived signed URLs** (recommended) | URLs with the shortest validity period that still allows the request to complete                | URLs that become inaccessible after expiry                         |
| **Base64**                                | Base64-encoded strings                                                                          | `` placeholders                                            |
| **Hybrid**                                | URLs for non-sensitive images (product catalogs), base64 for sensitive images (customer photos) | Catalog image URLs and `` placeholders for customer photos |

Base64 increases the request size, so short-lived signed URLs are generally recommended for better reliability and can provide similar privacy. With any of these strategies, set `return_base64: true` to shorten the window during which the output is available.

A complete request using short-lived signed URLs:

```bash
curl -X POST https://api.fashn.ai/v1/run \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -d '{
           "model_name": "tryon-max",
           "inputs": {
             "model_image": "https://your-cdn.com/person.jpg?expires=1735689600&signature=...",
             "product_image": "https://your-cdn.com/garment.jpg?expires=1735689600&signature=...",
             "return_base64": true
           }
         }'
```

```js
const response = await fetch("https://api.fashn.ai/v1/run", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model_name: "tryon-max",
    inputs: {
      model_image:
        "https://your-cdn.com/person.jpg?expires=1735689600&signature=...",
      product_image:
        "https://your-cdn.com/garment.jpg?expires=1735689600&signature=...",
      return_base64: true,
    },
  }),
});
```

```python
import requests

response = requests.post(
    "https://api.fashn.ai/v1/run",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "model_name": "tryon-max",
        "inputs": {
            "model_image": "https://your-cdn.com/person.jpg?expires=1735689600&signature=...",
            "product_image": "https://your-cdn.com/garment.jpg?expires=1735689600&signature=...",
            "return_base64": True,
        },
    },
)
```

To send base64 instead, replace each URL with a data URI. The hybrid approach combines the two. In the following `inputs`, the customer photo is sent as base64 and the catalog image as a URL:

```json
{
  "model_image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
  "product_image": "https://your-cdn.com/catalog-garment.jpg",
  "return_base64": true
}
```

## Legal terms

FASHN's full terms are published in the [Legal Center](https://fashn.ai/legal): the [Terms of Service](https://fashn.ai/legal/terms-of-service), [Privacy Policy](https://fashn.ai/legal/privacy-policy), [Data Processing Addendum](https://fashn.ai/legal/dpa) for business customers, and [Subprocessor List](https://fashn.ai/legal/subprocessors).

---

---
title: Python
description: A quick start guide to FASHN for Python users using the official SDK
---

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

# Python

A quick start guide to FASHN for Python users using the official SDK

This guide shows you how to get started with FASHN's API using our official Python SDK. The SDK handles authentication, request/response parsing, error handling, and polling automatically.

For detailed documentation and how to use the FASHN API, please refer to:
- [API Reference](/api-reference)
- [Troubleshooting Guide](/guides/troubleshooting-guide)
- [GitHub Repository](https://github.com/fashn-AI/fashn-python-sdk)

Install the [FASHN agent skill](/getting-started/agent-skill) and Claude Code, Codex, Cursor, or another agent can wire this SDK into your project for you: `npx skills add fashn-ai/fashn-skill`.

## Installation

First, install the FASHN Python SDK:

  ```bash
  pip install fashn
  ```

  ```bash
  uv add fashn
  ```

  ```bash
  poetry add fashn
  ```

## Generate an API Key

Go to the [Developer API dashboard](https://app.fashn.ai/api) and click **Create new API key**. 
You won't be able to view it again after closing the window.

## Quick Start with the SDK

The SDK's `subscribe` method handles the entire prediction lifecycle automatically - it submits your request, polls for completion, and returns the final result. You can use any `model_name` from our [API Reference](/api-reference) section with their respective input parameters.

### Synchronous

```python
import os
from fashn import Fashn

client = Fashn(
    api_key=os.environ.get("FASHN_API_KEY"), # This is the default and can be omitted
)

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

print("Generation completed!")
print("Result:", result)
print("Credits used:", result.credits_used)
```

### Async

```python
import os
import asyncio
from fashn import AsyncFashn

async def main():
    client = AsyncFashn(
        api_key=os.environ.get("FASHN_API_KEY"),  # This is the default and can be omitted
    )

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

    print("Generation completed!")
    print("Result:", result)
    print("Credits used:", result.credits_used)

asyncio.run(main())
```

### Response

The `subscribe` method returns a response with these attributes:

- `id`: Prediction ID.
- `status`: Current state of the prediction.
- `output`: Generated outputs when the prediction completes successfully.
- `error`: Error details when `status` is `failed`.
- `credits_used`: Number of credits consumed for that prediction. Present only when `status` is `completed`.

## Error Handling

The FASHN API has two distinct types of errors that you need to handle in different places. For a complete list of all error types and status codes, see the [API Fundamentals Error Handling](/api-overview/api-fundamentals#error-handling) section.

```python
import os
import fashn
from fashn import Fashn

client = Fashn(
    api_key=os.environ.get("FASHN_API_KEY"),  # This is the default and can be omitted
)

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

    # 1. Check for Runtime Errors (during model execution). Status can be failed, canceled or time_out.
    if result.status != "completed":
        print("Runtime Error - Status:", result.status)
        if result.error:
            print("Error message:", result.error.message)
    else:
        # 2. Success case (status is completed)
        print("Generation completed successfully!")
        print("Generated:", result.output)

except fashn.APIError as e:
    # 3. Handle API-Level Errors (before request processing)
    print("API-Level Error - Status:", e.status_code)
    print("Message:", e.message)
except Exception as e:
    # Network or unexpected error
    print("Network or unexpected error:", e)
```

**API-Level Errors** (handled in `except` blocks):
- Occur before your request is accepted for processing
- Examples: invalid API key (401), rate limits (429), bad request format (400)
- Thrown as exceptions with `e.status_code` and `e.message`

**Runtime Errors** (check `result.status`):
- Occur during model execution after successful request submission  
- Examples: image loading failures, content moderation, pose detection issues
- Available in `result.error` fields when present

## Configuration

Advanced configuration options (retries, timeouts, proxies, custom HTTP client) are available in our open source GitHub repository: [fashn-python-sdk](https://github.com/fashn-AI/fashn-python-sdk).

## Advanced Usage

The SDK provides methods to submit a request and fetch the status of a request separately. If you choose this workflow you would need to:
1. Submit a request
2. Poll for the status of the request until it is completed

The subscribe method described above already implements this workflow with good defaults and better error handling.
We only recommend using this workflow if you have a specific use case that requires it.

### Submit a request

Submit a request to the API and get a prediction ID.

```python
import os
from fashn import Fashn

client = Fashn(api_key=os.environ.get("FASHN_API_KEY"))

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

print("Prediction ID:", response.id)
```

### Fetch request status

Use the prediction ID returned from the run method to fetch the status of the request.

```python
import os
from fashn import Fashn

client = Fashn(api_key=os.environ.get("FASHN_API_KEY"))

status = client.predictions.status(
    "9dafef71-6e90-4bc9-ac05-d0d97c612722"  # Prediction ID
)

print("Prediction Status:", status.status)
```

---

---
title: TypeScript
description: A quick start guide to FASHN for TypeScript users using the official SDK
---

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

# TypeScript

A quick start guide to FASHN for TypeScript users using the official SDK

This guide shows you how to get started with FASHN's API using our official TypeScript SDK. The SDK handles authentication, request/response parsing, error handling, and polling automatically.

Use this SDK on the server-side only. Never expose your `FASHN_API_KEY` in client-side or browser code.

For detailed documentation and how to use the FASHN API, please refer to:
- [API Reference](/api-reference)
- [Troubleshooting Guide](/guides/troubleshooting-guide)
- [GitHub Repository](https://github.com/fashn-AI/fashn-typescript-sdk)
- [Next.js quickstart](/guides/nextjs-quickstart)
- [React Router quickstart](/guides/react-router-quickstart)

Install the [FASHN agent skill](/getting-started/agent-skill) and Claude Code, Codex, Cursor, or another agent can wire this SDK into your project for you: `npx skills add fashn-ai/fashn-skill`.

## Installation

First, install the FASHN SDK:

  ```bash
  npm install fashn
  ```

  ```bash
  yarn add fashn
  ```

  ```bash
  pnpm add fashn
  ```

## Generate an API Key

Go to the [Developer API dashboard](https://app.fashn.ai/api) and click **Create new API key**. 
You won't be able to view it again after closing the window.

## Quick Start with the SDK

The SDK's `subscribe` method handles the entire prediction lifecycle automatically - it submits your request, polls for completion, and returns the final result. You can use any `model_name` from our [API Reference](/api-reference) section with their respective input parameters.

```typescript

const client = new Fashn({
  apiKey: process.env.FASHN_API_KEY, // This is the default and can be omitted
});

async function runGeneration() {
  const response = await client.predictions.subscribe({
    model_name: "tryon-max",
    inputs: {
      model_image: "https://example.com/path/to/model.jpg",
      product_image: "https://example.com/path/to/garment.jpg",
    },
  });

  console.log("Generation completed!");
  console.log("Result:", response);
  console.log("Credits used:", response.creditsUsed);
}

// Run the generation
runGeneration();
```

### Response Object

The `subscribe` method resolves to a response object with these fields:

- `id`: Prediction ID.
- `status`: Current state of the prediction.
- `output`: Generated outputs when the prediction completes successfully.
- `error`: Error details when `status` is `failed`.
- `creditsUsed`: Number of credits consumed for that prediction. Present only when `status` is `completed`.

## Error Handling

The FASHN API has two distinct types of errors that you need to handle in different places. For a complete list of all error types and status codes, see the [API Fundamentals Error Handling](/api-overview/api-fundamentals#error-handling) section.

```typescript

const client = new Fashn({
  apiKey: process.env.FASHN_API_KEY,
});

async function runGeneration() {
  try {
    const response = await client.predictions.subscribe({
      model_name: "tryon-max",
      inputs: {
        model_image: "https://example.com/model.jpg",
        product_image: "https://example.com/garment.jpg",
      },
    });

    // 1. Check for Runtime Errors (during model execution). Status can be failed, canceled or time_out.
    if (response.status !== "completed") {
      console.error("Runtime Error - Status:", response.status);
      console.error("Error message:", response.error?.message);
      return;
    }

    // 2. Success case (status is completed)
    console.log("Generation completed successfully!");
    console.log("Generated:", response.output);
  } catch (error) {
    // 3. Handle API-Level Errors (before request processing)
    if (error instanceof Fashn.APIError) {
      console.error("API-Level Error - Status:", error.status);
      console.error("Message:", error.message);
    } else {
      console.error("Network or unexpected error:", error);
    }
  }
}

runGeneration();
```

**API-Level Errors** (handled in `catch` block):
- Occur before your request is accepted for processing
- Examples: invalid API key (401), rate limits (429), bad request format (400)
- Thrown as exceptions with `error.status` and `error.message`

**Runtime Errors** (check `response.status`):
- Occur during model execution after successful request submission  
- Examples: image loading failures, content moderation, pose detection issues
- Available in `response.error.name` and `response.error.message`

## Configuration

All configuration options are available in our open source GitHub repository: [fashn-typescript-sdk](https://github.com/fashn-AI/fashn-typescript-sdk). You can explore the source code, contribute, or check out advanced configuration options and examples.

## Advanced Usage

The SDK provides methods to submit a request and fetch the status of a request separately. If you choose this workflow you would need to:
1. Submit a request
2. Poll for the status of the request until it is completed

The subscribe method described above already implements this workflow with good defaults and better error handling.
We only recommend using this workflow if you have a specific use case that requires it.

### Submit a request

Submit a request to the API and get a prediction ID.

```typescript

const client = new Fashn({
  apiKey: process.env.FASHN_API_KEY,
});

const response = await client.predictions.run({
  model_name: "tryon-max",
  inputs: {
    model_image: "https://example.com/model.jpg",
    product_image: "https://example.com/garment.jpg",
  },
});

console.log("Prediction ID:", response.id);
```

### Fetch request status

Use the prediction ID returned from the run method to fetch the status of the request.

```typescript

const client = new Fashn({
  apiKey: process.env.FASHN_API_KEY,
});

const response = await client.predictions.status(
  "9dafef71-6e90-4bc9-ac05-d0d97c612722" // Prediction ID
);

console.log("Prediction Status:", response.status);
```

---

---
title: Agent Images: Fashion AI Agent API
description: The FASHN Agent API for agentic fashion content creation. Send a prompt and up to 6 images, and get back on-model photos, packshots, and lookbooks.
---

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

# Agent Images: Fashion AI Agent API

The FASHN Agent API for agentic fashion content creation. Send a prompt and up to 6 images, and get back on-model photos, packshots, and lookbooks.

Agent Images is the FASHN Agent API endpoint: a fashion AI agent that turns a plain-language request into finished images. Describe the result in a prompt and attach up to six images, such as product photos, a model photo, or a location. The FASHN Agent decides which operations the request needs, such as a try-on, a model swap, or an edit, runs them, and returns every image it made.

Use it for agentic fashion content creation: on-model product photos, packshots, catalog images, and lookbooks. One request can cover several steps that would otherwise take a chain of calls to the [single-task endpoints](/api-reference#single-task-endpoints). It is a plain REST endpoint, so your own code can call it, or a coding agent such as Claude Code, Codex, or Cursor can call it for you. Your agent acts as the producer and the FASHN Agent as the photographer. See [Use it from a coding agent](#use-it-from-a-coding-agent).

New to the Agent? The [FASHN Agent API Quickstart](/getting-started/agent-quickstart) walks through a first request and example prompts.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** October 26, 2026

## Request body

Send the parameters documented under [Input parameters](#input-parameters) as top-level fields of a JSON object. A field not listed there is rejected with `400 BadRequest`.

## Request

Run the Agent and wait for its images in the same request:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/agent/images \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "prompt": "Put the dress from the second image on the model in the first image",
                   "images": [
                     "https://example.com/person.jpg",
                     "https://example.com/dress.jpg"
                   ]
                 }'
        ```

        ```javascript
        const response = await fetch('https://api.fashn.ai/v1/agent/images', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'
          },
          body: JSON.stringify({
            prompt: "Put the dress from the second image on the model in the first image",
            images: [
              "https://example.com/person.jpg",
              "https://example.com/dress.jpg"
            ]
          })
        });

        const result = await response.json();
        for (const prediction of result.predictions) {
          console.log(prediction.tool, prediction.results);
        }
        ```

        ```python
        import requests

        response = requests.post(
            'https://api.fashn.ai/v1/agent/images',
            headers={
                'Content-Type': 'application/json',
                'Authorization': 'Bearer YOUR_API_KEY'
            },
            json={
                "prompt": "Put the dress from the second image on the model in the first image",
                "images": [
                    "https://example.com/person.jpg",
                    "https://example.com/dress.jpg"
                ]
            }
        )

        result = response.json()
        for prediction in result['predictions']:
            print(prediction['tool'], prediction['results'])
        ```

    #### Response

        Returns every image the Agent made:

          **Example Response:**

            ```json
            {
              "id": "3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18",
              "predictions": [
                {
                  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
                  "tool": "generate-image",
                  "results": [
                    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
                  ],
                  "credits_used": 1
                }
              ],
              "credits_used": 1
            }
            ```

The request stays open until the Agent finishes, which takes about 40 seconds for one image at the default settings and longer for requests with several steps. To avoid holding a connection open, use an [asynchronous run](#asynchronous-runs) instead.

## Input parameters

**prompt** (`string`) *required*

What you want, in plain language: between 1 and 10,000 characters. Refer to
  the images by their position ("the first image", "the dress in the second
  image") or by what they show.

The Agent never asks a question back. When the prompt is unclear, it makes the best guess that fits the prompt and the images.

**images** (`(image URL | data URI)[]`)

Up to 6 images, in the order the prompt refers to them. Each item is a
  publicly accessible `http(s)` image URL or a base64 data URI
  (`data:image/;base64,...`).

**Default:** `[]` (the Agent generates from the prompt alone)

**aspect_ratio** (`1:1 | 2:3 | 3:2 | 3:4 | 4:3 | 4:5 | 5:4 | 9:16 | 16:9 | 21:9`)

Aspect ratio of the generated images. An aspect ratio asked for in the
  prompt takes precedence.

**Default:** None. The Agent chooses: an edit keeps the edited image's frame, and a new image gets a frame that suits the request.

**resolution** (`1k | 2k | 3k | 4k`)

Output resolution tier of the generated images. `'1k'` produces about 1
  megapixel, `'2k'` about 4, `'3k'` about 9, and `'4k'` about 16. An output
  size asked for in the prompt takes precedence. Some images are made and
  billed at `'2k'` when `'3k'` or `'4k'` is requested.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level for every image the Agent generates.
  `'quality'` produces the most detailed and realistic output but takes longer
  and costs more credits. `'fast'` prioritizes speed and lower cost.

**Default:** `balanced`

**return_base64** (`boolean`)

When set to `true`, every image in `results` is returned as a base64 data URI
  (`data:image/png;base64,...`) instead of a CDN URL.

The images are still stored on the CDN for three days.

**Default:** `false`

## What the Agent can do

For each request, the Agent can:

- **Generate images:** create new images or edit existing ones, including try-on, product-to-model, model creation and swap, background changes, packshots, and transparent images.
- **Upscale images:** enlarge an image or restore its detail.
- **Remove backgrounds:** return a transparent cutout of an image.

Each of these counts as one operation; inspecting its own results does not.

A request for several images, such as "three angles" or "two colorways", makes one image per generation. The Agent adds no steps you did not ask for, such as an upscale or a variation.

The Agent makes images only. A request for a video, or one that cannot be met with images, fails with `NoImageGenerated`.

## Use it from a coding agent

Claude Code, Codex, Cursor, and other coding agents can call Agent Images for you. Your agent finds the photos, sends the request, and saves the results, and the FASHN Agent makes the images.

**Follow a recipe.** The [lookbook recipe](https://docs.fashn.ai/recipes/lookbook.md) is a set of instructions, written for Claude Code, that makes a four-look lookbook from six photos in one call. Open Claude Code in a folder with a face photo, a location photo, and four outfit photos, then paste:

```text
Download https://docs.fashn.ai/recipes/lookbook.md with curl and follow it exactly
```

The recipe sets up your API key in a `.env` file, confirms which photo is which, and saves the looks in a new folder. [How to make an AI lookbook with Claude Code ↗](https://fashn.ai/blog/fashn-agent-api-getting-started) walks through a full run.

**Point your agent at this page.** Every page of these docs is also available as Markdown. Ask your agent to read `https://docs.fashn.ai/api-reference/agent-images.md` and build the request your project needs, for example a script that turns every product photo in a folder into an on-model photo.

See [Coding Agents](/getting-started/agent-skill) for more ways to use FASHN from a coding agent.

## Technical limitations

| Requirement       | Limit             |
| ----------------- | ----------------- |
| Input images      | 6 per request     |
| Base64 image size | 10 MB per image   |
| Image formats     | JPEG, PNG, WebP   |
| Prompt length     | 10,000 characters |
| Operations        | 8 per request     |
| Request duration  | 15 minutes        |

A request with too many images, a base64 image over 10 MB, or a prompt over 10,000 characters fails with `400 BadRequest`. An image the Agent cannot read, such as one in another format, fails with `422 BadRequest`.

A request that reaches 8 operations stops and returns the images made so far. A request still running after 15 minutes stops the same way. If it made no image, it fails with `504 AgentTimeout`. Generations still running at that point complete and are billed, but are not returned.

Each operation counts against your [concurrency limit](/api-overview/api-fundamentals#concurrency-limits) while it runs. [Rate limits](/api-overview/api-fundamentals#rate-limits) are 100 requests per 60 seconds to start a run and 50 requests per 10 seconds for `/v1/agent/status`.

## Credit cost

You pay only for the images the Agent makes. Each generated image costs:

| `generation_mode` \ `resolution` | `1k` | `2k` | `3k` | `4k` |
| -------------------------------- | ---- | ---- | ---- | ---- |
| `fast`                           | 1    | 1    | 1    | 1    |
| `balanced`                       | 1    | 2    | 3    | 3    |
| `quality`                        | 2    | 3    | 4    | 4    |

Additional pricing rules:

- An upscale or a background removal costs 1 credit.
- A request costs the sum of its operations, intermediate images included, with at most 8 operations per request, so at most 32 credits.
- Failed operations do not consume credits.
- The top-level `credits_used` field and the `X-Fashn-Credits-Used` response header give the exact cost of the request, and each entry in `predictions` gives its own.

## Response

**id** (`string`)

ID of the Agent run. Errors returned after the run starts include it too.

**predictions** (`object[]`)

Every operation that produced images, in the order the Agent ran them,
  intermediate steps included. Each entry has:

- `id`: the prediction ID.
- `tool`: the operation, `generate-image`, `image-upscale`, or `background-remove`.
- `results`: the images it produced, as CDN URLs, or as data URIs with `return_base64`.
- `credits_used`: the credits it consumed.

**credits_used** (`integer`)

Total credits consumed by the request.

The Agent's text is never returned.

## Asynchronous runs

To avoid waiting on an open request, start the run, then poll its status or receive it on a webhook. The run takes the same request body as `/v1/agent/images`:

    #### Request example

        ```bash
        curl -X POST "https://api.fashn.ai/v1/agent/images/run?webhook_url=https://your-server.com/webhook" \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "prompt": "Put the dress from the second image on the model in the first image",
                   "images": [
                     "https://example.com/person.jpg",
                     "https://example.com/dress.jpg"
                   ]
                 }'
        ```

    #### Response

        Returns the run ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18",
              "error": null
            }
            ```

With the optional `webhook_url` query parameter, FASHN sends the run's result to that URL when the run ends, with the same body as a completed or failed status response. See [Webhooks](/api-overview/webhooks).

### Status polling

Poll the run with the ID returned when it started:

The response follows the `/v1/status` states, `processing`, `completed`, and `failed`, with no partial results while the run is processing. A completed run returns the same `predictions` and `credits_used` as the synchronous response, and sets the `X-Fashn-Credits-Used` header:

```json
{
  "id": "3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18",
  "status": "completed",
  "predictions": [
    {
      "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
      "tool": "generate-image",
      "results": [
        "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
      ],
      "credits_used": 1
    }
  ],
  "credits_used": 1,
  "error": null
}
```

A failed run returns the error:

```json
{
  "id": "3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18",
  "status": "failed",
  "error": {
    "name": "NoImageGenerated",
    "message": "The agent did not generate an image for this request. Make the prompt more specific or check the input images."
  }
}
```

A run that does not exist, or that belongs to another user, returns `404`.

## Errors

An invalid request fails before the run starts, with the [API-level errors](/api-overview/error-handling#api-level-errors), such as `400 BadRequest` or `429 RateLimitExceeded`. When a generation is refused for your credits or concurrency limit and the run made no image, the run fails with that `429` error, `OutOfCredits` or `ConcurrencyLimitExceeded`.

Otherwise, a run that made no image fails with one of the errors below. A synchronous request returns it with the HTTP status shown and the run's `id`, and an asynchronous run returns it as its `failed` status.

| Code | Name                  | Cause                                                                                  | How to fix                                                                       |
| ---- | --------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| 422  | `NoImageGenerated`    | The Agent did not make an image, for example for a video request or an unclear prompt. | Make the prompt more specific, or check the input images.                        |
| 422  | `ImageLoadError`      | An input image URL could not be downloaded.                                            | Use publicly accessible image URLs, or send the images as base64.                |
| 422  | `BadRequest`          | An input image could not be read.                                                      | Send JPEG, PNG, or WebP images, and a smaller version of a very large image.     |
| 422  | Runtime error name    | The Agent's last generation failed, for example with `ContentModerationError`.         | See [Common runtime errors](/api-overview/error-handling#common-runtime-errors). |
| 504  | `AgentTimeout`        | The request ran longer than 15 minutes and made no image.                              | Simplify the request, or split it into several requests.                         |
| 500  | `InternalServerError` | The run failed unexpectedly.                                                           | Retry with backoff; contact support@fashn.ai with the run `id` if it persists.   |

```json
// HTTP 422 NoImageGenerated
{
  "error": "NoImageGenerated",
  "message": "The agent did not generate an image for this request. Make the prompt more specific or check the input images.",
  "id": "3c1f6a52-8e0b-4d7a-9a51-2f4b7c9d0e18"
}
```

When the Agent made at least one image, the run succeeds with the images it made, even if a later step failed.

## Data handling

Base64 input images are stored privately while the run uses them, and deleted after it ends. Generated images follow the standard [data retention](/api-overview/data-retention-privacy) of API outputs.

## Related guides

- **[FASHN Agent API Quickstart](/getting-started/agent-quickstart)** - Make a first request and try example prompts for fashion content
- **[Coding Agents](/getting-started/agent-skill)** - Use FASHN from Claude Code, Codex, Cursor, and other coding agents
- **[Prompting in FASHN ↗](https://help.fashn.ai/usage-guides/prompting-in-fashn)** - Learn how to write effective prompts for best results
- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your input images for better results
- **[Data Retention & Privacy](/api-overview/data-retention-privacy)** - Understand how FASHN handles your data

---

---
title: Try-On Max
description: FASHN's most capable virtual try-on model, with enhanced fidelity, up to 4K resolution, and prompt-based customization
---

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

# Try-On Max

FASHNs most capable virtual try-on model, with enhanced fidelity, up to 4K resolution, and prompt-based customization

Try-On Max is our recommended virtual try-on endpoint, built for AI fashion photoshoots and publishable e-commerce content. It places products onto model images with enhanced fidelity, producing images suitable for PDPs, catalogs, and marketing assets.

This endpoint supports clothing, shoes, hats, jewelry, bags, and other wearable fashion items.

**Lifecycle:** [Preview](/api-overview/model-lifecycle) · **Released:** January 26, 2026

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `tryon-max`.                                                                              |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Generate try-on images by submitting your product and model images to the universal `/v1/run` endpoint:

    #### Request examples

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

        ```javascript
        const response = await fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'
          },
          body: JSON.stringify({
            model_name: "tryon-max",
            inputs: {
              product_image: "https://example.com/garment.jpg",
              model_image: "https://example.com/person.jpg"
            }
          })
        });

        const result = await response.json();
        console.log('Prediction ID:', result.id);
        ```

        ```python
        import requests

        response = requests.post(
            'https://api.fashn.ai/v1/run',
            headers={
                'Content-Type': 'application/json',
                'Authorization': 'Bearer YOUR_API_KEY'
            },
            json={
                "model_name": "tryon-max",
                "inputs": {
                    "product_image": "https://example.com/garment.jpg",
                    "model_image": "https://example.com/person.jpg"
                }
            }
        )

        result = response.json()
        print('Prediction ID:', result['id'])
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**product_image** (`image URL | data URI`) *required*

Product image (garment, accessory, etc.) to place on the model.

**model_image** (`image URL | data URI`) *required*

Image of the person who will wear the product. The try-on process preserves
  the model's identity, pose, and styling while seamlessly integrating the
  product.

**prompt** (`string`)

Optional instructions to customize the try-on result. Use this to adjust how the product is worn or make minor styling changes.

Examples: `"remove scarf"`, `"tuck in shirt"`, `"roll up sleeves"`, `"open jacket"`.

**Default:** Empty string (uses intelligent defaults based on the images)

**resolution** (`1k | 2k | 4k`)

Output resolution tier. `'1k'` produces ~1 megapixel output, `'2k'` ~4 megapixels, and `'4k'` ~16 megapixels. Exact output dimensions depend on this tier and the image aspect ratio.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level. `'quality'` produces the most detailed and
  realistic output but takes longer to process and costs more credits.
  `'balanced'` offers a middle ground between speed and quality. `'fast'`
  prioritizes speed and lower cost. If omitted, FASHN selects `generation_mode`
  automatically. For `tryon-max`, omitted `generation_mode` is currently billed
  as `'balanced'` at all resolutions.

**seed** (`integer`)

Sets random operations to a fixed state. Use the same seed to reproduce results with the same inputs, or a different seed to force different results.

**Default:** `42` · **Range:** `0` to `2^32 - 1`

**num_images** (`integer`)

Number of images to generate in a single request. Must be between 1 and 4. Additional images consume more compute (and credits) and can increase processing time.

**Default:** `1`

**output_format** (`png | jpeg`)

Specifies the output image format.

- `png`: Lossless quality, best for further editing or when maximum fidelity is needed.
- `jpeg`: Smaller file size with slight compression, suitable for direct web use.

**Default:** `png`

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed according to the `output_format` (e.g., `data:image/png;base64,...` or `data:image/jpeg;base64,...`).

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 15 × 15 px       |
| Aspect ratio       | 1:16 to 16:1     |

Inputs outside these limits fail with `InputValidationError`. The output `resolution` does not change the input limits.

## Credit cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `fast`                           | 1    | 2    | 3    |
| `balanced`                       | 2    | 3    | 4    |
| `quality`                        | 3    | 4    | 5    |

Additional pricing rules:

- `num_images` multiplies the total cost by the number of outputs requested.
- If `generation_mode` is omitted, automatic pricing applies.

## Processing time

Processing time depends on both `resolution` and `generation_mode`. The fastest configuration (`fast` + `1k`) typically completes in around 10 seconds, `balanced` at `2k` finishes in around 25 seconds, and the most intensive combination (`quality` + `4k`) typically takes around 55 seconds. Actual latency may vary with current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your try-on generation completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

The `output` array contains URLs to your generated try-on images with the product seamlessly placed on the model.

## Runtime errors

Runtime errors for Try-On Max use the shared set in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

- **[Prompting in FASHN ↗](https://help.fashn.ai/usage-guides/prompting-in-fashn)** - Learn how to write effective prompts for best results
- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your input images for better results
- **[Data Retention & Privacy](/api-overview/data-retention-privacy)** - Understand how FASHN handles your data

---

---
title: FASHN Virtual Try-On v1.6
description: Fast, lightweight virtual try-on optimized for real-time e-commerce experiences
---

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

# FASHN Virtual Try-On v1.6

Fast, lightweight virtual try-on optimized for real-time e-commerce experiences

Virtual Try-On v1.6 is a fast, lightweight virtual try-on model optimized for real-time e-commerce integrations.

**Lifecycle:** [Stable](/api-overview/model-lifecycle) · **Released:** June 25, 2025

[Try-On Max](/api-reference/tryon-max) is our recommended virtual try-on endpoint, offering higher resolution (up to 4K), broader item support (shoes, hats, jewelry, bags), and prompt-based customization. Use v1.6 when speed and cost are your primary concerns.

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `tryon-v1.6`.                                                                             |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Generate a virtual try-on by submitting your model and garment images to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "tryon-v1.6",
                   "inputs": {
                     "model_image": "http://example.com/path/to/model.jpg",
                     "garment_image": "http://example.com/path/to/garment.jpg"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "tryon-v1.6",
            inputs: {
              model_image: "http://example.com/path/to/model.jpg",
              garment_image: "http://example.com/path/to/garment.jpg"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "tryon-v1.6",
            "inputs": {
              "model_image": "http://example.com/path/to/model.jpg",
              "garment_image": "http://example.com/path/to/garment.jpg"
            }
          }
        )
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**model_image** (`image URL | data URI`) *required*

Primary image of the person on whom the virtual try-on will be performed.

**garment_image** (`image URL | data URI`) *required*

Reference image of the clothing item to be tried on the `model_image`.

**category** (`auto | tops | bottoms | one-pieces`)

Use `auto` to enable automatic classification of the garment type. For flat-lay or ghost mannequin images, the system detects the garment type automatically. For on-model images, full-body shots default to a full outfit swap. For focused shots (upper or lower body), the system selects the most likely garment type (tops or bottoms).

**Default:** `auto`

**segmentation_free** (`boolean`)

Direct garment fitting without clothing segmentation, enabling bulkier garment try-ons with improved preservation of body shape and skin texture. Set to `false` if original garments are not removed properly.

**Default:** `true`

**moderation_level** (`conservative | permissive | none`)

Sets the content moderation level for garment images.

-`conservative` enforces stricter modesty standards suitable for culturally sensitive contexts. Blocks underwear, swimwear, and revealing outfits.

-`permissive` allows swimwear, underwear, and revealing garments, while still
blocking explicit nudity.

-`none` disables all content moderation

**Default:** `permissive`

This technology is designed for ethical virtual try-on applications. Misuse—such as generating inappropriate imagery without consent—violates our [Terms of Service ↗](https://fashn.ai/legal/terms-of-service).

Setting `moderation_level: none` does not remove your responsibility for ethical and lawful use. **Violations may result in service denial**.

**garment_photo_type** (`auto | flat-lay | model`)

Specifies the type of garment photo to optimize internal parameters for better performance. 'model' is for photos of garments on a model, 'flat-lay' is for flat-lay or ghost mannequin images, and 'auto' attempts to automatically detect the photo type.

**Default:** `auto`

**mode** (`performance | balanced | quality`)

Specifies the mode of operation.

-`performance` mode is faster but may compromise quality

-`balanced` mode is a perfect middle ground between speed and quality

-`quality` mode is slower, but delivers the highest quality results.

**Default:** `balanced`

**seed** (`int`)

Sets random operations to a fixed state. Use the same seed to reproduce
  results with the same inputs, or different seed to force different results.

**Default:** `42` · **Range:** `0` to `2^32 - 1`

**num_samples** (`int`)

Number of images to generate in a single run. Image generation has a random
  element in it, so trying multiple images at once increases the chances of
  getting a good result.

**Default:** `1` · **Range:** `1` to `4`

**output_format** (`png | jpeg`)

Specifies the desired output image format.

-`png`: Delivers the highest quality image, ideal for use cases such as content creation where quality is paramount.

-`jpeg`: Provides a faster response with a slightly compressed image, more
suitable for real-time applications like consumer virtual try-on experiences.

**Default:** `png`

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed according to the `output_format` (e.g., `data:image/png;base64,...` or `data:image/jpeg;base64,...`).

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

Input images are processed at 864 × 1296 px.

## Credit cost

Virtual Try-On v1.6 costs 1 credit per output image. The `num_samples` value determines the number of outputs and therefore the total cost.

## Processing time

| `mode`        | Typical processing time                                |
| ------------- | ------------------------------------------------------ |
| `performance` | About 5 seconds                                        |
| `balanced`    | About 8 seconds                                        |
| `quality`     | About 12–17 seconds, depending on the input resolution |

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your virtual try-on completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

The `output` array contains URLs to your generated try-on images showing the model wearing the specified garment. The number of images depends on the `num_samples` parameter (default: 1).

## Runtime errors

Try-On shares the common runtime errors in [Error Handling](/api-overview/error-handling#common-runtime-errors). Additional endpoint-specific errors:

| Name        | Cause                                                                                                                              | Solution                                                                                                                                             |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PoseError` | The pipeline was unable to detect a body pose in either the model image or the garment image (when `garment_photo_type: "model"`). | Improve model or garment photo quality following the [model photo guidelines ↗](https://utfs.io/f/wXFHUNfTHmLj93Xx8jWT5IXsA4Lhru0e7dJiKFwpQ6Glm28S). |

## Related guides

For detailed implementation guidance and best practices specific to Virtual Try-On:

- **[Try-On Parameters Guide](/guides/tryon-parameters-guide)** - Detailed parameter optimization for try-on models
- **[Python Quickstart Guide](/guides/tryon-python-quickstart-guide)** - Complete Python implementation examples
- **[JavaScript Quickstart Guide](/guides/tryon-javascript-quickstart-guide)** - Frontend integration patterns
- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your input images for better results
- **[Data Retention & Privacy](/api-overview/data-retention-privacy)** - Understand how FASHN handles your data

---

---
title: Product to Model
description: Transform product images into people wearing those products, with optional inspiration, background, and face reference inputs
---

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

# Product to Model

Transform product images into people wearing those products, with optional inspiration, background, and face reference inputs

Powered by best-in-class image editing AI, the **Product to Model** endpoint transforms product images into people wearing those products, with optional guidance from an inspiration image, background, or face reference.

This endpoint is designed specifically for **wearable fashion items** such as clothing, shoes, hats, jewelry, bags, and accessories.

**Lifecycle:** [Preview](/api-overview/model-lifecycle) · **Released:** September 2, 2025

To place a product on an existing person image while preserving that image's
  pose and background, use the [`tryon-max`](/api-reference/tryon-max) endpoint
  with `model_image`. On Product to Model, a model's identity is passed via
  `face_reference` instead, and the endpoint generates a new image of that
  person wearing the product; it does not replace the clothing or keep the pose
  and background of the reference photo.

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `product-to-model`.                                                                       |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Generate product-to-model images by submitting your product image to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "product-to-model",
                   "inputs": {
                     "product_image": "http://example.com/path/to/product.jpg",
                     "prompt": "professional office setting",
                     "output_format": "png",
                     "return_base64": false
                   }
                 }'
        ```

        ```javascript
        const response = await fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'
          },
          body: JSON.stringify({
            model_name: "product-to-model",
            inputs: {
              product_image: "http://example.com/path/to/product.jpg",
              prompt: "professional office setting",
              output_format: "png",
              return_base64: false
            }
          })
        });

        const result = await response.json();
        console.log('Prediction ID:', result.id);
        ```

        ```python
        import requests

        response = requests.post(
            'https://api.fashn.ai/v1/run',
            headers={
                'Content-Type': 'application/json',
                'Authorization': 'Bearer YOUR_API_KEY'
            },
            json={
                "model_name": "product-to-model",
                "inputs": {
                    "product_image": "http://example.com/path/to/product.jpg",
                    "prompt": "professional office setting",
                    "output_format": "png",
                    "return_base64": False
                }
            }
        )

        result = response.json()
        print('Prediction ID:', result['id'])
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**product_image** (`image URL | data URI`) *required*

Product image to be worn. Supports clothing, accessories, shoes, and other
  wearable fashion items.

**image_prompt** (`image URL | data URI`)

Optional inspiration image that guides pose, environment, and lighting while keeping the product centered in the final output.

**Default:** Not set

**face_reference** (`image URL | data URI`)

Optional face identity reference to guide who the generated person should look like. When provided, the pipeline refines identity to match the reference while keeping product fidelity. Using a face reference typically adds around 20 seconds to the processing time.

**Default:** Not set

**face_reference_mode** (`match_base | match_reference`)

Controls how the identity from `face_reference` influences pose and expression.

-`match_reference` favors the reference face’s pose and expression for maximum resemblance.

-`match_base` gives more weight to the prompt (or system default prompt if omitted) when generating the person's pose and expression.

**Default:** `match_reference`

**prompt** (`string`)

Additional instructions for person appearance, styling preferences, or background.

Examples: "man with tattoos", "tucked-in", "open jacket", "rolled-up sleeves", "studio background".

**Default:** Not set

**aspect_ratio** (`string`)

Desired aspect ratio for the output image. If omitted, the generation inherits the aspect ratio from the most specific image supplied (`background_reference` → `image_prompt` → `product_image`). Provide an explicit ratio to override that default even when using these image references.

Supported ratios: `"1:1"`, `"3:4"`, `"4:3"`, `"9:16"`, `"16:9"`, `"2:3"`, `"3:2"`, `"4:5"`, `"5:4"`

**Default:** Aspect ratio of the most specific image supplied

**resolution** (`1k | 2k | 4k`)

Output resolution tier. `'1k'` produces ~1 megapixel output, `'2k'` ~4 megapixels, and `'4k'` ~16 megapixels. Exact output dimensions depend on this tier and the image aspect ratio.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level. `'quality'` produces the most detailed and
  realistic output but takes longer to process and costs more credits. `'fast'`
  prioritizes speed and lower cost. If omitted, FASHN selects `generation_mode`
  automatically. For `product-to-model`, omitted `generation_mode` is currently
  billed as `'fast'` at `1k` and as `'balanced'` at `2k` or `4k`.

**background_reference** (`image URL | data URI`)

Background image used as the backdrop for generation. Ensures location consistency across generations. If a person appears in the image, they will be ignored and only the background will be used.

When provided alongside `image_prompt`, `image_prompt` governs the model's appearance, pose, and styling, while `background_reference` anchors the scene.

**Default:** Not set

**seed** (`integer`)

Seed for reproducible results. Must be between 0 and 2^32-1.

**Default:** `42`

**num_images** (`integer`)

Number of images to generate in a single request. Must be between 1 and 4. Additional images consume more compute (and credits) and can increase processing time.

**Default:** `1`

**output_format** (`string`)

Output image format.
- `"png"` - PNG format, original quality
- `"jpeg"` - JPEG format, smaller file size

**Default:** `png`

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed `data:image/png;base64,...`.

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 15 × 15 px       |
| Aspect ratio       | 1:16 to 16:1     |

Inputs outside these limits fail with `InputValidationError`. The output `resolution` does not change the input limits.

## Credit cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `fast`                           | 1    | 2    | 3    |
| `balanced`                       | 2    | 3    | 4    |
| `quality`                        | 3    | 4    | 5    |

Additional pricing rules:

- `face_reference` adds `+3` credits per output image.
- `num_images` multiplies the total cost by the number of outputs requested.
- If `generation_mode` is omitted, automatic pricing applies.

## Processing time

Processing time depends on both `resolution` and `generation_mode`. The fastest configuration (`fast` + `1k`) typically completes in around 10 seconds, `balanced` at `2k` finishes in around 25 seconds, and the most intensive combination (`quality` + `4k`) typically takes around 55 seconds. Using `face_reference` typically adds around 20 seconds on top of any configuration. Actual latency may vary with current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your product-to-model generation completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

## Runtime errors

Runtime errors for Product to Model use the shared set in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

- **[Prompting in FASHN ↗](https://help.fashn.ai/usage-guides/prompting-in-fashn)** - Learn how to write effective prompts for best results
- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your input images for better results
- **[Data Retention & Privacy](/api-overview/data-retention-privacy)** - Understand how FASHN handles your data

---

---
title: Model Create
description: Generate realistic fashion models using textual prompts or reference images
---

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

# Model Create

Generate realistic fashion models using textual prompts or reference images

Model Create enables you to generate realistic fashion models with simple, intuitive prompts or reference images.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** August 11, 2025

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `model-create`.                                                                           |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Generate fashion models by submitting your prompt and optional reference assets to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "model-create",
                   "inputs": {
                     "prompt": "Full body shot, woman wearing a white t-shirt and dark blue biker shorts"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "model-create",
            inputs: {
              prompt: "Full body shot, woman wearing a white t-shirt and dark blue biker shorts"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "model-create",
            "inputs": {
              "prompt": "Full body shot, woman wearing a white t-shirt and dark blue biker shorts"
            }
          }
        )
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**prompt** (`string`) *required*

Prompt for the model image generation. Describes the desired fashion model,
  clothing, pose, and scene.

**image_reference** (`image URL | data URI`)

Optional image to guide composition and pose. The AI won't copy the exact details from the image, but will use it as inspiration.

You can control whether to copy just the pose or the exact silhouette using the `prompt` parameter with natural language.

**aspect_ratio** (`string`)

Defines the width-to-height ratio of the generated image.

When `image_reference` is provided, the output inherits the reference image's aspect ratio. Supply an explicit `aspect_ratio` to override that default.

Supported ratios: `"21:9"`, `"16:9"`, `"9:16"`, `"4:3"`, `"3:4"`, `"3:2"`, `"2:3"`, `"4:5"`, `"5:4"`, `"1:1"`.

**Default:** `1:1`

**face_reference** (`image URL | data URI`)

Optional portrait image that locks in a specific identity across generations.

- When face_reference is used, output resolution is capped at 2K regardless of the requested resolution tier.
- Adds `3` credits per image.
- Typically adds around `20` seconds of processing time.

Use this to achieve model consistency across generations without training a custom checkpoint.

**face_reference_mode** (`match_base | match_reference`)

Controls how the provided `face_reference` shapes pose and expression.

-`match_base` prioritizes the prompt and base generation, keeping the original pose while adapting the reference face to those instructions.

-`match_reference` aligns the generated model closely with the reference face’s
pose, gaze, and expression for maximum resemblance.

**Default:** `match_reference`

**resolution** (`1k | 2k | 4k`)

Output resolution tier. `'1k'` produces ~1 megapixel output, `'2k'` ~4 megapixels, and `'4k'` ~16 megapixels. Exact output dimensions depend on this tier and the image aspect ratio.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level. `'quality'` produces the most detailed and
  realistic output but takes longer to process and costs more credits. `'fast'`
  prioritizes speed and lower cost. If omitted, FASHN selects `generation_mode`
  automatically. For `model-create`, omitted `generation_mode` is currently
  billed as `'fast'` at `1k` and as `'balanced'` at `2k` or `4k`.

**seed** (`integer`)

Sets random operations to a fixed state. Use the same seed to reproduce results with the same inputs, or different seed to force different results.

**Default:** `42` · **Range:** `0` to `2^32 - 1`

**num_images** (`integer`)

Number of images to generate per request. Must be between 1 and 4. Additional images consume more compute (and credits) and can increase processing time.

**Default:** `1`

**output_format** (`png | jpeg`)

Specifies the desired output image format.

-`png`: Delivers the highest quality image, ideal for use cases such as content creation where quality is paramount.

-`jpeg`: Provides a faster response with a slightly compressed image, more
suitable for real-time applications.

**Default:** `png`

**return_base64** (`boolean`)

When set to `true`, the API returns the generated image as a base64 string instead of a CDN URL. The base64 output is prefixed according to `output_format` (e.g., `data:image/png;base64,...` or `data:image/jpeg;base64,...`).

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 15 × 15 px       |
| Aspect ratio       | 1:16 to 16:1     |

Inputs outside these limits fail with `InputValidationError`. The output `resolution` does not change the input limits.

## Credit cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `fast`                           | 1    | 2    | 3    |
| `balanced`                       | 2    | 3    | 4    |
| `quality`                        | 3    | 4    | 5    |

Additional pricing rules:

- `face_reference` adds `+3` credits per output image.
- `num_images` multiplies the total cost by the number of outputs requested.
- If `generation_mode` is omitted, automatic pricing applies.

## Processing time

Processing time depends on both `resolution` and `generation_mode`. The fastest configuration (`fast` + `1k`) typically completes in around 10 seconds, `balanced` at `2k` finishes in around 25 seconds, and the most intensive combination (`quality` + `4k`) typically takes around 55 seconds. Using `face_reference` typically adds around 20 seconds on top of any configuration. Actual latency may vary with current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your model creation completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

The `output` array contains URLs to your generated fashion model images based on your prompt and optional reference parameters.

## Runtime errors

Runtime errors for Model Create use the shared set in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

For detailed implementation guidance and best practices:

- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your reference images

---

---
title: Face to Model
description: Transform face images into try-on ready upper-body avatars while preserving facial identity
---

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

# Face to Model

Transform face images into try-on ready upper-body avatars while preserving facial identity

The Face to Model endpoint transforms face images into try-on ready upper-body avatars. It converts cropped headshots or selfies into full upper-body representations that can be used in virtual try-on applications when full-body photos are not available, while preserving facial identity.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** September 19, 2025

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `face-to-model`.                                                                          |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Transform face images into professional model shots by submitting the face image to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "face-to-model",
                   "inputs": {
                     "face_image": "http://example.com/path/to/headshot.jpg",
                     "output_format": "jpeg"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "face-to-model",
            inputs: {
              face_image: "http://example.com/path/to/headshot.jpg",
              output_format: "jpeg"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "face-to-model",
            "inputs": {
              "face_image": "http://example.com/path/to/headshot.jpg",
              "output_format": "jpeg"
            }
          }
        )

        result = response.json()
        print('Prediction ID:', result['id'])
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**face_image** (`image URL | data URI`) *required*

Face image to transform into an upper-body avatar. The AI will analyze facial
  features, hair, and skin tone to create a representation suitable for virtual
  try-on applications.

**prompt** (`string`)

Optional styling or body shape guidance for the avatar representation. Examples: "athletic build", "curvy figure", "slender frame".

If you don't provide a prompt, the body shape will be inferred from the face image.

**aspect_ratio** (`string`)

Desired aspect ratio for the output image. Only vertical ratios are supported. Images will always be extended downward to fit the aspect ratio.

Supported ratios: `"1:1"`, `"4:5"`, `"3:4"`, `"2:3"`, `"9:16"`.

**Default:** `2:3`

**resolution** (`1k | 2k | 4k`)

Output resolution tier. `'1k'` produces ~1 megapixel output, `'2k'` ~4 megapixels, and `'4k'` ~16 megapixels. Exact output dimensions depend on this tier and the image aspect ratio.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level. `'quality'` produces the most detailed and
  realistic output but takes longer to process and costs more credits. `'fast'`
  prioritizes speed and lower cost. If omitted, FASHN selects `generation_mode`
  automatically. For `face-to-model`, omitted `generation_mode` is currently
  billed as `'fast'` at `1k` and as `'balanced'` at `2k` or `4k`.

**seed** (`integer`)

Sets random operations to a fixed state. Use the same seed to reproduce results with the same inputs, or different seed to force different results.

**Default:** `42`

**num_images** (`integer`)

Number of images to generate in a single request. Must be between 1 and 4. Additional images consume more compute (and credits) and can increase processing time.

**Default:** `1`

**output_format** (`string`)

Specifies the output image format.

- `"png"` - PNG format, original quality
- `"jpeg"` - JPEG format, smaller file size

**Default:** `jpeg`

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed `data:image/png;base64,...`.

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 15 × 15 px       |
| Aspect ratio       | 1:16 to 16:1     |

Inputs outside these limits fail with `InputValidationError`. The output `resolution` does not change the input limits.

## Credit cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `fast`                           | 1    | 2    | 3    |
| `balanced`                       | 2    | 3    | 4    |
| `quality`                        | 3    | 4    | 5    |

Additional pricing rules:

- `num_images` multiplies the total cost by the number of outputs requested.
- If `generation_mode` is omitted, automatic pricing applies.

## Processing time

Processing time depends on both `resolution` and `generation_mode`. The fastest configuration (`fast` + `1k`) typically completes in around 10 seconds, `balanced` at `2k` finishes in around 25 seconds, and the most intensive combination (`quality` + `4k`) typically takes around 55 seconds. Actual latency may vary with current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your face-to-model avatar creation completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": {
    "images": [
      "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
    ]
  },
  "error": null
}
```

The `images` array contains URLs to your upper-body avatars with preserved facial identity, ready for virtual try-on applications.

## Runtime errors

Runtime errors for Face to Model use the shared set in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your input images for better results
- **[Data Retention & Privacy](/api-overview/data-retention-privacy)** - Understand how FASHN handles your data

---

---
title: Model Swap
description: Change the identity of fashion models while preserving clothing and outfit details
---

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

# Model Swap

Change the identity of fashion models while preserving clothing and outfit details

Model Swap enables you to change the identity of fashion models in existing images while preserving clothing and outfit details exactly as they appear. Transform skin tone, facial features, and hair while maintaining the garments, pose, and styling perfectly intact.

For consistent photoshoots, an optional premium face reference capability lets you swap to a specific identity and achieve repeatable, campaign‑ready results across sets.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** August 13, 2025

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `model-swap`.                                                                             |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Transform fashion model identity while preserving clothing by submitting the source image (and optionally a face reference) to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "model-swap",
                   "inputs": {
                     "model_image": "https://example.com/fashion-model.jpg",
                     "prompt": "Asian woman with blue hair"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "model-swap",
            inputs: {
              model_image: "https://example.com/fashion-model.jpg",
              prompt: "Asian woman with blue hair"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "model-swap",
            "inputs": {
              "model_image": "https://example.com/fashion-model.jpg",
              "prompt": "Asian woman with blue hair"
            }
          }
        )
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**model_image** (`image URL | data URI`) *required*

Source fashion model image containing the clothing and pose to preserve. The
  model's identity (face, skin tone, hair) will be transformed while keeping the
  outfit exactly as shown.

**prompt** (`string`)

Text guidance for identity or scene adjustments. If omitted, the system generates an appropriate prompt based on image analysis.

**Default:** Empty string (automatic prompt)

**face_reference** (`image URL | data URI`)

Optional reference image to guide identity. When provided, the pipeline refines the model swap so both the body and face are aligned with the reference. Using a face reference typically adds around 20 seconds to the processing time.

**Default:** Not set

**face_reference_mode** (`match_base | match_reference`)

Additional fine control for identity guidance when `face_reference` is provided.

-`match_base` keeps the original photo’s head angle, gaze, and expression while applying the reference identity.

-`match_reference` favors the reference face’s pose and expression for maximum
resemblance.

**Default:** `match_reference`

**resolution** (`1k | 2k | 4k`)

Output resolution tier. `'1k'` produces ~1 megapixel output, `'2k'` ~4 megapixels, and `'4k'` ~16 megapixels. Exact output dimensions depend on this tier and the image aspect ratio.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level. `'quality'` produces the most detailed and
  realistic output but takes longer to process and costs more credits. `'fast'`
  prioritizes speed and lower cost. If omitted, FASHN selects `generation_mode`
  automatically. For `model-swap`, omitted `generation_mode` is currently billed
  as `'fast'` at `1k` and as `'balanced'` at `2k` or `4k`.

**seed** (`integer`)

Sets random operations to a fixed state. Use the same seed to reproduce results with the same inputs, or different seed to force different results.

**Default:** `42` · **Range:** `0` to `2^32 - 1`

**num_images** (`integer`)

Number of images to generate per request. Must be between 1 and 4.

**Default:** `1`

**output_format** (`png | jpeg`)

Specifies the desired output image format.

-`png`: Delivers the highest quality image, ideal for use cases such as content creation where quality is paramount.

-`jpeg`: Provides a faster response with a slightly compressed image, more
suitable for real-time applications.

**Default:** `png`

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed according to the `output_format` (e.g., `data:image/png;base64,...` or `data:image/jpeg;base64,...`).

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 15 × 15 px       |
| Aspect ratio       | 1:16 to 16:1     |

Inputs outside these limits fail with `InputValidationError`. The output `resolution` does not change the input limits.

## Credit cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `fast`                           | 1    | 2    | 3    |
| `balanced`                       | 2    | 3    | 4    |
| `quality`                        | 3    | 4    | 5    |

Additional pricing rules:

- `face_reference` adds `+3` credits per output image.
- `num_images` multiplies the total cost by the number of outputs requested.
- If `generation_mode` is omitted, automatic pricing applies.

## Processing time

Processing time depends on both `resolution` and `generation_mode`. The fastest configuration (`fast` + `1k`) typically completes in around 10 seconds, `balanced` at `2k` finishes in around 25 seconds, and the most intensive combination (`quality` + `4k`) typically takes around 55 seconds. Using `face_reference` typically adds around 20 seconds on top of any configuration. Actual latency may vary with current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your model swap completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

The `output` array contains URLs to your processed images with the transformed model identity while preserving the original clothing and styling.

## Runtime errors

Runtime errors for Model Swap use the shared set in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

For detailed implementation guidance and best practices:

- **[Prompting in FASHN ↗](https://help.fashn.ai/usage-guides/prompting-in-fashn)** - Learn how to write effective prompts for best results
- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your source images for identity transformation

---

---
title: Edit
description: Versatile post-processing to restyle shots, adjust views, and fix details while preserving identity and product fidelity
---

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

# Edit

Versatile post-processing to restyle shots, adjust views, and fix details while preserving identity and product fidelity

Edit is a versatile post-processing endpoint that preserves identity and product fidelity while executing freeform instructions. Use it to change poses or viewpoints for extra angles, style a shot with accessories or lighting, or fix issues in [Product to Model](/api-reference/product-to-model) or [Model Swap](/api-reference/model-swap) outputs.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** December 1, 2025

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `edit`.                                                                                   |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Refine images by submitting the source image and edit instructions to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "edit",
                   "inputs": {
                     "image": "https://example.com/model.jpg",
                     "prompt": "turn the model slightly to the left, add a black leather crossbody bag, soft daylight studio lighting"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "edit",
            inputs: {
              image: "https://example.com/model.jpg",
              prompt: "turn the model slightly to the left, add a black leather crossbody bag, soft daylight studio lighting"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "edit",
            "inputs": {
              "image": "https://example.com/model.jpg",
              "prompt": "turn the model slightly to the left, add a black leather crossbody bag, soft daylight studio lighting"
            }
          }
        )
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**image** (`image URL | data URI`) *required*

Source image to refine. The model preserves subject identity and product
  details while applying the requested edits.

**prompt** (`string`) *required*

Freeform instructions for the edits you want to apply, ideal for pose or view
  adjustments, styling (accessories, lighting, environment), or small fixes to
  existing outputs.

**mask** (`image URL | data URI`)

Optional mask image that guides the edit toward specific regions. White pixels (255) mark areas to prioritize, black pixels (0) mark areas to preserve. The model may still adjust nearby pixels to keep the image coherent, so treat the mask as a strong hint rather than strict inpainting.

The mask must have the same dimensions as the source image.

**image_context** (`image URL | data URI`)

Optional reference image that provides visual context to guide the edit. Use
  this when the desired result cannot be fully described in words alone.
  Examples include a specific background scene, complex pose, or texture
  pattern.

**resolution** (`1k | 2k | 4k`)

Output resolution tier. `'1k'` produces ~1 megapixel output, `'2k'` ~4 megapixels, and `'4k'` ~16 megapixels. Exact output dimensions depend on this tier and the image aspect ratio.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level. `'quality'` produces the most detailed and
  realistic output but takes longer to process and costs more credits. `'fast'`
  prioritizes speed and lower cost. If omitted, FASHN selects `generation_mode`
  automatically. For `edit`, omitted `generation_mode` is currently billed as
  `'fast'` at `1k` and as `'balanced'` at `2k` or `4k`.

**seed** (`integer`)

Sets random operations to a fixed state. Use the same seed to reproduce results with the same inputs, or different seed to force different results.

**Default:** `42` · **Range:** `0` to `2^32 - 1`

**num_images** (`integer`)

Number of images to generate in a single request. Must be between 1 and 4. Additional images consume more compute (and credits) and can increase processing time.

**Default:** `1`

**output_format** (`png | jpeg`)

Specifies the output image format.

-`png`: Delivers the highest quality image, ideal for use cases such as content creation where quality is paramount.

-`jpeg`: Provides a faster response with a slightly compressed image, more
suitable for real-time applications.

**Default:** `png`

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed according to the `output_format` (e.g., `data:image/png;base64,...` or `data:image/jpeg;base64,...`).

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 15 × 15 px       |
| Aspect ratio       | 1:16 to 16:1     |

Inputs outside these limits fail with `InputValidationError`. The output `resolution` does not change the input limits.

## Credit cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `fast`                           | 1    | 2    | 3    |
| `balanced`                       | 2    | 3    | 4    |
| `quality`                        | 3    | 4    | 5    |

Additional pricing rules:

- `num_images` multiplies the total cost by the number of outputs requested.
- If `generation_mode` is omitted, automatic pricing applies.

## Processing time

Processing time depends on both `resolution` and `generation_mode`. The fastest configuration (`fast` + `1k`) typically completes in around 10 seconds, `balanced` at `2k` finishes in around 25 seconds, and the most intensive combination (`quality` + `4k`) typically takes around 55 seconds. Actual latency may vary with current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your edit completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

The `output` array contains URLs to your edited images, which follow your instructions while preserving product and subject fidelity.

## Runtime errors

Edit shares the common runtime errors in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

For detailed implementation guidance and best practices:

- **[Prompting in FASHN ↗](https://help.fashn.ai/usage-guides/prompting-in-fashn)** - Learn how to write effective prompts for best results
- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your source images for editing

---

---
title: Reframe
description: Adjust image aspect ratios by expanding or cropping based on smart content analysis
---

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

# Reframe

Adjust image aspect ratios by expanding or cropping based on smart content analysis

Reframe intelligently adjusts image aspect ratios using AI-powered content analysis. The model analyzes your image and automatically decides whether to expand (outpaint/zoom-out) or crop (zoom-in) to reach the target aspect ratio while preserving important content.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** August 14, 2025

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `reframe`.                                                                                |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Reframe images by submitting the source image and target aspect ratio to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "reframe",
                   "inputs": {
                     "image": "https://example.com/portrait.jpg",
                     "aspect_ratio": "16:9"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "reframe",
            inputs: {
              image: "https://example.com/portrait.jpg",
              aspect_ratio: "16:9"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "reframe",
            "inputs": {
              "image": "https://example.com/portrait.jpg",
              "aspect_ratio": "16:9"
            }
          }
        )
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**image** (`image URL | data URI`) *required*

Source image to reframe to a new aspect ratio. The AI analyzes the image
  content and intelligently decides whether to expand or crop based on subject
  position, content density, and edge details.

**aspect_ratio** (`21:9 | 1:1 | 4:3 | 3:2 | 2:3 | 5:4 | 4:5 | 3:4 | 16:9 | 9:16`) *required*

Target aspect ratio for the reframed image. The AI determines whether expansion or cropping is more appropriate based on the current image content and dimensions.

### Supported Aspect Ratios

    Each aspect ratio corresponds to a specific resolution optimized for ~1MP output:

    | Aspect Ratio | Resolution | Use Case |
    |--------------|------------|----------|
    | 21:9 | 1568 × 672 | Ultra-wide cinematic |
    | 1:1 | 1024 × 1024 | Square format, social media |
    | 4:3 | 1176 × 880 | Traditional landscape |
    | 3:2 | 1248 × 832 | Standard landscape |
    | 2:3 | 832 × 1248 | Portrait, fashion photography |
    | 5:4 | 1144 × 912 | Instagram landscape |
    | 4:5 | 912 × 1144 | Instagram portrait |
    | 3:4 | 880 × 1176 | Standard portrait |
    | 16:9 | 1360 × 760 | Horizontal video format |
    | 9:16 | 760 × 1360 | Vertical video format |

**resolution** (`1k | 2k | 4k`)

Output resolution tier. `'1k'` produces ~1 megapixel output, `'2k'` ~4 megapixels, and `'4k'` ~16 megapixels. Exact output dimensions depend on this tier and the image aspect ratio.

**Default:** `1k`

**generation_mode** (`fast | balanced | quality`)

Sets the generation quality level. `'quality'` produces the most detailed and
  realistic output but takes longer to process and costs more credits. `'fast'`
  prioritizes speed and lower cost. If omitted, FASHN selects `generation_mode`
  automatically. For `reframe`, omitted `generation_mode` is currently billed as
  `'fast'` at `1k` and as `'balanced'` at `2k` or `4k`.

**num_images** (`integer`)

Number of images to generate in a single run. Image generation has a random element, so generating multiple images increases the chances of getting a good result.

**Default:** `1` · **Range:** `1` to `4`

**seed** (`integer`)

Sets random operations to a fixed state. Use the same seed to reproduce results with the same inputs, or different seed to force different results.

**Default:** `42` · **Range:** `0` to `2^32 - 1`

**output_format** (`png | jpeg`)

Specifies the output image format.

-`png`: Delivers the highest quality image, ideal for use cases such as content creation where quality is paramount.

-`jpeg`: Provides a faster response with a slightly compressed image, more
suitable for real-time applications.

**Default:** `png`

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed according to the `output_format` (e.g., `data:image/png;base64,...` or `data:image/jpeg;base64,...`).

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 15 × 15 px       |
| Aspect ratio       | 1:16 to 16:1     |

Inputs outside these limits fail with `InputValidationError`. The output `resolution` does not change the input limits.

## Credit cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `fast`                           | 1    | 2    | 3    |
| `balanced`                       | 2    | 3    | 4    |
| `quality`                        | 3    | 4    | 5    |

Additional pricing rules:

- `num_images` multiplies the total cost by the number of outputs requested.
- If `generation_mode` is omitted, automatic pricing applies.

## Processing time

Processing time depends on both `resolution` and `generation_mode`. The fastest configuration (`fast` + `1k`) typically completes in around 10 seconds, `balanced` at `2k` finishes in around 25 seconds, and the most intensive combination (`quality` + `4k`) typically takes around 55 seconds. Actual latency may vary with current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your reframe operation completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

The `output` array contains URLs to your reframed images, adjusted to the target aspect ratio.

## Runtime errors

Reframe shares the common runtime errors in [Error Handling](/api-overview/error-handling#common-runtime-errors).

In addition, Reframe may return:

| Error                  | Description                               |
| ---------------------- | ----------------------------------------- |
| `InputValidationError` | Image already matches target aspect ratio |

## Related guides

For detailed implementation guidance and best practices:

- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your source images for reframing operations

---

---
title: Background Remove
description: Remove image backgrounds to create transparent PNG cutouts of foreground subjects
---

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

# Background Remove

Remove image backgrounds to create transparent PNG cutouts of foreground subjects

Background Remove enables you to cleanly remove backgrounds from images, creating transparent PNG cutouts of foreground subjects. This classic background removal tool automatically detects and preserves the main subject while eliminating the background.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** August 15, 2025

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `background-remove`.                                                                      |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Remove image backgrounds by submitting the source image to the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "background-remove",
                   "inputs": {
                     "image": "https://example.com/portrait.jpg"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "background-remove",
            inputs: {
              image: "https://example.com/portrait.jpg"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "background-remove",
            "inputs": {
              "image": "https://example.com/portrait.jpg"
            }
          }
        )
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**image** (`image URL | data URI`) *required*

Source image to remove the background from. The AI will automatically detect
  the main subject and create a clean cutout with transparent background.

**return_base64** (`boolean`)

When set to `true`, the API will return the generated image as a base64-encoded string instead of a CDN URL. The base64 string will be prefixed `data:image/png;base64,...`.

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

**Default:** `false`

## Technical limitations

Minimum image dimensions are 128 × 128 px. Smaller images fail with `InputValidationError`.

## Credit cost

Background Remove costs 1 credit per output image.

## Processing time

Background removal typically completes in 1–3 seconds. Actual latency may vary with image complexity and current server load.

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your background removal completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.png"
  ],
  "error": null
}
```

The `output` array contains either URLs or, if `return_base64` is set to `true`, base64-encoded strings of your processed PNG images with backgrounds removed.

## Runtime errors

Runtime errors for Background Remove use the shared set in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

For detailed implementation guidance and best practices:

- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Optimize your source images for background removal

---

---
title: Image to Video
description: Create short videos from a single image with tasteful camera work and model movements tailored for fashion.
---

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

# Image to Video

Create short videos from a single image with tasteful camera work and model movements tailored for fashion.

Image to Video turns a still image into a short motion clip, with tasteful camera work and model movements tailored for fashion. Provide a starting image, add motion guidance if needed, and include an ending image when you want the clip to transition toward a specific final frame.

**Lifecycle:** [Experimental](/api-overview/model-lifecycle) · **Released:** October 15, 2025

## Request body

Every call uses the universal `POST /v1/run` request body:

| Field        | Type   | Required | Description                                                                                       |
| ------------ | ------ | -------- | ------------------------------------------------------------------------------------------------- |
| `model_name` | string | Yes      | Must be `image-to-video`.                                                                         |
| `inputs`     | object | Yes      | Contains the endpoint-specific parameters documented under [Input parameters](#input-parameters). |

Place all endpoint parameters inside `inputs`; they are not top-level request fields.

## Request

Animate a single image into a short video via the universal `/v1/run` endpoint:

    #### Request examples

        ```bash
        curl -X POST https://api.fashn.ai/v1/run \
             -H "Content-Type: application/json" \
             -H "Authorization: Bearer YOUR_API_KEY" \
             -d '{
                   "model_name": "image-to-video",
                   "inputs": {
                     "image": "https://example.com/photo.jpg",
                     "duration": 5,
                     "resolution": "1080p"
                   }
                 }'
        ```

        ```js
        fetch('https://api.fashn.ai/v1/run', {
          method: 'POST',
          body: JSON.stringify({
            model_name: "image-to-video",
            inputs: {
              image: "https://example.com/photo.jpg",
              duration: 5,
              resolution: "1080p"
            }
          }),
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json',
          }
        });
        ```

        ```python
        import requests

        response = requests.post(
          "https://api.fashn.ai/v1/run",
          headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
          },
          json={
            "model_name": "image-to-video",
            "inputs": {
              "image": "https://example.com/photo.jpg",
              "duration": 5,
              "resolution": "1080p"
            }
          }
        )
        ```

    #### Response

        Returns a prediction ID for status polling:

          **Example Response:**

            ```json
            {
              "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
              "error": null
            }
            ```

## Input parameters

**image** (`image URL | data URI`) *required*

Source image to animate into a short video.

**prompt** (`string`)

Optional motion guidance. Detailed prompting is not recommended because motion is difficult to control precisely. For the best results, leave this field empty and allow the system to plan motion automatically. If you choose to include guidance, keep it short and concrete, for example: "raising hand to touch face".

**Default:** Empty string (automatic motion)

**duration** (`5 | 10`)

Duration of the generated video in seconds.

**Default:** `5`

**resolution** (`480p | 720p | 1080p`)

Target video resolution used by the video engine.

**Default:** `1080p`

**end_image** (`image URL | data URI`)

Optional image to use as the final frame of the generated video. When
  provided, the video smoothly transitions from `image` (start frame) to
  `end_image` (end frame) over the clip duration.

## Technical limitations

| Requirement        | Limit            |
| ------------------ | ---------------- |
| Image file size    | 30 MiB per image |
| Minimum dimensions | 301 × 301 px     |

Images outside these limits fail with `InputValidationError`. FASHN does not upscale undersized images.

## Credit cost

| `duration` \ `resolution` | `480p` | `720p` | `1080p` |
| ------------------------- | ------ | ------ | ------- |
| `5s`                      | 1      | 3      | 6       |
| `10s`                     | 2      | 6      | 12      |

## Response polling

After submitting your request, poll the status endpoint using the returned prediction ID. See [API Fundamentals](/api-overview/api-fundamentals#status-polling) for complete polling details.

### Successful response

When your video completes successfully, the status endpoint will return:

```json
{
  "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1",
  "status": "completed",
  "output": [
    "https://cdn.fashn.ai/123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1/output_0.mp4"
  ],
  "error": null
}
```

The `output` array contains URLs to your generated MP4 video(s). The number of items reflects the workflow’s output (currently 1 video per request).

## Runtime errors

Runtime errors for Image to Video use the shared set in [Error Handling](/api-overview/error-handling#common-runtime-errors).

## Related guides

- **[API Fundamentals](/api-overview/api-fundamentals)** - Authentication, requests, and status polling
- **[Data Retention & Privacy](/api-overview/data-retention-privacy)** - Understand how FASHN handles your data
- **[Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices)** - Improve input quality for better results

---

---
title: Credits Balance
description: Retrieve your current FASHN API credits balance and usage information
---

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

# Credits Balance

Retrieve your current FASHN API credits balance and usage information

The Credits endpoint allows you to retrieve your current FASHN API credits balance. The response includes your total credits, the on-demand credits you've purchased, and any credits from an existing API plan.

- **On-Demand Credits**: Credits you buy on demand from [Billing](https://app.fashn.ai/billing)
- **Subscription Credits**: Credits from an existing API plan, if your account has one
- **Total Credits**: Combined balance of subscription + on-demand credits

## Request

Check your current credits balance by making a GET request to the credits endpoint:

    Call this endpoint whenever you need to know how many credits you have remaining.

    #### Request Examples

        ```bash
        curl -X GET https://api.fashn.ai/v1/credits \
             -H "Authorization: Bearer YOUR_API_KEY"
        ```

        ```js
        fetch('https://api.fashn.ai/v1/credits', {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
          }
        });
        ```

        ```python
        import requests

        response = requests.get(
          "https://api.fashn.ai/v1/credits",
          headers={"Authorization": "Bearer YOUR_API_KEY"},
        )
        ```

    #### Response

        Example response payload

          **Example Response:**

            ```json
            {
              "credits": {
                "total": 234,
                "subscription": 100,
                "on_demand": 134
              }
            }
            ```

## Response Fields

**credits** (`object`)

Container object for all credit information.

  Your total available credits (subscription + on-demand credits combined).

**subscription** (`integer`)

Credits from an existing API plan. These credits reset monthly based on the plan's billing cycle. The value is `0` if your account has no active API plan.

**on_demand** (`integer`)

Credits you bought on demand. If you also have subscription credits, those are used first.

## Rate Limits

The credits endpoint has its own specific rate limit:

| Endpoint | Limit |
|----------|-------|
| `/v1/credits` | 30 requests per 10 seconds |

For other endpoints, see the default rate limits in [API Fundamentals](/api-overview/api-fundamentals#rate-limits).

---

---
title: Try-On v1.6 Parameters
description: A detailed guide to all parameters available in FASHN’s Virtual Try-On v1.6 API
---

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

# Try-On v1.6 Parameters

A detailed guide to all parameters available in FASHN’s Virtual Try-On v1.6 API

This guide covers the parameters of the [Try-On v1.6](/api-reference/tryon-v1-6) endpoint. [Try-On Max](/api-reference/tryon-max), our recommended try-on model, uses a simpler interface (`product_image`, `model_image`, and an optional `prompt`) documented in its [API reference](/api-reference/tryon-max).

### Model Image

`image URL | base64`

`model_image` is the primary image of the person on whom the virtual try-on will be performed. You can provide the image as a publicly accessible URL or a base64 string.

💡 **💡 Mode Tips**

Use `mode: performance` to quickly test and find model and garment combinations that work well. Once you're satisfied, switch to `mode: quality` to produce a final high-quality result ready for publishing.

  *Tips for selecting the best model image and avoiding common issues.

### Garment Image

`image URL | base64`

`garment_image` is the reference image of the clothing item to be tried on the `model_image`. The image can be provided as a URL or a base64 string. FASHN supports a variety of garment photo types, as shown below:

  *Infographic displaying supported garment image types ranked from best (left)
  to worst (right).

💡 **💡 Image Handling Tips**

Read [Image Preprocessing Best Practices](https://docs.fashn.ai/guides/image-preprocessing-best-practices) to ensure your requests reach our servers fast and without issues

⚠️ **Common Image Issues**

**For Image URLs:**
- Ensure the URL is publicly accessible without permission restrictions.
- Confirm the `Content-Type` header matches the image format (e.g., `image/jpeg`, `image/png`).

**For Base64 Images:**
- Prefix the string with `data:image/;base64,` where `` is the image type (e.g., `jpeg`, `png`).

### Category

`'auto' | 'tops' | 'bottoms' | 'one-pieces'`

Specifies the type of garment in the `garment_image` to apply to the `model_image`. If the garment image includes multiple items (e.g., a t-shirt and jeans), use this parameter to select which item to apply.

- **`auto`** (recommended): Automatically determines the garment category. For flat-lay or ghost mannequin images, garment type detection is automatic. For on-model images, full-body shots default to swapping the entire outfit, and focused shots (upper or lower body) select the most likely garment type (`tops` or `bottoms`).
- **`tops`**: Specifies garments for the upper body (e.g., shirts, blouses).
- **`bottoms`**: Specifies garments for the lower body (e.g., pants, skirts).
- **`one-pieces`**: Specifies single-piece garments or full-body garments (e.g., dresses, jumpsuits).

  *Examples of try-on results for categories `'tops'`, `'bottoms'`, and
  `'one-pieces'`.

### Mode

`performance | balanced | quality`

The `mode` parameter determines the trade-off between processing speed and output quality:

- **`performance`**: Fastest, with reduced image quality.
- **`balanced`**: A middle ground, offering a good balance between speed and quality.
- **`quality`**: Slowest, delivering the highest-quality results.

  *Side-by-side comparison of results for `'performance'`, `'balanced'`, and
  `'quality'` modes.

💡 **💡 Mode Tips**

Use `mode: performance` to quickly test and find model and garment combinations that work well. Once you're satisfied, switch to `mode: quality` to produce a final high-quality result ready for publishing.

### Garment Photo Type

`auto | model | flat-lay`

Defines the garment photo type for optimal performance:

- **`model`**: Photos of garments on a model.
- **`flat-lay`**: Flat-lay or ghost mannequin images.
- **`auto`**: Automatically detects the photo type.

`flat-lay` is required for precise handling of flat-lay images where elements like back neck labels or size tags should be excluded.

  *Comparison of `'flat-lay'` and `'model'` configurations with flat-lay input.

### Number of Samples
`integer`

The `num_samples` parameter specifies how many images to generate in a single run. By increasing `num_samples`, you can explore multiple variations simultaneously, improving the likelihood of achieving a desirable result. 

Because `num_samples` introduces diversity within a batch, its practical effect is similar to running multiple trials with different seeds. However, when used with the same `seed` value, the results remain reproducible for a given `num_samples` count.

💡 **💡 FASHN Tip**

Great try-on results might just be a seed change away! Conversely, a poor outcome doesn't necessarily mean the input combination won't work—sometimes a simple seed change can make all the difference. Use `num_samples: 2-4` along with `mode: performance` to quickly test multiple seeds and assess how sensitive your inputs are to seed variation.

### Seed
`integer`

**Default:** `42`
**Min:** `0`, **Max:** `2^32 - 1`

The `seed` parameter is used to set the random operations within the image generation process to a fixed state. This is crucial for reproducibility:
- Use the **same seed value** with the same inputs to consistently generate the exact same try-on result.
- Use a **different seed value** with the same inputs to force different variations of the try-on result. This is useful for exploring different aesthetic outcomes without changing your core `model_image` or `garment_image`.

### Segmentation Free
`boolean`

**Default:** `true`

When set to `true`, this parameter enables direct garment fitting without requiring explicit clothing segmentation from the input images. This is particularly useful for achieving a more natural look with bulkier garments, as it aims to preserve the model's body shape and skin texture more effectively. If you observe issues where the original garments are not properly removed in the try-on result, and it is critical for your use-case, set this to `false`.

### Moderation Level
`'conservative' | 'permissive' | 'none'`

**Default:** `permissive`

This parameter allows you to set the content moderation standards for the garment images processed by the API.
- **`conservative`**: Enforces stricter modesty standards, suitable for culturally sensitive contexts. It is designed to block images of underwear, swimwear, and revealing outfits.
- **`permissive`**: This is the default setting. It allows images of swimwear, underwear, and revealing garments, but still blocks explicit nudity.
- **`none`**: Disables all content moderation.

This technology is designed for ethical and appropriate virtual try-on applications. Misuse—such as generating inappropriate imagery of individuals without consent—violates our [Terms of Service](https://fashn.ai/legal/terms-of-service).

  Setting `moderation_level: none` does not absolve users from their responsibility to ensure ethical and lawful use. **Violations may result in service denial**.

### Output Format
`'png' | 'jpeg'`

**Default:** `png`

This parameter specifies the desired format of the generated output image:
- **`png`**: Delivers the highest quality image, making it ideal for use cases where image fidelity is paramount, such as content creation, marketing materials, or high-resolution displays.
- **`jpeg`**: Provides a faster response time with a slightly compressed image. This format is more suitable for real-time applications like consumer-facing virtual try-on experiences where speed is a priority over uncompressed quality.

### Return Base64
`boolean`

**Default:** `false`

When set to `true`, the API will return the generated image directly as a base64-encoded string in the response body, instead of providing a CDN (Content Delivery Network) URL. The base64 string will be appropriately prefixed according to the chosen `output_format` (e.g., `data:image/png;base64,...` or `data:image/jpeg;base64,...`).

**Privacy benefit:** Outputs are available for up to 60 minutes instead of the standard three-day window. Request history contains only a `` placeholder.

---

---
title: Try-On Python Quickstart
description: A quick guide to FASHN for Python users
---

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

# Try-On Python Quickstart

A quick guide to FASHN for Python users

We suggest using our Python SDK rather than the manual method described below. Find more details in the [Python SDK documentation](/sdk/python).

Below is a minimal Python snippet to demonstrate how to:
1. **POST** to the `/run` endpoint with your input data.
2. **Poll** the `/status/` endpoint until the prediction is completed.
3. **Retrieve** the final results from the `"output"` field.

For detailed documentation (including advanced parameters and usage), please refer to:
- [Try-On Max Documentation](/api-reference/tryon-max)
- [tryon-gradio-app](https://github.com/fashn-AI/tryon-gradio-app) (interactive Gradio UI example)
- [ComfyUI-FASHN](https://github.com/fashn-AI/ComfyUI-FASHN) (node-based workflow integration)

---
### Minimal Python Example

This snippet demonstrates a basic request using model and product image URLs. You can also adapt the code to send local images in Base64 format.

```python
import os
import time
import requests

# 1. Set up the API key and base URL
API_KEY = os.getenv("FASHN_API_KEY")
assert API_KEY, "Please set the FASHN_API_KEY environment variable."
BASE_URL = "https://api.fashn.ai/v1"

# 2. POST request to /run
input_data = 
}
headers = "}
run_response = requests.post(f"/run", json=input_data, headers=headers)
run_data = run_response.json()
prediction_id = run_data.get("id")
print("Prediction started, ID:", prediction_id)

# 3. Poll /status/
while True:
    status_response = requests.get(f"/status/", headers=headers)
    status_data = status_response.json()

    if status_data["status"] == "completed":
        print("Prediction completed.")
        # 4. The "output" field contains the final image URLs
        print(status_data["output"])
        break

    elif status_data["status"] in ["starting", "in_queue", "processing"]:
        print("Prediction status:", status_data["status"])
        time.sleep(3)

    else:
        print("Prediction failed:", status_data.get("error"))
        break

---

---
title: Try-On JavaScript Quickstart
description: A quick guide to FASHN for JavaScript users
---

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

# Try-On JavaScript Quickstart

A quick guide to FASHN for JavaScript users

We suggest using our TypeScript SDK rather than the manual method described below. Find more details in the [TypeScript SDK documentation](/sdk/typescript).

Below is a minimal JavaScript snippet to demonstrate how to:
1. **POST** to the `/run` endpoint with your input data.
2. **Poll** the `/status/` endpoint until the prediction is completed.
3. **Retrieve** the final results from the `"output"` field.

For detailed documentation (including advanced parameters and usage), please refer to:
- [Try-On Max Documentation](/api-reference/tryon-max)
- [tryon-nextjs-app](https://github.com/fashn-AI/tryon-nextjs-app) (interactive Next.js example)
- [Integrate FASHN SDK into your Next.js application](https://fashn.ai/blog/how-to-integrate-fashn-sdk-into-your-next-js-application)

--- 
### Minimal JavaScript Example

This snippet demonstrates a basic request using model and product image URLs. You can also adapt the code to send local images in Base64 format.

```javascript
// 1. Set up the API key and base URL
const API_KEY = process.env.FASHN_API_KEY;
if (!API_KEY) {
    throw new Error("Please set the FASHN_API_KEY environment variable.");
}
const BASE_URL = "https://api.fashn.ai/v1";

// 2. POST request to /run
const inputData = {
    model_name: "tryon-max",
    inputs: {
        model_image: "http://example.com/path/to/model.jpg",
        product_image: "http://example.com/path/to/garment.jpg"
    }
};

const headers = {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${API_KEY}`
};

async function runPrediction() {
    try {
        // Make the initial run request
        const runResponse = await fetch(`${BASE_URL}/run`, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(inputData)
        });
        const runData = await runResponse.json();
        const predictionId = runData.id;
        console.log("Prediction started, ID:", predictionId);

        // Poll for status
        while (true) {
            const statusResponse = await fetch(`${BASE_URL}/status/${predictionId}`, {
                headers: headers
            });
            const statusData = await statusResponse.json();

            if (statusData.status === "completed") {
                console.log("Prediction completed.");
                console.log(statusData.output);
                break;
            } else if (["starting", "in_queue", "processing"].includes(statusData.status)) {
                console.log("Prediction status:", statusData.status);
                await new Promise(resolve => setTimeout(resolve, 3000));
            } else {
                console.log("Prediction failed:", statusData.error);
                break;
            }
        }
    } catch (error) {
        console.error("Error:", error.message);
    }
}

// Run the prediction
runPrediction();
```

---

---
title: Next.js Quickstart
description: Learn how to integrate the FASHN SDK into your Next.js application using Server Actions. This step-by-step tutorial covers project setup, SDK installation, API configuration, and building your first FASHN-powered feature with a practical virtual try-on example.
---

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

# Next.js Quickstart

Learn how to integrate the FASHN SDK into your Next.js application using Server Actions. This step-by-step tutorial covers project setup, SDK installation, API configuration, and building your first FASHN-powered feature with a practical virtual try-on example.

In this guide, you'll learn how to integrate the FASHN SDK into a Next.js application using Server Actions. We'll walk through the complete setup process and demonstrate the integration by building a virtual try-on feature, one of many capabilities the FASHN SDK offers.

**What you'll build:** A web application with a simple interface that displays a pre-selected model and garment image, then generates a realistic try-on result showing the model wearing that garment.

**Tech stack:** Next.js App Router, Server Actions, TypeScript, and the FASHN SDK.

By the end of this tutorial, you'll have a solid foundation for integrating FASHN's virtual try-on capabilities into your own projects.

## Prerequisites

Before you begin, you'll need a FASHN API key. The SDK uses this key to authenticate all requests to the FASHN API.
Here's how to get your key:
- Navigate to the [Developer API dashboard](https://app.fashn.ai/api) and click **"Create new API key"**
- Copy the generated key immediately, you won't be able to view it again after closing the dialog
- Store it securely in a password manager or secure note

**Important:** Your API key should never be exposed to the client side. We'll configure it as a server-side environment variable to keep it secure.

## Step 1: Create Your Next.js Project

Let's start by scaffolding a fresh Next.js application. We'll use create-next-app with default settings to get the App Router, TypeScript configuration, and development server set up automatically.

```bash
npx create-next-app@latest my-fashn-app --yes
cd my-fashn-app
npm run dev
```

The --yes flag accepts all defaults, which is perfect for our purposes, it includes TypeScript, ESLint, Tailwind CSS, and the App Router.

Once the server starts, open [http://localhost:3000](http://localhost:3000) in your browser. You should see the default Next.js welcome page, confirming everything is working correctly.

## Step 2: Install the FASHN SDK

The FASHN TypeScript SDK provides a clean, type-safe interface to the FASHN API. It handles authentication, request/response formatting, automatic polling for generation results, and error handling, eliminating the boilerplate you'd otherwise need to write.

Install it with npm:

```bash
npm i fashn
```

**A note on security:** The SDK is designed for server-side use only. Always call it from Server Actions, API Routes, or other backend code, never directly from client components. This ensures your API key remains secure.

## Step 3: Configure Your API Key

Create a `.env.local` file in your project root to store your API key:

```env
FASHN_API_KEY=your_api_key_here
```
Replace `your_api_key_here` with the actual API key you copied earlier.

**Important details:**
- Don't use the `NEXT_PUBLIC_` prefix! That would expose the variable to the browser
- Restart your development server after creating or modifying environment variables
- Add `.env.local` to your `.gitignore` to prevent accidentally committing secrets

## Step 4: Build the User Interface

Now let's create a simple UI that displays the model and garment images and allows users to generate the virtual try-on result. Replace the contents of `app/page.tsx` with the following:

```tsx
"use client";

export default function Home() {
  const [result, setResult] = useState();
  const [error, setError] = useState();
  const [loading, setLoading] = useState(false);

  const modelImage =
    "https://cm7xvlqw96.ufs.sh/f/wXFHUNfTHmLj9QTMwFWT5IXsA4Lhru0e7dJiKFwpQ6Glm28S";
  const garmentImage =
    "https://utfs.io/f/wXFHUNfTHmLjtkhepmqOUnkr8XxZbNIFmRWldShDLu320TeC";

  const handleTryOn = async () => {
    try {
      setLoading(true);
      const result = await runGeneration(modelImage, garmentImage);

      if (result.error) {
        return setError(result.error);
      }

      setResult(result.output);
    } catch (error) {
      setError("Internal server error");
    } finally {
      setLoading(false);
    }
  };

  return (

            Garment Image

            Model Image

              {result && }
              {error && {error}}
              {loading && Loading...}

            Result Image

            Virtual Try-On

          Go to fashn.ai →

  );
}
```

This interface includes:
- **Pre-selected images** for the model and garment to keep the demo simple
- **A generate button** that triggers the Server Action (which we'll create next)
- **A results section** that displays the generated try-on image
- **Loading states** to provide feedback during generation

## Step 5: Create the Server Action

Server Actions let you run secure backend code without setting up separate API routes. Create a new file at `app/actions.ts`:

```ts
"use server";

const client = new Fashn();

export async function runGeneration(modelImage: string, garmentImage: string) {
  try {
    const response = await client.predictions.subscribe({
      model_name: "tryon-max",
      inputs: {
        model_image: modelImage,
        product_image: garmentImage,
      },
    });

    // 1. Check for Runtime Errors (during model execution). Status can be failed, canceled or time_out.
    if (response.status !== "completed") {
      return { error: response.error?.message };
    }

    // 2. Success case (status is completed)
    return { output: response.output?.at(0) };
  } catch (error) {
    console.error(error);
    // 3. Handle API-Level Errors (before request processing)
    if (error instanceof Fashn.APIError) {
      return { error: error.message };
    } else {
      return { error: "Network or unexpected error" };
    }
  }
}
```

This Server Action does the heavy lifting:
- **Initializes the FASHN client** with your API key from the environment
- **Calls the subscribe method**, which creates a generation job using the tryon-max model and automatically polls until the result is ready
- **Returns the final image URL** to display in your UI
- **Handles errors gracefully**, providing meaningful feedback if something goes wrong

The `subscribe` method abstracts away the complexity of polling, so you get a simple async function that resolves when the generation is complete.

## Step 6: See It in Action

With everything wired up, let's test the application:
- Make sure your dev server is still running (`npm run dev`)
- Navigate to [http://localhost:3000](http://localhost:3000)
- You'll see the pre-selected model and garment images displayed
- Click **"Virtual Try-On"**

After a few moments, you'll see the generated result, your model wearing the garment. The FASHN SDK handles the entire process behind the scenes, from job creation to polling to result delivery.

## Next Steps

Congratulations! You've built a working virtual try-on application with the FASHN SDK. This demo covers the core integration with pre-selected images for simplicity, but production applications typically need additional features:
- **User authentication** to manage user sessions and limit abuse
- **File upload** to let users provide their own model and garment images
- **Image validation** to ensure inputs meet size and format requirements
- **Error handling** with user-friendly messages and retry logic
- **Progress indicators** to show generation status in real-time

## Helpful Resources

Ready to take your integration further? Check out these resources:
- [Full Next.js Example App](https://github.com/fashn-AI/tryon-nextjs-app)
- [SDK Reference](/sdk/typescript)

Happy building! If you create something cool with FASHN, we'd love to see it. Share your project with the community or reach out to our support team.

---

---
title: React Router Quickstart
description: Learn to integrate FASHN SDK with React Router v7. This step-by-step tutorial covers SDK installation, secure API key management, server action implementation, and working with FASHN's async generation API, complete with production-ready code examples.
---

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

# React Router Quickstart

Learn to integrate FASHN SDK with React Router v7. This step-by-step tutorial covers SDK installation, secure API key management, server action implementation, and working with FASHNs async generation API, complete with production-ready code examples.

React Router powers millions of web applications, from indie projects to enterprise platforms. It's the go-to framework for building Shopify apps, making it an ideal choice for e-commerce developers looking to add cutting-edge features like virtual try-on.

In this guide, you'll learn how to integrate the FASHN SDK into a React Router application. We'll build a complete virtual try-on feature that lets customers visualize garments on models, a game-changer for online fashion retailers.

**What you'll build:** A production-ready web application that displays model and garment images, then generates photorealistic try-on results showing the model wearing the selected garment.

**Tech stack:** React Router v7, TypeScript, and the FASHN SDK.

By the end of this tutorial, you'll have a solid foundation for adding FASHN's AI-powered virtual try-on to your e-commerce applications and Shopify apps.

## Prerequisites

Before diving in, you'll need a FASHN API key to authenticate your requests. Getting started is straightforward:
1. Head to the [Developer API dashboard](https://app.fashn.ai/api) and click **"Create new API key"**
2. Copy your key immediately, it's only shown once
3. Store it securely (use a password manager or your team's secrets vault)

**Security note:** API keys should always stay server-side. React Router's server actions make this easy. We'll configure your key as an environment variable that never touches the browser.

## Step 1: Create Your React Router Project

Let's scaffold a new React Router application with all the modern tooling configured out of the box, Vite for lightning-fast builds, TypeScript for type safety, and Tailwind CSS for styling.

```bash
npx create-react-router@latest my-rr-fashn-app
cd my-rr-fashn-app
npm run dev
```

Visit [http://localhost:5173](http://localhost:5173) to confirm everything's running. You should see the React Router welcome screen.

## Step 2: Add the FASHN SDK

The FASHN TypeScript SDK eliminates boilerplate by handling authentication, polling, and error management automatically. It's built specifically for server-side environments, keeping your API credentials secure.

Install it with npm:

```bash
npm install fashn
```

**Architecture note:** The SDK must only be called from server actions or backend routes, never from client components. This server-side-only design is intentional and protects your API key from exposure.

## Step 3: Set Up Environment Variables

Create a .env.local in your project root:

```env
FASHN_API_KEY=your_api_key_here
```
Replace `your_api_key_here` with your actual key.

**Important reminders:**
- Restart your dev server after adding environment variables
- Verify `.env.local` is in your `.gitignore` (it should be by default)
- Never commit API keys to version control

## Step 4: Create the Try-On Interface

Now for the fun part: building the UI. We'll create a clean interface that showcases the before and after, making the virtual try-on transformation clear to users.
Replace the contents of `app/routes/home.tsx` with this code:

```tsx

export async function action({ request }: Route.ActionArgs) {
  const formData = await request.formData();
  const modelImage = formData.get("modelImage") as string;
  const garmentImage = formData.get("garmentImage") as string;
  const result = await runGeneration(modelImage, garmentImage);
  return result;
}

export default function Home() {
  const fetcher = useFetcher();
  const loading = fetcher.state !== "idle";
  const result = fetcher.data?.output;
  const error = fetcher.data?.error;

  const modelImage =
    "https://cm7xvlqw96.ufs.sh/f/wXFHUNfTHmLj9QTMwFWT5IXsA4Lhru0e7dJiKFwpQ6Glm28S";
  const garmentImage =
    "https://utfs.io/f/wXFHUNfTHmLjtkhepmqOUnkr8XxZbNIFmRWldShDLu320TeC";

  const handleTryOn = () => {
    fetcher.submit(
      {
        modelImage,
        garmentImage,
      },
      {
        method: "POST",
      }
    );
  };

  return (

            Garment Image

            Model Image

              {result && }
              {error && {error}}
              {loading && Loading...}

            Result Image

            Virtual Try-On

          Go to fashn.ai →

  );
}
```

This interface includes:
- **Side-by-side layout** showing the original garment and model
- **One-click generation** with a clear call-to-action button
- **Real-time feedback** through loading states
- **Results display** that highlights the transformation

## Step 5: Implement the Server Action

Create `app/actions.ts` to handle the FASHN SDK integration:

```ts

const client = new Fashn();

export async function runGeneration(modelImage: string, garmentImage: string) {
  try {
    const response = await client.predictions.subscribe({
      model_name: "tryon-max",
      inputs: {
        model_image: modelImage,
        product_image: garmentImage,
      },
    });

    // 1. Check for Runtime Errors (during model execution). Status can be failed, canceled or time_out.
    if (response.status !== "completed") {
      return { error: response.error?.message };
    }

    // 2. Success case (status is completed)
    return { output: response.output?.at(0) };
  } catch (error) {
    console.error(error);
    // 3. Handle API-Level Errors (before request processing)
    if (error instanceof Fashn.APIError) {
      return { error: error.message };
    } else {
      return { error: "Network or unexpected error" };
    }
  }
}
```

How it works:
- **Initializes the FASHN client** with your API key from the environment
- **Calls the subscribe method**, which creates a generation job using the tryon-max model and automatically polls until the result is ready
- **Returns the final image URL** to display in your UI
- **Handles errors gracefully**, providing meaningful feedback if something goes wrong

The subscribe method is the secret sauce here. It turns a complex async workflow into a single awaitable function call.

## Step 6: Test Your Integration

With everything wired up, let's see the result:
- Restart your dev server (`npm run dev`)
- Open [http://localhost:5173](http://localhost:5173)
- Review the pre-selected model and garment images
- Click **"Virtual Try-On"**
- Watch as the AI generates a photorealistic result

The entire process typically takes around 25 seconds in the default `balanced` generation mode, and can be faster or slower depending on the [`generation_mode` and `resolution`](/api-reference/tryon-max#input-parameters) you choose. The FASHN SDK manages everything behind the scenes, job creation, status polling, and result retrieval.

## Taking It Further

You've built a working virtual try-on feature! This tutorial uses pre-selected images for simplicity, but for production you would typically need:
- **User management** - Track usage, prevent abuse, and implement rate limiting
- **File upload** - Let customers upload their own photos or choose from a catalog
- **Image preprocessing** - Validate dimensions, format, and quality before processing
- **Enhanced UX** - User-friendly messages, retry logic and progress bars

## Resources to Explore

- [SDK Reference](/sdk/typescript)
- [React Router Getting Started](https://reactrouter.com/start/framework/installation)
- [Shopify Apps Development Guide](https://shopify.dev/docs/apps/build/scaffold-app)

Built something cool? Share it with the FASHN community or reach out to our team. We love seeing what developers create!

---

---
title: Troubleshooting
description: Resolve common FASHN API issues
---

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

# Troubleshooting

Resolve common FASHN API issues

Use this guide to identify and resolve common issues when working with the FASHN API.

| **Issue**                                                              | **Cause**                                                                                                                                                                | **Solution**                                                                                                                                                                                          |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| API results differ from the Web App                                    | The Web App preprocesses images before sending them to the API, which can lead to different outputs if the same steps are not followed externally.                       | **Preprocessing**: See [Image Preprocessing Best Practices](https://docs.fashn.ai/guides/image-preprocessing-best-practices) for instructions on replicating the Web App's steps to ensure consistent results.                                                         |
| Error Code 500 (Server Error)                                          | Commonly caused by an oversized payload (e.g., high-resolution, base64-encoded images), preventing the request from reaching our API.                                    | **Reduce Payload**: See [Image Preprocessing Best Practices](https://docs.fashn.ai/guides/image-preprocessing-best-practices) for recommended steps to avoid large payloads.                                                                                           |

---

---
title: Image Preprocessing Best Practices
description: Preserve image quality while keeping API requests efficient and reliable
---

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

# Image Preprocessing Best Practices

Preserve image quality while keeping API requests efficient and reliable

FASHN accepts public image URLs and base64 data URIs. In most cases, use the original image at a stable URL.

---

## Recommended approach

1. **Check the endpoint's input requirements**

   Each endpoint reference has a **Technical limitations** section covering only endpoint-specific constraints such as file-size, dimension, or aspect-ratio limits. For example, [Image to Video](/api-reference/image-to-video#technical-limitations) lists its minimum dimensions and file-size limit.

2. **Do not resize an input merely to match the requested output resolution**

   A 4K source can be appropriate for a 1K or 2K output. The output `resolution` controls the generated result; it is not a general input-size ceiling. Resize only when an endpoint's documented input bounds require it or when you intentionally want a smaller upload.

3. **Prefer a URL for large images**

   Use a publicly reachable HTTPS URL that returns the image directly, follows normal redirects, and does not require custom authorization headers. Signed URLs are supported, but they must remain valid until the prediction completes. Set accurate `Content-Type` and, when possible, `Content-Length` response headers.

4. **Choose between signed URLs and base64 based on your privacy needs**

   Base64 is a privacy-focused option when you prefer not to submit an image URL: request history displays the input as a `` placeholder. Because base64 increases the request size, short-lived signed URLs are generally recommended for better reliability and can provide similar privacy when they remain valid only long enough for the prediction to complete. Base64 data URIs must include the media prefix, such as `data:image/jpeg;base64,...`. See [Data Retention & Privacy](/api-overview/data-retention-privacy) for more details.

5. **Preserve the original format and quality when possible**

   JPEG, PNG, and WebP are broadly supported. Avoid converting or recompressing an image unless the endpoint does not accept its format or the file exceeds a documented limit. If you do resize, preserve the aspect ratio and use a high-quality downsampling filter such as LANCZOS or INTER_AREA.

---

---
title: API Reference: Agent and Single-Task Endpoints
description: Reference for the FASHN Agent API (Agent Images) and the FASHN single-task endpoints for virtual try-on, model generation, and image editing.
---

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

# API Reference: Agent and Single-Task Endpoints

Reference for the FASHN Agent API (Agent Images) and the FASHN single-task endpoints for virtual try-on, model generation, and image editing.

Welcome to the FASHN API Reference. Start with the FASHN Agent API, which plans and runs the steps a request needs, or call a single-task endpoint directly.

## FASHN Agent API

- [Agent Images](/api-reference/agent-images): Describe the images you need in plain language and attach up to six references, and the FASHN Agent plans and runs the generations: on-model photos, packshots, catalog images, and lookbooks

New to the Agent? Start with the [Agent API Quickstart](/getting-started/agent-quickstart).

## Single-task endpoints

Each single-task endpoint does one job through `POST /v1/run`. Use them for real-time virtual try-on in shopping experiences, for direct control over one task's parameters, or for video.

- [Try-On Max](/api-reference/tryon-max): Premium virtual try-on with enhanced fidelity, up to 4K resolution, and prompt-based customization
- [FASHN Virtual Try-On v1.6](/api-reference/tryon-v1-6): Fast, lightweight virtual try-on optimized for real-time e-commerce experiences
- [Product to Model](/api-reference/product-to-model): Transform product images into people wearing those products, with optional inspiration, background, and face reference inputs
- [Model Create](/api-reference/model-create): Generate realistic fashion models using textual prompts or reference images
- [Face to Model](/api-reference/face-to-model): Transform face images into try-on ready upper-body avatars while preserving facial identity
- [Model Swap](/api-reference/model-swap): Change the identity of fashion models while preserving clothing and outfit details
- [Edit](/api-reference/edit): Versatile post-processing that follows edit instructions while preserving identity and product fidelity
- [Reframe](/api-reference/reframe): Adjust image aspect ratios by expanding or cropping based on smart content analysis
- [Background Remove](/api-reference/background-remove): Remove image backgrounds to create transparent PNG cutouts of foreground subjects
- [Image to Video](/api-reference/image-to-video): Create short videos from a single image with tasteful camera work and model movements tailored for fashion.

---

---
title: Guides
description: Explore comprehensive guides and resources to help you integrate, configure, and optimize the FASHN API.
---

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

# Guides

Explore comprehensive guides and resources to help you integrate, configure, and optimize the FASHN API.

Explore our comprehensive guides and resources designed to help you seamlessly integrate, configure, and optimize the FASHN API.

- [FASHN Agent API Quickstart](/getting-started/agent-quickstart): Make your first Agent request and try prompts for on-model photos, packshots, catalog images, and lookbooks.
- [Lookbook Recipe for Claude Code](/recipes/lookbook.md): Make a four-look lookbook from six photos in one FASHN Agent API call.
- [API Try-On Parameters Guide](/guides/tryon-parameters-guide): Learn about API parameters and how to use them effectively.
- [Python Try-On Quickstart Guide](/guides/tryon-python-quickstart-guide): Get started with the FASHN API using Python.
- [Troubleshooting Guide](/guides/troubleshooting-guide): Identify and resolve common issues when working with the FASHN API.
- [Image Preprocessing Best Practices](/guides/image-preprocessing-best-practices): Ensure optimal performance and consistent outputs when using the FASHN API.