### Install FASHN Python SDK Source: https://docs.fashn.ai/sdk/python Install the FASHN Python SDK using pip. This is the first step to integrate with the FASHN API. ```bash pip install fashn ``` -------------------------------- ### Install FASHN SDK Source: https://docs.fashn.ai/guides/react-router-quickstart Install the FASHN TypeScript SDK using npm. This SDK handles authentication, polling, and error management for server-side environments. ```bash npm install fashn ``` -------------------------------- ### Install FASHN SDK Source: https://docs.fashn.ai/guides/nextjs-quickstart Installs the FASHN TypeScript SDK using npm. This SDK is intended for server-side use only to keep your API key secure. ```bash npm i fashn ``` -------------------------------- ### Successful Response Example Source: https://docs.fashn.ai/api-reference/product-to-model Example of a successful response from the status endpoint after image generation. ```APIDOC ## 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 } ``` ### Response Parameters - **id** (string) - Unique identifier for the prediction. - **status** (string) - The current status of the generation job (e.g., "completed"). - **output** (array of strings) - A list of URLs to the generated images or base64 encoded strings if `return_base64` is true. - **error** (null or object) - Contains error details if the generation failed, otherwise null. ``` -------------------------------- ### Scaffold a New React Router Project Source: https://docs.fashn.ai/guides/react-router-quickstart Use this command to create a new React Router application with Vite, TypeScript, and Tailwind CSS. Navigate into the project directory and start the development server. ```bash npx create-react-router@latest my-rr-fashn-app cd my-rr-fashn-app npm run dev ``` -------------------------------- ### Webhook Payload Examples Source: https://docs.fashn.ai/api-overview/webhooks Expected JSON structures for successful and failed process notifications. ```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 } ``` ```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" } } ``` -------------------------------- ### Run FASHN.AI Prediction with JavaScript Source: https://docs.fashn.ai/guides/tryon-javascript-quickstart-guide This snippet demonstrates a basic request using model and garment image URLs. It handles API key setup, initiating a prediction via POST to the /run endpoint, and polling the /status/ endpoint until completion. Adapt this code to send local images in Base64 format if needed. ```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(); ``` -------------------------------- ### Quick Start: Generate Prediction with FASHN SDK Source: https://docs.fashn.ai/sdk/typescript Use the `subscribe` method to automatically handle the prediction lifecycle, including submission, polling, and result retrieval. Ensure your API key is securely stored and not exposed client-side. ```typescript import Fashn from "fashn"; 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(); ``` -------------------------------- ### Set Up Environment Variables Source: https://docs.fashn.ai/guides/react-router-quickstart Create a .env.local file in your project root to store your FASHN API key. Ensure this file is added to your .gitignore to prevent committing sensitive keys. ```env FASHN_API_KEY=your_api_key_here ``` -------------------------------- ### POST /run (with Webhook) Source: https://docs.fashn.ai/api-overview/webhooks Initiates a process and registers a webhook URL to receive asynchronous status updates. ```APIDOC ## POST /run ### Description Initiates a process and registers a webhook URL to receive asynchronous status updates when the process completes. ### Method POST ### Endpoint https://api.fashn.ai/v1/run ### Parameters #### Query Parameters - **webhook_url** (string) - Required - The URL where the system will send the POST request upon process completion. #### Request Body - **model_name** (string) - Required - The name of the model to use (e.g., "tryon-v1.6"). - **inputs** (object) - Required - Input data containing model_image and garment_image URLs. ### Request Example { "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 #### Success Webhook Payload - **id** (string) - Unique identifier for the process. - **status** (string) - The status of the process (e.g., "completed"). - **output** (array) - List of URLs containing the generated output images. - **error** (null) - Null if the process succeeded. #### Error Webhook Payload - **id** (string) - Unique identifier for the process. - **status** (string) - The status of the process (e.g., "failed"). - **error** (object) - Contains error details including name and message. ``` -------------------------------- ### Perform Virtual Try-On with Python Source: https://docs.fashn.ai/guides/tryon-python-quickstart-guide Demonstrates a basic request using model and garment image URLs. Requires the FASHN_API_KEY environment variable to be set. ```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 = { "model_name": "tryon-v1.6", "inputs": { "model_image": "https://v3.fal.media/files/panda/jRavCEb1D4OpZBjZKxaH7_image_2024-12-08_18-37-27%20Large.jpeg", "garment_image": "https://v3.fal.media/files/elephant/qXMQpeM6fVOlg7bZs0dEh_fashn-tshirt-2.png" } } headers = {"Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}"} run_response = requests.post(f"{BASE_URL}/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"{BASE_URL}/status/{prediction_id}", 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 ``` -------------------------------- ### POST /v1/run Source: https://docs.fashn.ai/api-reference/background-remove Submit an image to the background removal model to initiate processing. ```APIDOC ## POST /v1/run ### Description Submits a source image to the background removal model. The API returns a prediction ID used for status polling. ### Method POST ### Endpoint https://api.fashn.ai/v1/run ### Parameters #### Request Body - **model_name** (string) - Required - Must be "background-remove" - **inputs** (object) - Required - Contains the image source - **inputs.image** (string) - Required - Image URL or base64 string (with prefix) - **return_base64** (boolean) - Optional - If true, returns the image as a base64 string instead of a URL. Default: false ### Request Example { "model_name": "background-remove", "inputs": { "image": "https://example.com/portrait.jpg" } } ### Response #### Success Response (200) - **id** (string) - The prediction ID for status polling - **error** (null) - Error status #### Response Example { "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1", "error": null } ``` -------------------------------- ### Runtime Error Response Example Source: https://docs.fashn.ai/api-overview/error-handling Example of a runtime error response when a prediction is accepted but fails during execution. Includes prediction ID and error details. ```json { "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1", "status": "failed", "error": { "name": "ImageLoadError", "message": "Error loading model image: Invalid URL format" } } ``` -------------------------------- ### Configure FASHN API Key Source: https://docs.fashn.ai/guides/nextjs-quickstart Sets up your FASHN API key as a server-side environment variable in a `.env.local` file. Do not use the `NEXT_PUBLIC_` prefix, and restart your development server after changes. ```env FASHN_API_KEY=your_api_key_here ``` -------------------------------- ### GET /predictions/status Source: https://docs.fashn.ai/sdk/typescript Fetches the current status of a previously submitted prediction request using its ID. ```APIDOC ## GET /predictions/status ### Description Use the prediction ID returned from the run method to fetch the status of the request. ### Method GET ### Parameters #### Path Parameters - **prediction_id** (string) - Required - The unique ID of the prediction request. ### Response #### Success Response (200) - **status** (string) - The current status of the prediction request. ``` -------------------------------- ### GET /v1/status/{id} Source: https://docs.fashn.ai/api-overview/api-fundamentals Poll the status of a previously submitted prediction using its unique ID. ```APIDOC ## GET /v1/status/{id} ### Description Polls the current status and retrieves results for a specific prediction ID. ### Method GET ### Endpoint https://api.fashn.ai/v1/status/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique prediction ID returned by the /v1/run endpoint. ### Response #### Success Response (200) - **id** (string) - The prediction ID. - **status** (string) - Current state: 'starting', 'in_queue', 'processing', 'completed', or 'failed'. - **output** (array) - List of result URLs (only if completed). - **error** (object) - Error details (only if failed). #### Response Example { "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 } ``` -------------------------------- ### POST /v1/run Source: https://docs.fashn.ai/api-reference/image-to-video Submit an image to the image-to-video model to generate a short motion clip. ```APIDOC ## POST /v1/run ### Description Animate a single image into a short video clip using the image-to-video model. ### Method POST ### Endpoint https://api.fashn.ai/v1/run ### Parameters #### Request Body - **model_name** (string) - Required - Must be "image-to-video" - **inputs** (object) - Required - Contains the configuration for the video generation - **image** (string) - Required - Image URL or base64 encoded string - **duration** (integer) - Optional - 5 or 10 seconds. Default: 5 - **resolution** (string) - Optional - 480p, 720p, or 1080p. Default: 1080p - **prompt** (string) - Optional - Motion guidance string. Default: empty ### Request Example { "model_name": "image-to-video", "inputs": { "image": "https://example.com/photo.jpg", "duration": 5, "resolution": "1080p" } } ### Response #### Success Response (200) - **id** (string) - The prediction ID used for status polling - **error** (null) - Error status #### Response Example { "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1", "error": null } ``` -------------------------------- ### Virtual Try-On Parameters Source: https://docs.fashn.ai/guides/tryon-parameters-guide Configuration parameters for the virtual try-on process. ```APIDOC ## Virtual Try-On Parameters ### Description Parameters used to configure the virtual try-on process, including image inputs, garment categorization, and generation quality settings. ### Parameters #### Request Body - **model_image** (string) - Required - The primary image of the person (URL or base64 string). - **garment_image** (string) - Required - The reference image of the clothing item (URL or base64 string). - **category** (string) - Optional - Garment type: 'auto', 'tops', 'bottoms', or 'one-pieces'. - **mode** (string) - Optional - Processing mode: 'performance', 'balanced', or 'quality'. - **garment_photo_type** (string) - Optional - Photo type: 'auto', 'model', or 'flat-lay'. - **num_samples** (integer) - Optional - Number of images to generate in a single run. - **seed** (integer) - Optional - Seed for random operations (Default: 42, Range: 0 to 2^32 - 1). ``` -------------------------------- ### GET /status Source: https://docs.fashn.ai/api-reference/edit Retrieves the current status and output URLs for a specific image editing request. ```APIDOC ## GET /status ### Description Returns the status of an image editing task and provides URLs to the generated output images upon completion. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the edit request. - **status** (string) - The current state of the request (e.g., "completed"). - **output** (array) - A list of URLs pointing to the edited images. - **error** (null|string) - Error details if the request failed. #### Response Example { "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 } ``` -------------------------------- ### GET /status/{prediction_id} Source: https://docs.fashn.ai/api-reference/model-swap Polls the status of a submitted model swap request using the prediction ID. ```APIDOC ## GET /status/{prediction_id} ### Description Polls the status of a model swap request. Use this endpoint to check if the processing is complete and to retrieve the output image URLs. ### Method GET ### Endpoint /status/{prediction_id} ### Response #### Success Response (200) - **id** (string) - The unique identifier for the prediction. - **status** (string) - The current status of the request (e.g., "completed"). - **output** (array) - A list of URLs pointing to the processed images. - **error** (string/null) - Error message if the process failed, otherwise null. #### Response Example { "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 } ``` -------------------------------- ### GET /v1/credits Source: https://docs.fashn.ai/utility-endpoints/credits Retrieve the current FASHN API credits balance, including total, subscription, and on-demand credits. ```APIDOC ## GET /v1/credits ### Description Retrieve your current FASHN API credits balance. The response includes your total credits, API subscription credits, and any additional on-demand credits. ### Method GET ### Endpoint https://api.fashn.ai/v1/credits ### Response #### Success Response (200) - **credits** (object) - Container object for all credit information. - **total** (integer) - Your total available credits (subscription + on-demand credits combined). - **subscription** (integer) - Credits included with your current API subscription plan. - **on_demand** (integer) - Additional credits purchased separately from your subscription. #### Response Example { "credits": { "total": 234, "subscription": 100, "on_demand": 134 } } ``` -------------------------------- ### Create Next.js Project Source: https://docs.fashn.ai/guides/nextjs-quickstart Scaffolds a new Next.js application with default settings including App Router and TypeScript. Ensure you are in your desired project directory before running. ```bash npx create-next-app@latest my-fashn-app --yes cd my-fashn-app npm run dev ``` -------------------------------- ### Submit a request to Fashn.AI API Source: https://docs.fashn.ai/sdk/python Submit a request to the API and get a prediction ID. Ensure your FASHN_API_KEY is set in your environment variables. ```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) ``` -------------------------------- ### Generate Product to Model Images Source: https://docs.fashn.ai/api-reference/product-to-model Submit product and model images to the /v1/run endpoint to initiate the generation process. ```cURL 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", "model_image": "http://example.com/path/to/person.jpg", "prompt": "professional office setting", "output_format": "png", "return_base64": false } }' ``` -------------------------------- ### GET /status/{id} Source: https://docs.fashn.ai/api-reference/tryon-max Endpoint to retrieve the status of a try-on generation job. You can poll this endpoint using the job ID to check for completion. ```APIDOC ## GET /status/{id} ### Description Retrieves the status and output of a try-on generation job. ### Method GET ### Endpoint /status/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the try-on generation job. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the try-on generation job. - **status** (string) - The current status of the job (e.g., "completed", "processing", "failed"). - **output** (array) - An array of URLs pointing to the generated try-on images if the job is completed successfully. - **error** (string or null) - Contains error details if the job failed, otherwise null. #### Response Example ```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 } ``` ``` -------------------------------- ### API-Level Unauthorized Access Error Response Source: https://docs.fashn.ai/api-overview/error-handling Example of an HTTP 401 Unauthorized response for API-level errors. This occurs when authentication fails and no prediction ID is issued. ```json // HTTP 401 UnauthorizedAccess { "error": "UnauthorizedAccess", "message": "Unauthorized: Invalid token" } ``` -------------------------------- ### Implement Webhook Request with Fetch Source: https://docs.fashn.ai/api-overview/webhooks Initiate a process with a webhook notification using the fetch API. ```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", }, }), }, ); ``` -------------------------------- ### Create Server Action for Image Generation Source: https://docs.fashn.ai/guides/nextjs-quickstart Use this Server Action to run secure backend code for virtual try-on. It initializes the FASHN client, calls the subscribe method for generation, and handles potential API or runtime errors. ```typescript "use server"; import Fashn from "fashn"; 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" }; } } } ``` -------------------------------- ### POST /v1/run - Product to Model Source: https://docs.fashn.ai/api-reference/product-to-model Transforms product images into people wearing those products using AI. Supports dual-mode operation: standard product-to-model (generates new person) and try-on mode (adds product to existing person). Designed for wearable fashion items. ```APIDOC ## POST /v1/run ### Description Generates product-to-model images by submitting product and optional model images to the universal `/v1/run` endpoint. This endpoint transforms product images into people wearing those products, supporting both generating a new person and adding the product to an existing person's image. ### Method POST ### Endpoint `https://api.fashn.ai/v1/run` ### Parameters #### Request Body - **model_name** (string) - Required - Specifies the model to use, should be `"product-to-model"`. - **inputs** (object) - Required - Contains the input parameters for the model. - **product_image** (string) - Required - URL or base64 encoded image of the product to be worn. Supports clothing, accessories, shoes, and other wearable fashion items. - **model_image** (string) - Optional - URL or base64 encoded image of the person to wear the product. When provided, enables try-on mode. When omitted, generates a new person wearing the product. Cannot be combined with other image inputs (`image_prompt`, `face_reference`, or `background_reference`). - **image_prompt** (string) - Optional - URL or base64 encoded inspiration image that guides pose, environment, and lighting while keeping the product centered in the final output. - **face_reference** (string) - Optional - URL or base64 encoded 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. - **face_reference_mode** (string) - Optional - Controls how the identity from `face_reference` influences pose and expression. Supported values: `'match_base'`, `'match_reference'`. Default: `'match_reference'`. - **prompt** (string) - Optional - Additional instructions for person appearance (when `model_image` is not provided), styling preferences or background. Examples: "man with tattoos", "tucked-in", "open jacket", "rolled-up sleeves", "studio background". - **output_format** (string) - Optional - Desired output format for the image. Supported values: `"png"`, `"jpeg"`. Default: `"png"`. - **return_base64** (boolean) - Optional - If true, returns the output image as a base64 encoded string. If false, returns a URL to the image. Default: `false`. - **aspect_ratio** (string) - Optional - Desired aspect ratio for the output image. 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** (string) - Optional - Output resolution tier. Supported values: `'1k'`, `'2k'`, `'4k'`. Default: `'1k'`. - **generation_mode** (string) - Optional - Sets the generation quality level. Supported values: `'fast'`, `'balanced'`, `'quality'`. Default: FASHN selects automatically (billed as 'fast' at 1k, 'quality' at 2k/4k if omitted). - **background_reference** (string) - Optional - 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. - **seed** (integer) - Optional - Seed for reproducible results. Must be between 0 and 2^32-1. Default: 42. ### Request Example ```json { "model_name": "product-to-model", "inputs": { "product_image": "http://example.com/path/to/product.jpg", "model_image": "http://example.com/path/to/person.jpg", "prompt": "professional office setting", "output_format": "png", "return_base64": false } } ``` ### Response #### Success Response (200) Returns a prediction ID for status polling. - **id** (string) - The unique identifier for the prediction job. - **error** (object | null) - An error object if the request failed, otherwise null. #### Response Example ```json { "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1", "error": null } ``` ``` -------------------------------- ### Generate Try-On Images via cURL Source: https://docs.fashn.ai/api-reference/tryon-max Submit a POST request to the /v1/run endpoint with product and model image URLs. ```cURL 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" } }' ``` -------------------------------- ### Implement the Home Page UI in Next.js Source: https://docs.fashn.ai/guides/nextjs-quickstart Replaces the contents of app/page.tsx to provide a UI for selecting images and triggering the virtual try-on generation. Requires the runGeneration server action to be defined. ```tsx "use client"; import Image from "next/image"; import { runGeneration } from "./actions"; import { useState } from "react"; 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 Garment Image
Model Image Model Image
{result && Result Image} {error &&

{error}

} {loading &&

Loading...

}
Result Image
); } ``` -------------------------------- ### FASHN Virtual Try-On v1.6 API Source: https://docs.fashn.ai/api-reference Fast, lightweight virtual try-on optimized for real-time e-commerce experiences. ```APIDOC ## FASHN Virtual Try-On v1.6 API ### Description Fast, lightweight virtual try-on optimized for real-time e-commerce experiences. ### Method POST ### Endpoint /api/v1.6/tryon ### Parameters #### Request Body - **image_url** (string) - Required - URL of the person's image. - **clothing_url** (string) - Required - URL of the clothing item image. ### Request Example ```json { "image_url": "https://example.com/person_for_tryon.jpg", "clothing_url": "https://example.com/item_of_clothing.jpg" } ``` ### Response #### Success Response (200) - **tryon_image_url** (string) - URL of the virtual try-on result. #### Response Example ```json { "tryon_image_url": "https://example.com/tryon_result_v1_6.jpg" } ``` ``` -------------------------------- ### POST /v1/run Source: https://docs.fashn.ai/api-reference/model-create Submit a request to generate fashion models using the model-create model. ```APIDOC ## POST /v1/run ### Description Generate fashion models by submitting your prompt and optional reference assets to the universal /v1/run endpoint. ### Method POST ### Endpoint https://api.fashn.ai/v1/run ### Parameters #### Request Body - **model_name** (string) - Required - Must be "model-create". - **inputs** (object) - Required - Contains the generation parameters. - **prompt** (string) - Required - Description of the desired fashion model, clothing, pose, and scene. - **image_reference** (string) - Optional - Image URL or base64 string to guide composition and pose. - **aspect_ratio** (string) - Optional - Width-to-height ratio (e.g., "1:1", "16:9"). Default: "1:1". - **face_reference** (string) - Optional - Portrait image URL or base64 to lock in identity. - **face_reference_mode** (string) - Optional - 'match_base' or 'match_reference'. Default: 'match_reference'. - **resolution** (string) - Optional - '1k', '2k', or '4k'. Default: '1k'. - **generation_mode** (string) - Optional - 'fast', 'balanced', or 'quality'. - **seed** (integer) - Optional - Random seed for reproducibility. Default: 42. - **num_images** (integer) - Optional - Number of images to generate (1-4). Default: 1. - **output_format** (string) - Optional - 'png' or 'jpeg'. Default: 'png'. - **return_base64** (boolean) - Optional - If true, returns base64 string instead of URL. Default: false. ### Request Example { "model_name": "model-create", "inputs": { "prompt": "Full body shot, woman wearing a white t-shirt and dark blue biker shorts" } } ### Response #### Success Response (200) - **id** (string) - Prediction ID for status polling. - **error** (null) - Error status. #### Response Example { "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1", "error": null } ``` -------------------------------- ### Implement FASHN Server Action Source: https://docs.fashn.ai/guides/react-router-quickstart Handles the virtual try-on generation process by subscribing to the FASHN API and managing runtime or network errors. ```typescript import Fashn from "fashn"; 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" }; } } } ``` -------------------------------- ### Virtual Try-On API - Output Formats Source: https://docs.fashn.ai/api-reference/tryon-v1-6 This section explains the `return_base64` parameter, which controls whether the output image is returned as a base64-encoded string or a CDN URL. ```APIDOC ## `return_base64` Parameter ### Description 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` ``` -------------------------------- ### POST /v1/run Source: https://docs.fashn.ai/api-reference/tryon-v1-6 Submits a virtual try-on request using the tryon-v1.6 model. Returns a prediction ID for status polling. ```APIDOC ## POST /v1/run ### Description Generates a virtual try-on by submitting model and garment images to the FASHN API. ### Method POST ### Endpoint https://api.fashn.ai/v1/run ### Parameters #### Request Body - **model_name** (string) - Required - The model identifier, e.g., "tryon-v1.6". - **inputs** (object) - Required - Contains model_image and garment_image URLs or base64 strings. - **category** (string) - Optional - 'auto' | 'tops' | 'bottoms' | 'one-pieces'. Default: 'auto'. - **segmentation_free** (boolean) - Optional - Direct garment fitting without segmentation. Default: true. - **moderation_level** (string) - Optional - 'conservative' | 'permissive' | 'none'. Default: 'permissive'. - **garment_photo_type** (string) - Optional - 'auto' | 'flat-lay' | 'model'. Default: 'auto'. - **mode** (string) - Optional - 'performance' | 'balanced' | 'quality'. Default: 'balanced'. - **seed** (integer) - Optional - Random seed for reproducibility. Default: 42. - **num_samples** (integer) - Optional - Number of images to generate. Default: 1. - **output_format** (string) - Optional - 'png' | 'jpeg'. Default: 'png'. ### Request Example { "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 #### Success Response (200) - **id** (string) - The prediction ID used for status polling. - **error** (null) - Error status. #### Response Example { "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1", "error": null } ``` -------------------------------- ### Generate Fashion Models via API Source: https://docs.fashn.ai/api-reference/model-create Submit a POST request to the /v1/run endpoint to initiate image generation. Requires an API key in the Authorization header. ```cURL 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" } }' ``` -------------------------------- ### POST /v1/run - Try-On Max Endpoint Source: https://docs.fashn.ai/api-reference/tryon-max Submit product and model images to the /v1/run endpoint to generate virtual try-on images. This endpoint supports various wearable fashion items and offers customization options for resolution, generation mode, and more. ```APIDOC ## POST /v1/run ### Description Generates virtual try-on images by placing a product onto a model image with enhanced fidelity. Suitable for e-commerce PDPs, catalogs, and marketing assets. ### Method POST ### Endpoint `https://api.fashn.ai/v1/run` ### Parameters #### Request Body - **model_name** (string) - Required - Specifies the model to use. For this endpoint, it must be `"tryon-max"`. - **inputs** (object) - Required - Contains the input images. - **product_image** (string) - Required - URL or base64 encoded image of the product. - **model_image** (string) - Required - URL or base64 encoded image of the model. - **prompt** (string) - Optional - Instructions to customize the try-on result (e.g., `"remove scarf"`, `"tuck in shirt"`). Defaults to an empty string. - **resolution** ('1k' | '2k' | '4k') - Optional - Output resolution tier. Defaults to `'1k'`. - **generation_mode** ('balanced' | 'quality') - Optional - Sets the generation quality level. Defaults to `'quality'` if omitted for `tryon-max`. - **seed** (integer) - Optional - Sets random operations to a fixed state for reproducible results. Defaults to `42`. - **num_images** (integer) - Optional - Number of images to generate. Must be between 1 and 4. Defaults to 1. - **output_format** ('png' | 'jpeg') - Optional - Specifies the output image format. Defaults to `png`. - **return_base64** (boolean) - Optional - If true, returns the image as a base64-encoded string instead of a URL. Defaults to `false`. ### Request Example ```json { "model_name": "tryon-max", "inputs": { "product_image": "https://example.com/garment.jpg", "model_image": "https://example.com/person.jpg" }, "prompt": "tuck in shirt", "resolution": "2k", "generation_mode": "quality", "num_images": 1, "output_format": "jpeg", "return_base64": false } ``` ### Response #### Success Response (200) - **id** (string) - A prediction ID for status polling. - **error** (null) - Indicates no error occurred. #### Response Example ```json { "id": "123a87r9-4129-4bb3-be18-9c9fb5bd7fc1-u1", "error": null } ``` ```