Docs

API Documentation

Smart Replace API Documentation

Base URL: https://api.ideal.house
Version: v1
Updated: 2026-03-06


πŸ“– Overview

The Smart Replace API allows you to intelligently replace a selected area in an image with AI-generated content based on your text prompt. You provide a source image, a mask image that defines the area to be replaced, and a text prompt describing what should fill that area. The AI will seamlessly blend the generated content into the original image. The workflow is asynchronous and involves two steps:

  1. Create a task β€” Submit your image, mask, and prompt, then receive a taskId.
  2. Poll for results β€” Use the taskId to query task status and retrieve the result image.

πŸ” Authentication

All API requests must be authenticated using an API Key.

Include your API Key in the request header:

HeaderValue
APIKEYyour_api_key_here

⚠️ Keep your API Key secure. Do not expose it in client-side code or public repositories.


πŸ’° Credits Deduction

[!WARNING] πŸͺ™ Each task deducts 1 credit from your account upon successful task creation. If the task ultimately fails, the deducted credits will be automatically refunded to your account.
Insufficient credits will return error code 9051. πŸ“„ See Credits Deduction Reference.


πŸ–ΌοΈ Mask Image Format

The mask image defines the area to be replaced in the source image.

Mask Rules:

ColorMeaning
⬛ BlackArea to be replaced (region where new content will be generated)
⬜ WhiteArea to be preserved (background to keep unchanged)

⚠️ The mask image must match the same dimensions as the source image (imageUrl).

Mask Example:

Mask Example

The black area in the mask marks the region to be replaced by AI; the white area is the background to preserve.


πŸ“Œ API Endpoints


1. Create Smart Replace Task

Creates a new AI smart replace task and returns a unique taskId for polling.

Endpoint

POST /api/v1/smartReplace/generate

Request Headers

HeaderRequiredDescription
APIKEYβœ… YesYour API authentication key
Content-Typeβœ… Yesapplication/json

Request Body

FieldTypeRequiredDescription
imageUrlstringβœ… YesURL of the source image
promptstringβœ… YesText prompt describing the content to generate in the masked area (e.g., "a modern armchair", "marble flooring")
maskUrlstring⚠️ Either maskUrl or maskBase64URL of the mask image. Black areas will be replaced; white areas will be preserved
maskBase64string⚠️ Either maskUrl or maskBase64Base64-encoded mask image (PNG format recommended). Used when you cannot provide a hosted URL

⚠️ At least one of maskUrl or maskBase64 must be provided. If both are given, maskUrl takes precedence.


πŸ“₯ Request Examples

cURL

# Using maskUrl
curl -X POST "https://api.ideal.house/api/v1/smartReplace/generate" \
  -H "APIKEY: your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "imageUrl": "https://example.com/room.jpg",
    "prompt": "a modern velvet sofa in dark blue",
    "maskUrl": "https://example.com/mask.png"
  }'

# Using maskBase64
curl -X POST "https://api.ideal.house/api/v1/smartReplace/generate" \
  -H "APIKEY: your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "imageUrl": "https://example.com/room.jpg",
    "prompt": "a modern velvet sofa in dark blue",
    "maskBase64": "iVBORw0KGgoAAAANSUhEUgAA..."
  }'

Java (OkHttp)

import okhttp3.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

public class SmartReplaceApiExample {

    private static final String BASE_URL = "https://api.ideal.house";
    private static final String API_KEY  = "your_api_key_here";

    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        // Option 1: Use maskUrl
        String requestBody = """
            {
                "imageUrl": "https://example.com/room.jpg",
                "prompt": "a modern velvet sofa in dark blue",
                "maskUrl": "https://example.com/mask.png"
            }
            """;

        // Option 2: Use maskBase64 (encode local mask file)
        // byte[] maskBytes = Files.readAllBytes(Path.of("/path/to/mask.png"));
        // String maskBase64 = Base64.getEncoder().encodeToString(maskBytes);
        // String requestBody = """
        //     {
        //         "imageUrl": "https://example.com/room.jpg",
        //         "prompt": "a modern velvet sofa in dark blue",
        //         "maskBase64": "%s"
        //     }
        //     """.formatted(maskBase64);

        Request request = new Request.Builder()
            .url(BASE_URL + "/api/v1/smartReplace/generate")
            .addHeader("APIKEY", API_KEY)
            .addHeader("Content-Type", "application/json")
            .post(RequestBody.create(requestBody, MediaType.parse("application/json")))
            .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("Response: " + response.body().string());
        }
    }
}

Python (requests)

import requests
import base64

BASE_URL = "https://api.ideal.house"
API_KEY  = "your_api_key_here"

headers = {
    "APIKEY": API_KEY,
    "Content-Type": "application/json"
}

# Option 1: Use maskUrl
payload = {
    "imageUrl": "https://example.com/room.jpg",
    "prompt": "a modern velvet sofa in dark blue",
    "maskUrl": "https://example.com/mask.png"
}

# Option 2: Use maskBase64 (encode local mask file)
# with open("/path/to/mask.png", "rb") as f:
#     mask_base64 = base64.b64encode(f.read()).decode("utf-8")
# payload = {
#     "imageUrl": "https://example.com/room.jpg",
#     "prompt": "a modern velvet sofa in dark blue",
#     "maskBase64": mask_base64
# }

response = requests.post(
    f"{BASE_URL}/api/v1/smartReplace/generate",
    headers=headers,
    json=payload
)

data = response.json()
task_id = data.get("data")
print(f"Task ID: {task_id}")

Node.js (axios)

const axios = require('axios');
const fs = require('fs');

const BASE_URL = 'https://api.ideal.house';
const API_KEY  = 'your_api_key_here';

async function createSmartReplaceTask() {
  try {
    // Option 1: Use maskUrl
    const payload = {
      imageUrl: 'https://example.com/room.jpg',
      prompt: 'a modern velvet sofa in dark blue',
      maskUrl: 'https://example.com/mask.png'
    };

    // Option 2: Use maskBase64 (encode local mask file)
    // const maskBuffer = fs.readFileSync('/path/to/mask.png');
    // const maskBase64 = maskBuffer.toString('base64');
    // const payload = {
    //   imageUrl: 'https://example.com/room.jpg',
    //   prompt: 'a modern velvet sofa in dark blue',
    //   maskBase64: maskBase64
    // };

    const response = await axios.post(
      `${BASE_URL}/api/v1/smartReplace/generate`,
      payload,
      {
        headers: {
          'APIKEY': API_KEY,
          'Content-Type': 'application/json'
        }
      }
    );

    const taskId = response.data.data;
    console.log('Task ID:', taskId);
    return taskId;
  } catch (error) {
    console.error('Error:', error.response?.data || error.message);
  }
}

createSmartReplaceTask();

πŸ“€ Response

Success Response

{
  "code": 0,
  "message": "success",
  "data": 1234567890123456789
}
FieldTypeDescription
codeinteger0 indicates success
messagestringResponse message
datalongThe unique task ID for polling results

2. Get Task Result

Retrieves the current status and output of a previously created smart replace task.

Endpoint

GET /api/v1/smartReplace/result

Request Headers

HeaderRequiredDescription
APIKEYβœ… YesYour API authentication key

Query Parameters

ParameterTypeRequiredDescription
taskIdlongβœ… YesThe task ID returned from the create task endpoint

πŸ“₯ Request Examples

cURL

curl -X GET "https://api.ideal.house/api/v1/smartReplace/result?taskId=1234567890123456789" \
  -H "APIKEY: your_api_key_here"

Java (OkHttp)

import okhttp3.*;
import java.io.IOException;

public class SmartReplaceResultExample {

    private static final String BASE_URL = "https://api.ideal.house";
    private static final String API_KEY  = "your_api_key_here";

    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();
        long taskId = 1234567890123456789L;

        Request request = new Request.Builder()
            .url(BASE_URL + "/api/v1/smartReplace/result?taskId=" + taskId)
            .addHeader("APIKEY", API_KEY)
            .get()
            .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("Response: " + response.body().string());
        }
    }
}

Python (requests)

import requests
import time

BASE_URL = "https://api.ideal.house"
API_KEY  = "your_api_key_here"

headers = {
    "APIKEY": API_KEY
}

task_id = 1234567890123456789

# Poll until task is complete
while True:
    response = requests.get(
        f"{BASE_URL}/api/v1/smartReplace/result",
        headers=headers,
        params={"taskId": task_id}
    )

    data = response.json()
    result = data.get("data", {})
    status = result.get("status")

    print(f"Status: {status}, Progress: {result.get('percentage')}%, Queue: {result.get('waitNumber')}")

    if status in ("Success", "Failed"):
        break

    time.sleep(3)  # Poll every 3 seconds

if status == "Success":
    print("Result URL:", result["output"]["resultUrl"])
else:
    print("Task ended with status:", status)

Node.js (axios)

const axios = require('axios');

const BASE_URL = 'https://api.ideal.house';
const API_KEY  = 'your_api_key_here';

async function pollResult(taskId) {
  const headers = { 'APIKEY': API_KEY };

  while (true) {
    const response = await axios.get(
      `${BASE_URL}/api/v1/smartReplace/result`,
      {
        headers,
        params: { taskId }
      }
    );

    const result = response.data.data;
    const { status, percentage, waitNumber } = result;

    console.log(`Status: ${status} | Progress: ${percentage}% | Queue: ${waitNumber}`);

    if (['Success', 'Failed'].includes(status)) {
      if (status === 'Success') {
        console.log('Result URL:', result.output.resultUrl);
        console.log('Size:', result.output.width, 'x', result.output.height);
      } else {
        console.log('Task ended with status:', status);
      }
      break;
    }

    // Wait 3 seconds before next poll
    await new Promise(resolve => setTimeout(resolve, 3000));
  }
}

pollResult(1234567890123456789n);

πŸ“€ Response

Success Response (Task Completed)

{
  "code": 0,
  "message": "success",
  "data": {
    "id": 1234567890123456789,
    "status": "Success",
    "waitNumber": 0,
    "percentage": 100,
    "input": {
      "imageUrl": "https://example.com/room.jpg",
      "prompt": "a modern velvet sofa in dark blue",
      "maskUrl": "https://example.com/mask.png"
    },
    "output": {
      "resultUrl": "https://cdn.ideal.house/output/smart_replace_result.jpg",
      "width": 1024,
      "height": 1024
    }
  }
}

Response (Task Processing / In Queue)

{
  "code": 0,
  "message": "success",
  "data": {
    "id": 1234567890123456789,
    "status": "Processing",
    "waitNumber": 1,
    "percentage": 45,
    "input": {
      "imageUrl": "https://example.com/room.jpg",
      "prompt": "a modern velvet sofa in dark blue",
      "maskUrl": "https://example.com/mask.png"
    },
    "output": null
  }
}

Response (Task Failed)

{
  "code": 0,
  "message": "success",
  "data": {
    "id": 1234567890123456789,
    "status": "Failed",
    "waitNumber": 0,
    "percentage": 0,
    "input": {
      "imageUrl": "https://example.com/room.jpg",
      "prompt": "a modern velvet sofa in dark blue",
      "maskUrl": "https://example.com/mask.png"
    },
    "output": null
  }
}

Response Fields

FieldTypeDescription
idlongTask unique identifier
statusstringCurrent task status (see Task Status)
waitNumberintegerNumber of tasks ahead in the queue (0 means currently processing)
percentageintegerTask completion percentage (0–100)
inputobjectThe original input parameters of the task
input.imageUrlstringSource image URL
input.promptstringText prompt describing the replacement content
input.maskUrlstringMask image URL (if provided via maskUrl)
outputobjectGeneration result (only available when status is Success)
output.resultUrlstringURL to the smart-replaced result image
output.widthintegerOutput width in pixels
output.heightintegerOutput height in pixels

πŸ“Š Task Status

StatusDescription
UnprocessedTask has been created but not yet started
ProcessingTask is currently being processed
SuccessTask completed successfully β€” output is available
FailedTask failed due to an error

πŸ’‘ Polling Recommendation: Poll the result endpoint every 3–5 seconds. Avoid polling too frequently to prevent rate limiting.


❌ Error Responses

All error responses share the same JSON structure:

{
  "code": 5002,
  "message": "Invalid API Key",
  "data": null
}

Error Code Reference

CodeNameDescriptionSuggested Action
1001FAILEDRequest failed (generic error)Check the message field for specific error details
1003INTERNAL_ERRORInternal server errorRetry after a short delay; contact support if it persists
1011PARAM_ERRORRequest parameter error β€” e.g., prompt or mask missingEnsure both prompt and at least one mask field are provided
5002API_KEY_INVALIDInvalid or missing API KeyEnsure the APIKEY header is present and the value is correct
9010SCAN_TEXT_ERRORText prompt failed content reviewModify the prompt to remove any sensitive or prohibited content
9038PROHIBITED_CONTENTGenerated output image contains prohibited contentAdjust prompt/style/inputs and retry
9051COINS_NOT_ENOUGHInsufficient coins / creditsTop up your account credits and retry

πŸ“„ For the complete list of common API error codes, refer to the Error Code Reference.


β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                                                         β”‚
β”‚  Prepare:                                               β”‚
β”‚    - Source image URL (imageUrl) [required]             β”‚
β”‚    - Prompt: describe the replacement content [required] β”‚
β”‚    - Mask image: black = replace, white = keep          β”‚
β”‚      β†’ Provide as maskUrl or maskBase64 [required]      β”‚
β”‚                                                         β”‚
β”‚  1. POST /api/v1/smartReplace/generate                  β”‚
β”‚     β†’ Receive taskId                                    β”‚
β”‚                                                         β”‚
β”‚  2. Wait 3–5 seconds                                    β”‚
β”‚                                                         β”‚
β”‚  3. GET /api/v1/smartReplace/result?taskId={taskId}     β”‚
β”‚     β†’ Check status field                               β”‚
β”‚                                                         β”‚
β”‚     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚     β”‚ status == "Unprocessed" or "Processing"       β”‚   β”‚
β”‚     β”‚   β†’ waitNumber: position in queue             β”‚   β”‚
β”‚     β”‚   β†’ percentage: current progress              β”‚   β”‚
β”‚     β”‚   β†’ Repeat step 2 & 3                         β”‚   β”‚
β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                         β”‚
β”‚     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚     β”‚ status == "Success"                           β”‚   β”‚
β”‚     β”‚   β†’ output.resultUrl: replaced result image   β”‚   β”‚
β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                         β”‚
β”‚     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚     β”‚ status == "Failed"                            β”‚   β”‚
β”‚     β”‚   β†’ Handle error accordingly                  β”‚   β”‚
β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Β© Ideal House AI β€” All rights reserved.