Image Search

Prev Next

This guide covers how to integrate XGen's Image Search capability, which allows users to upload an image and receive ranked product results based solely on visual similarity — no text query required.


Overview

Image Search uses a dedicated endpoint that accepts a raw image file and returns a ranked list of products matched against the visual content of the image. The response shape is identical to the standard search response with the addition of a score field per product indicating the confidence of the visual match.

This feature is well-suited for:

  • "Shop the look" or "find similar" UI patterns
  • Camera-based search on mobile
  • Visual discovery experiences where the user cannot easily articulate a text query

Endpoint

POST https://prompt.xgen.dev/customers/{customerId}/users/{userId}

Authentication

Authentication follows the same API Key pattern used across XGen's services. Refer to your XGen onboarding documentation or contact XGen support for credentials and token generation details.

Path Parameters

Parameter Required Description
customerId Yes Your XGen customer ID
userId Yes The ID of the end user making the request

Request Format

Important: This endpoint accepts multipart/form-data, not application/json. All fields must be sent as form data parts.

Body Fields

Field Required Type Description
image Yes file The image file to search with. See constraints below for supported formats.
collection No string The product collection to search within.

Image Constraints

Constraint Limit
File formats image/jpeg, image/jpg, image/png only
Max file size 5 MB

Requests that violate these constraints will receive the following errors respectively:

  • Invalid image format — unsupported file type supplied
  • File size exceeds the limit (1 MB) — image exceeds the 1 MB size cap

Response

The response structure mirrors the standard XGen search response. Each product in the products_list array includes an additional score field representing the visual similarity confidence as a float.

Product Object (truncated example)

{
  "prod_code": "123",
  "score": 0.5189
}

Integration Examples

Frontend (Browser)

The following example demonstrates a minimal browser implementation using the FormData API to construct and send a multipart/form-data POST request.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Image Search</title>
  </head>
  <body>
    <h2>Search by Image</h2>
    <form id="uploadForm" enctype="multipart/form-data">
      <input type="file" name="image" id="imageInput" accept="image/jpeg,image/jpg,image/png" />
      <label for="localeInput">Locale:</label>
      <input type="text" id="localeInput" name="locale" placeholder="e.g. en-us" /><br /><br />
      <button type="button" id="uploadButton">Search</button>
    </form>

    <div id="results"></div>

    <script>
      const CUSTOMER_ID = "<your_customer_id>";
      const USER_ID = "<your_user_id>";
      const ACCESS_TOKEN = "<your_access_token>";

      document.getElementById("uploadButton").addEventListener("click", async () => {
        const imageFile = document.getElementById("imageInput").files[0];
        const locale = document.getElementById("localeInput").value;

        if (!imageFile) {
          alert("Please select an image.");
          return;
        }

        const formData = new FormData();
        formData.append("image", imageFile);
        if (locale) formData.append("locale", locale);

        try {
          const response = await fetch(
            `/image/customers/${CUSTOMER_ID}/users/${USER_ID}`,
            {
              method: "POST",
              headers: {
                access_token: ACCESS_TOKEN,
              },
              body: formData,
            }
          );

          const data = await response.json();

          if (response.ok) {
            document.getElementById("results").innerText =
              JSON.stringify(data, null, 2);
          } else {
            document.getElementById("results").innerText =
              `Error: ${data.error}`;
          }
        } catch (error) {
          console.error("Error:", error);
          document.getElementById("results").innerText =
            "An error occurred while uploading the image.";
        }
      });
    </script>
  </body>
</html>

Key implementation notes:

  • Use FormData to construct the request body — do not set Content-Type manually. The browser will automatically set the correct multipart/form-data boundary when FormData is used as the fetch body.
  • Validate the file type and size client-side before sending to avoid unnecessary failed requests (supported formats: image/jpeg, image/jpg, image/png; max size: 5 MB).

Error Reference

Error Message Cause Resolution
Invalid image format File MIME type is not image/jpeg, image/jpg, or image/png Validate and convert the image format before uploading
File size exceeds the limit (5 MB) Image binary exceeds 5 MB Compress or resize the image before uploading
401 Unauthorized Missing or invalid access_token or credentials Verify authentication credentials
400 Bad Request Malformed request or missing required image field Ensure the request uses multipart/form-data and includes the image part

Additional References