fashn-logo
FASHNAI

JavaScript Quickstart Guide

Below is a minimal JavaScript snippet to demonstrate how to:

  1. POST to the /run endpoint with your input data.
  2. Poll the /status/<ID> 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:


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.

// 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_image: "http://example.com/path/to/model.jpg",
    garment_image: "http://example.com/path/to/garment.jpg",
    category: "tops",
};
 
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();

On this page