---
title: Introduction
description: FASHN AI’s developer API offers generative AI for fashion with virtual try-on, model creation, and advanced image editing, with enterprise-grade infrastructure and strong privacy protections.
---

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

# Introduction

FASHN AI’s developer API offers generative AI for fashion with virtual try-on, model creation, and advanced image editing, with enterprise-grade infrastructure and strong privacy protections.

## Welcome to the FASHN API

FASHN is an AI-first company specializing in human-centric generative image models tailored for fashion applications. The API provides developers and product teams with access to endpoints for image generation, virtual try-on, model creation, editing, background manipulation, and reframing functionalities.

## Core Features

Our flagship **Virtual Try-On (VTON)** model allows users to see how clothing would look on a person without physically wearing it. Using AI, our API takes a photo of a person and a garment, then generates a realistic image showing how the clothing would appear on that person.

The FASHN API also includes several other powerful fashion-oriented generative endpoints:

---

Ready to get started? Continue with our [API Setup Guide](/getting-started/api-setup).

---

---
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 and patterns that are consistent across all FASHN API endpoints. Understanding these concepts will help you integrate any current or future endpoint.

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).

## Request Pattern

All FASHN model endpoints follow a consistent request pattern to the same `/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": "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.

## 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): Available for **72 hours** after completion
- **Base64 outputs** (when `return_base64: true`): Available for **60 minutes** after completion

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"
      }
    }
    ```

## 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 are request validation or auth failures that happen **before** a prediction ID is issued. They return an HTTP error code and a short payload. Example:

  **Example Response:**

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

No `id` or `status` is returned because the request never entered processing.

### 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 pricing summary in **Model Specifications** and, where needed, a detailed **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`    | 50 requests per 60 seconds |
| `/v1/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

All FASHN API endpoints are tagged with a lifecycle state to help you understand their stability and integration recommendations:

- `stable` - Mature endpoints that developers can trust will remain backwards-compatible. Any changes to these endpoints will maintain backwards compatibility.
- `preview` - Should be stable functionality with reliable integration support, but noticeable improvements to the underlying pipeline might still occur before final release.
- `experimental` - Supported endpoints that are still a work in progress. Underlying models or schema can change as we refine the technology.
- `deprecated` - Endpoints that are no longer supported and will be discontinued. Migration to newer alternatives is required.

You'll find the lifecycle state listed in each endpoint's "Model Specifications" section to help you make informed integration decisions.

## 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: Data Retention & Privacy
description: Understanding FASHN's data retention policies and privacy-enhanced options for data-sensitive applications
---

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

# Data Retention & Privacy

Understanding FASHNs data retention policies and privacy-enhanced options for data-sensitive applications

This guide consolidates all information about FASHN's data retention policies and privacy features to help you build data-sensitive applications with confidence.

This guide focuses on our [Virtual Try-On
  endpoint](/api-reference/tryon-v1-6), since it is our most privacy-sensitive
  use-case. However, the principles outlined here can be implemented in all
  other endpoints where applicable.

## What FASHN Stores vs. What We Don't

### What We Store

- **Request metadata:** Who sent the API request, what the inputs were (request body), and when the request was made (timestamp).
- **Image URLs:** The URLs you provide for `model_image` and `garment_image` are saved as part of the request body
- **Base64 placeholders:** For base64 inputs, we store `` in request history, not the actual string

### What We Don't Store

- **Input image files:** Never stored on our servers, regardless of input method
- **Base64 image data:** The actual base64 strings are never retained
- **Output images:** Outputs returned through our CDN are automatically deleted after 72 hours (when using `return_base64: true`, outputs are kept in memory for 60 minutes only)

**Storing image URLs does not compromise privacy if your URLs expire.**
  Although FASHN saves the URLs you submit, once those URLs have expired, your
  images are no longer accessible through them.

## Data Retention Timeline and Purpose

Output availability depends on your chosen delivery method:

### CDN Delivery (Default)

Image outputs are temporarily stored for up to **72 hours** for the following purposes:

1. **Dashboard Preview:** To allow you to conveniently preview your API outputs through the API dashboard.
2. **Data Transfer Window:** To provide sufficient time for you to transfer the data to your own storage, or to support use cases that do not require long-term storage.
3. **Support & Troubleshooting:** To enable us to assist effectively in the event that issues are reported with the outputs.
4. **Content Moderation & Abuse Prevention:** To allow us to conduct content moderation, review policy compliance, and investigate potential misuse of the technology.

After 72 hours, image outputs are **automatically deleted** and CDN URLs become inaccessible.

### Base64 Delivery (`return_base64: true`)

For enhanced privacy, base64 outputs are kept **in-memory only for 60 minutes** after completion. After this time limit:

- The status endpoint will return `"_expired"` instead of the actual base64 data
- No persistent storage occurs during this 60-minute window

Your [request history ↗](https://app.fashn.ai/api/requests) remains visible in the web app interface for monitoring and debugging purposes, showing:

- Request parameters and metadata
- URLs (but images at those URLs may be expired/inaccessible)
- `` placeholders for base64 inputs
- Status and error information

Your data is never used for training or improving our AI models in any form.

## Privacy-Enhanced Options

FASHN provides several API parameters to enhance privacy for data-sensitive applications:

### Privacy Parameters

**return_base64** (`boolean`)

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

**Privacy benefit:** User-generated outputs are not stored on FASHN servers when `return_base64` is enabled, giving you complete control over the generated content.

**Time limit:** Base64 outputs are available for **60 minutes** after completion. After this time, the status endpoint returns `"_expired"`.

Default: `false`

**model_image** (`image URL | base64`)

Primary image of the person on whom the virtual try-on will be performed. Can be provided as a publicly accessible URL or base64-encoded string.

**Privacy benefit:** Using base64 inputs means only `` placeholders appear in your [request history ↗](https://app.fashn.ai/api/requests), never the actual image data.

**garment_image** (`image URL | base64`)

Reference image of the clothing item to be tried on the `model_image`. Can be provided as a publicly accessible URL or base64-encoded string.

**Privacy benefit:** Using base64 inputs means only `` placeholders appear in your [request history ↗](https://app.fashn.ai/api/requests), never the actual image data.

Base64 strings must include the proper prefix: `data:image/;base64,` where `` is the image type (e.g., `jpeg`, `png`).

While using base64-encoded images enhances privacy by avoiding storage of your
  image data on FASHN servers, please be aware that requests with large base64
  payloads are more susceptible to network issues or being dropped due to
  exceeding request size limits. For best reliability, ensure your client and
  network can handle large request bodies, and consider using signed URLs for
  large images.

## Best Practices for Data-Sensitive Applications

Choose the privacy strategy that best fits your application's requirements:

### URL Expiry Strategy (Recommended)

**Most effective approach for balanced privacy and performance.** While FASHN stores URLs in request history, this becomes privacy-neutral when URLs expire.

**Implementation:**

- **Configure URL expiry:** Set your image hosting to make URLs inaccessible after your required timeframe
- **Use signed URLs:** Employ temporary, signed URLs that automatically expire

```bash
curl -X POST https://api.fashn.ai/v1/run \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_API_KEY_HERE" \
     -d '{
           "model_name": "tryon-v1.6",
           "inputs": {
             "model_image": "https://your-cdn.com/signed-url?expires=1735689600",
             "garment_image": "https://your-cdn.com/signed-url?expires=1735689600",
             "return_base64": true
           }
         }'
```

```js
fetch("https://api.fashn.ai/v1/run", {
  method: "POST",
  body: JSON.stringify({
    model_name: "tryon-v1.6",
    inputs: {
      model_image: "https://your-cdn.com/signed-url?expires=1735689600",
      garment_image: "https://your-cdn.com/signed-url?expires=1735689600",
      return_base64: true,
    },
  }),
  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": "https://your-cdn.com/signed-url?expires=1735689600",
            "garment_image": "https://your-cdn.com/signed-url?expires=1735689600",
            "return_base64": True
        }
    }
)
```

**Privacy benefits:** URLs become inaccessible after expiry, no output images stored

### Base64 Strategy (Maximum Privacy)

**For highly sensitive content where any URL storage is unacceptable.** Only `` placeholders appear in request history, never actual image data.

```bash
curl -X POST https://api.fashn.ai/v1/run \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_API_KEY_HERE" \
     -d '{
           "model_name": "tryon-v1.6",
           "inputs": {
             "model_image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
             "garment_image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
             "return_base64": true,
             "output_format": "png"
           }
         }'
```

```js
fetch("https://api.fashn.ai/v1/run", {
  method: "POST",
  body: JSON.stringify({
    model_name: "tryon-v1.6",
    inputs: {
      model_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
      garment_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
      return_base64: true,
      output_format: "png",
    },
  }),
  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": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
            "garment_image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
            "return_base64": True,
            "output_format": "png"
        }
    }
)
```

**Privacy benefits:** Zero image data touches FASHN's storage systems—all data stays within your API request/response cycle

### Hybrid Approach

**For applications with mixed privacy requirements:**

```bash
curl -X POST https://api.fashn.ai/v1/run \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_API_KEY_HERE" \
     -d '{
           "model_name": "tryon-v1.6",
           "inputs": {
             "model_image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
             "garment_image": "https://your-cdn.com/catalog-image.jpg",
             "return_base64": true
           }
         }'
```

```js
fetch("https://api.fashn.ai/v1/run", {
  method: "POST",
  body: JSON.stringify({
    model_name: "tryon-v1.6",
    inputs: {
      model_image: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
      garment_image: "https://your-cdn.com/catalog-image.jpg",
      return_base64: true,
    },
  }),
  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": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...",
            "garment_image": "https://your-cdn.com/catalog-image.jpg",
            "return_base64": True
        }
    }
)
```

Use standard URLs for non-sensitive images (product catalogs) and base64 for sensitive images (customer photos).

---

---
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 request was rejected before a prediction ID was issued.
- **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 status code and do **not** include an `id` or `status` because the request never entered processing. They are typically caused by auth, validation, or quota issues.

  **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.        |

If you retry after an API-level error, send the same payload. Because no
  prediction ID was issued, duplicate processing is not a risk.

## 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/terms-of-use). 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 [Virtual Try-On API](/api-reference/tryon-v1-6), 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-v1.6",
      inputs: {
        model_image: "http://example.com/path/to/model.jpg",
        garment_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-reference/tryon-v1-6#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: 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.

- **Model Name**: `background-remove`
- **Lifecycle**: experimental
- **Processing Time**: 1-3 seconds
- **Supported Resolution**: up to 4MP
- **Credits**: 1 credit per output image

## 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
            }
            ```

## Request Parameters

### Required Parameters

**image** (`image URL | base64`) *required*

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

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

### Optional Parameters

**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,...`.

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

**Default**: `false`

## 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: 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.

- **Model Name**: `edit`
- **Lifecycle**: experimental
- **Processing Time**: 20s–120s (see [below](#processing-time))
- **Credits**: 1-5 per output image depending on `resolution` and `generation_mode`

## 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
            }
            ```

## Request Parameters

**image** (`image URL | base64`) *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 | base64`)

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 | base64`)

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,...`).

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

**Default**: `false`

## 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 under 20 seconds, while the most intensive (`quality` + `4k`) can take up to 120 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: 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.

- **Model Name**: `face-to-model`
- **Lifecycle**: experimental
- **Processing Time**: 20s–120s (see [below](#processing-time))
- **Output Formats**: PNG, JPEG
- **Delivery Methods**: URL or Base64 encoding
- **Credits**: 1-5 per output image depending on `resolution` and `generation_mode`

## 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
            }
            ```

## Request Parameters

**face_image** (`image URL | base64`) *required*

URL or base64 encoded image of the face 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,...`.

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

**Default**: `false`

## 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 under 20 seconds, while the most intensive (`quality` + `4k`) can take up to 120 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: 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 single image into a short motion clip, with tasteful camera work and model movements tailored for fashion. Provide an image and optional instructions to produce engaging 5–10 second videos at up to 1080p.

- **Model Name**: `image-to-video`
- **Lifecycle**: experimental
- **Duration Options**: 5s, 10s
- **Resolutions**: 480p, 720p, 1080p
- **Output**: MP4 video URLs
- **Credits**: 1-12 per output video depending on `resolution` and `duration`

## 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
            }
            ```

## Request Parameters

### Required Parameters

**image** (`image URL | base64`) *required*

Source image to animate into a short video.

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

### Optional Parameters

**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 internal video engine.

Default: `1080p`

**end_image** (`image URL | base64`)

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.

Only supported with `resolution: "1080p"`. Other resolutions are rejected with a validation error.

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

## 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: API Reference
description: Complete reference for all FASHN API endpoints and their capabilities.
---

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

# API Reference

Complete reference for all FASHN API endpoints and their capabilities.

Welcome to the FASHN API Reference. This comprehensive collection covers all available endpoints for fashion AI, virtual try-on, model generation, and image processing capabilities.

---

---
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.

- **Model Name**: `model-create`
- **Lifecycle**: experimental
- **Processing Time**: 20s–120s (see [below](#processing-time))
- **Output Formats**: PNG, JPEG
- **Delivery Methods**: URL or Base64 encoding
- **Credits**: 1-5 per output image depending on `resolution` and `generation_mode` (`+3` per output image with `face_reference`)

## 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
            }
            ```

## Request Parameters

### Required Parameters

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

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

### Optional Parameters

**image_reference** (`image URL | base64`)

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.

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`).

**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 | base64`)

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.
- Adds roughly `20-30` 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,...`).

Enables stricter privacy because images are never uploaded to our CDN and are only available for 60 minutes after completion.

**Default**: `false`

## 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 under 20 seconds, while the most intensive (`quality` + `4k`) can take up to 120 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 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: 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.

- **Model Name**: `model-swap`
- **Lifecycle**: experimental
- **Processing Time**: 20s–120s (see [below](#processing-time))
- **Credits**: 1-5 per output image depending on `resolution` and `generation_mode` (`+3` per output image with `face_reference`)

## 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
            }
            ```

## Request Parameters

### Required Parameters

**model_image** (`image URL | base64`) *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.

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

### Optional Parameters

**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 | base64`)

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.

**Default**: None

**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,...`).

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

Default: `false`

## 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 under 20 seconds, while the most intensive (`quality` + `4k`) can take up to 120 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 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: 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.

- **Model Name**: `product-to-model`
- **Lifecycle**: preview
- **Processing Time**: 20s–120s (see [below](#processing-time))
- **Output Formats**: PNG, JPEG
- **Delivery Methods**: URL or Base64 encoding
- **Credits**: 1-5 per output image depending on `resolution` and `generation_mode` (`+3` per output image with `face_reference`)

To combine a product with an existing person image, use the
  [`tryon-max`](/api-reference/tryon-max) endpoint. The `model_image` parameter
  on this endpoint is deprecated and cannot be combined with `image_prompt`,
  `background_reference`, or `face_reference`.

## 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
            }
            ```

## Request Parameters

**product_image** (`image URL | base64`) *required*

URL or base64 encoded image of the product to be worn. Supports clothing,
  accessories, shoes, and other wearable fashion items.

**image_prompt** (`image URL | base64`)

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

**Default**: None

**face_reference** (`image URL | base64`)

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.

**Default**: None

**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**: None

**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 | base64`)

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**: None

**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,...`.

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

**Default**: `false`

**model_image** (`image URL | base64`)

URL or base64 encoded image of the person to wear the product. When provided, the endpoint adds the product to the existing person instead of generating a new one.

This parameter is deprecated. It cannot be combined with `image_prompt`, `background_reference`, or `face_reference`, which are designed to compose freely with each other but conflict with a fixed model image. For combining a product image with a specific person, use the [`tryon-max`](/api-reference/tryon-max) endpoint instead.

**Default**: None

## 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 under 20 seconds, while the most intensive (`quality` + `4k`) can take up to 120 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 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: 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.

- **Model Name**: `reframe`
- **Lifecycle**: experimental
- **Processing Time**: 20s–120s (see [below](#processing-time))
- **Credits**: 1-5 per output image depending on `resolution` and `generation_mode`

## 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
            }
            ```

## Request Parameters

**image** (`image URL | base64`) *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.

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

**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,...`).

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

**Default**: `false`

## 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 under 20 seconds, while the most intensive (`quality` + `4k`) can take up to 120 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: Try-On Max
description: Premium virtual try-on with enhanced fidelity for placing products on model images
---

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

# Try-On Max

Premium virtual try-on with enhanced fidelity for placing products on model images

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.

- **Model Name**: `tryon-max`
- **Lifecycle**: experimental
- **Processing Time**: 20s–120s (see [below](#processing-time))
- **Output Formats**: PNG, JPEG
- **Delivery Methods**: URL or Base64 encoding
- **Credits**: 2-5 per output image depending on `resolution` and `generation_mode`

## 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
            }
            ```

## Request Parameters

### Required Parameters

**product_image** (`image URL | base64`) *required*

URL or base64 encoded image of the product (garment, accessory, etc.) to place on the model.

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

**model_image** (`image URL | base64`) *required*

URL or base64 encoded image of the person to wear the product. The try-on process preserves the model's identity, pose, and styling while seamlessly integrating the product.

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

### Optional Parameters

**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** (`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. 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,...`).

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

**Default**: `false`

## Credit Cost

| `generation_mode` \ `resolution` | `1k` | `2k` | `4k` |
| -------------------------------- | ---- | ---- | ---- |
| `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 (`balanced` + `1k`) typically completes in under 30 seconds, while the most intensive (`quality` + `4k`) can take up to 120 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. It delivers reliable results in 5-8 seconds at 1 credit per image.

[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.

- **Model Name**: `tryon-v1.6`
- **Lifecycle**: stable
- **Processing Resolution**: 864×1296 pixels
- **Processing Time**:
  - Performance: 5 seconds
  - Balanced: 8 seconds
  - Quality: 12–17 seconds (variable depending on input resolution)
- **Credits**: 1 credit per output image

## 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
            }
            ```

## Request Parameters

### Required Parameters

**model_image** (`image URL | base64`) *required*

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

**garment_image** (`image URL | base64`) *required*

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

Base64 images must include the proper prefix (e.g., `data:image/jpg;base64,`)

### Optional Parameters

**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/terms-of-use).

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`Min: `0` Max: `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` Min: `1` Max: `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,...`).

This option offers enhanced privacy as user-generated outputs are not stored on our servers when `return_base64` is enabled.

Default: `false`

## 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: Coding Agents
description: Integrate FASHN with coding agents like Claude Code, Codex, and Cursor using the official FASHN agent skill.
---

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

# Coding Agents

Integrate FASHN with coding agents like Claude Code, Codex, and Cursor using the official FASHN agent skill.

FASHN publishes an [agent skill](https://www.skills.sh/docs) that teaches coding agents how to integrate FASHN 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 endpoint 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.

## 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**

- "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."
- "Use FASHN to write a Python worker that runs every garment in `./products` through a model."
- "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`:

- `/fashn generate three on-model shots of this product for our product page` (product-to-model)
- `/fashn do a try-on with this model photo and this jacket` (one-off inline run)

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:** Pick an integration path with the [TypeScript](/sdk/typescript) or [Python](/sdk/python) SDK, or browse the [API Reference](/api-reference).

---

---
title: API Setup
description: Complete guide to setting up your FASHN API account and making your first request
---

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

# API Setup

Complete guide to setting up your FASHN API account and making your first 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).

    ### 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.

    ### Purchase Credits

    Go to [Billing](https://app.fashn.ai/billing) -> Click on the **FASHN API** tab. 
    Choose between subscription plans or on-demand credit top-ups based on your usage needs.

    ### Understand the Fundamentals

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

    ### Try Virtual Try-On

    Start with our [Try-On Max](/api-reference/tryon-max) endpoint - our most capable virtual try-on model with the highest quality output.

    ### Explore Guides

    Check out our [Python](/guides/tryon-python-quickstart-guide) and [JavaScript](/guides/tryon-javascript-quickstart-guide) quickstart guides for implementation 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 [API Fundamentals](/api-overview/api-fundamentals) or jump directly to [Try-On Max](/api-reference/tryon-max).

---

---
title: Image Preprocessing Best Practices
description: Optimize images for the best API performance
---

> 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

Optimize images for the best API performance

To ensure optimal performance and consistent outputs when using the FASHN API, it’s important to preprocess your images. By following these guidelines, you can prevent issues like large payloads or inconsistent results.

---

## Recommended Steps

1. **Resize**

   - Resize images to fit within the maximum resolution supported by the endpoint you're using:
     - 1K endpoints (e.g., Try-On v1.6): max 2000px on the longest edge
     - 4K endpoints (e.g., Product to Model with `resolution: '4k'`): max 6000px on the longest edge
   - Maintain aspect ratio to avoid distortion.
   - Use a quality-preserving downsampling technique (e.g., LANCZOS or INTER_AREA) for best results.

2. **Convert to JPEG**

   - Use a quality setting of around 95 to balance file size and image clarity.

3. **Upload to a CDN**
   - Instead of embedding large base64 strings in your request, upload the processed image to a CDN, and provide the image URL in your API request

---

Following these best practices helps ensure that your requests reach our servers without issues, leading to faster response times and more consistent results with the FASHN Web App.

---

---
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.

---

---
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-v1.6",
      inputs: {
        model_image: modelImage,
        garment_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-v1.6 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 in real-time, 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-v1.6",
      inputs: {
        model_image: modelImage,
        garment_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-v1.6 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 5-15 seconds. 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: 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:
- [Virtual Try-On v1.6 Documentation](/api-reference/tryon-v1-6)
- [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 garment 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-v1.6",
    inputs: {
        model_image: "http://example.com/path/to/model.jpg",
        garment_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: Try-On Parameters
description: A detailed guide to all parameters available in FASHN’s virtual try-on API
---

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

# Try-On Parameters

A detailed guide to all parameters available in FASHN’s virtual try-on API

### 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/terms-of-use).

  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,...`).

This option offers enhanced privacy, as it means user-generated outputs are not stored on Fashn.ai's servers when `return_base64` is enabled, giving users more control over their data.

---

---
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:
- [Virtual Try-On v1.6 Documentation](/api-reference/tryon-v1-6)
- [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 garment 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: 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-v1.6",
    inputs={
        "garment_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-v1.6",
        inputs={
            "garment_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-v1.6",
        inputs={
            "model_image": "https://example.com/model.jpg",
            "garment_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-v1.6",
    inputs={
        "model_image": "https://example.com/model.jpg",
        "garment_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-v1.6",
    inputs: {
      model_image: "https://example.com/path/to/model.jpg",
      garment_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-v1.6",
      inputs: {
        model_image: "https://example.com/model.jpg",
        garment_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-v1.6",
  inputs: {
    model_image: "https://example.com/model.jpg",
    garment_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: 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, API subscription credits (if you have an active subscription), and any additional on-demand credits you've purchased.

- **Subscription Credits**: Included with your monthly API plan
- **On-Demand Credits**: Additional credits purchased separately  
- **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 included with your current API subscription plan. These credits reset monthly based on your billing cycle.

**on_demand** (`integer`)

Additional credits purchased separately from your subscription. These credits are consumed after subscription credits.

## 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).