Skip to content

Getting Started

In this section, we'll walk through each step of implementing the Bodygram Headless SDK in your application.

Before you start

Before you start, make sure you have:

  • Client Key: Your unique client key. Contact Bodygram to get your client key.
  • brandId: Your unique brand ID. Contact Bodygram to get your brand ID.
  • garmentSku: The SKU of the garment you want to get size recommendations for. Contact Bodygram to get your garment SKU.
  • Familiarity with HTML and JavaScript.

Get the measurement and estimation token

In this section, we'll create a page that uses the Bodygram SDK to get the measurement and estimation token.

Step 1: Create a new HTML page

Create a new HTML page and add the following code:

index.html
<html>
    <head>
        <title>Bodygram Headless SDK</title>
    </head>
    <body>
        <h1>Bodygram Headless SDK</h1>
        <button id="get-estimation-token">Get Estimation Token</button>

        <script>
          async function getEstimationToken() {
            console.log("Getting estimation token");
          }

          document.getElementById("get-estimation-token").addEventListener("click", getEstimationToken);
        </script>
    </body>
</html>

This will create a button that when clicked, will call the getEstimationToken function. In the next step, we'll add the SDK to the page and initialize it.

Step 2: Add the SDK to the page

You need to add the script available at https://headless.body2fit.bodygram.com/sdk.umd.js to the page.

index.html
<html>
    <head>
        <title>Bodygram Headless SDK</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK</h1>
        <button id="get-estimation-token">Get Estimation Token</button>

        <script>
          async function getEstimationToken() {
            // If it setup correctly, you should see the BodygramSDK object in the console.
            console.log("Bodygram SDK", BodygramSDK);
          }

          document.getElementById("get-estimation-token").addEventListener("click", getEstimationToken);
        </script>
    </body>
</html>

In this step, we've added the SDK to the page. If everything is set up correctly, you should see the BodygramSDK object in the console when you click the button. In the next step, we'll learn how to initialize the SDK.

Step 3: Initialize the SDK

To initialize the SDK, you need to pass the clientKey and locale to BodygramSDK constructor. The SDK will use the locale to determine the language of the scan page UI. Locales supported by BodygramSDK's scan page

index.html
<html>
    <head>
        <title>Bodygram Headless SDK</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK</h1>
        <button id="get-estimation-token">Get Estimation Token</button>

        <script>
          async function getEstimationToken() {
            const sdk = new BodygramSDK({
              // Replace with your client key
              clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
              locale: "en"
            });

            // If everything is set up correctly, you should see the BodygramSDK object in the console.
            console.log("Bodygram SDK", sdk);
          }

          document.getElementById("get-estimation-token").addEventListener("click", getEstimationToken);
        </script>
    </body>
</html>

Note

Make sure to replace the <REPLACE_WITH_YOUR_CLIENT_KEY> with your client key. If you don't have a client key, you can get one by contacting Bodygram.

In this step, we've initialized the SDK. In the next step, we'll learn how to open the scan page.

Step 4: Scan the user's body

You can skip this step if you want to use your own UI for the scan page. If you want to use the photo-based estimation token and bodygram's default scan UI, you can open the scan page by calling the scan method.

index.html
<html>
    <head>
        <title>Bodygram Headless SDK</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK</h1>
        <button id="get-estimation-token">Get Estimation Token</button>

        <script>
          async function getEstimationToken() {
            const sdk = new BodygramSDK({
              // Replace with your client key
              clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
              locale: "en"
            });

            /**
             * This will open the scan UI in an iframe.
             * This returns the front and side images of the user.
             */
            const { front, side } = await sdk.scan();

            console.log("Front image", front);
            console.log("Side image", side);
          }

          document.getElementById("get-estimation-token").addEventListener("click", getEstimationToken);
        </script>
    </body>
</html>

iOS Audio Guidance

On iOS devices, audio guidance during the scan process may be missing due to browser restrictions that require a user gesture to enable audio playback. To ensure users can hear the audio instructions, you can detect the device type and set scanShouldIncludeOverlay: true in the SDK initialization only for iOS devices. This adds a tap overlay before the scan UI, prompting the user for a gesture and enabling audio guidance.

Example device check:

const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
const sdk = new BodygramSDK({
  clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
  locale: "en",
  scanShouldIncludeOverlay: isIOS, // Only add overlay for iOS
});

Note

The front and side images returned by sdk.scan() are base64-encoded strings representing the captured photos. You can use these strings to display the images or send them to your server. To display a base64 image on a webpage, you can set it as the src attribute of an <img> tag like this: <img src="BASE_64_IMAGE_STRING_RETURNED_BY_SDK">. Learn more about base64 image usage on MDN or see examples on Stack Overflow.

{
    "front": "data:image/jpeg;base64,...",
    "side": "data:image/jpeg;base64,..."
}

{
    "code": "SCAN_FAILED",
    "message": "BodygramSDK: Unable to scan user."
}
This could be due to user closing the scan UI or camera permission is not granted.

Step 5: Get the measurement and estimation token

Get photo-based estimation token

In this example, we assume you are using BodygramSDK's default scan UI.

index.html
<html>
    <head>
        <title>Bodygram Headless SDK</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK</h1>
        <form id="get-estimation-token-form">
            <input type="text" id="age" name="age" placeholder="Age">
            <select id="gender" name="gender">
                <option value="male">Male</option>
                <option value="female">Female</option>
            </select>
            <input type="text" id="height" name="height" placeholder="Height">
            <input type="text" id="weight" name="weight" placeholder="Weight">
            <button type="submit">Get Estimation Token</button>
            <pre id="estimation-token-result"></pre>
        </form>

        <script>
          async function getEstimationToken(event) {
            event.preventDefault();
            const sdk = new BodygramSDK({
              // Replace with your client key
              clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
              locale: "en",
            });

            /**
             * This will open the scan UI in an iframe.
             * This returns the front and side images of the user.
             */
            const { front, side } = await sdk.scan();

            console.log("Front image", front);
            console.log("Side image", side);

            const formData = new FormData(event.target);
            const age = formData.get("age");
            const gender = formData.get("gender");
            const height = formData.get("height");
            const weight = formData.get("weight");

            const photoEstimation = await sdk.getBody2FitPhotoEstimation({
              front,
              side,
              age,
              gender,
              height,
              weight
            });

            document.getElementById("estimation-token-result").textContent = 
              JSON.stringify(photoEstimation, null, 2);

            // Save the estimation token for future use
            const photoToken = photoEstimation.estimations.estimationToken.token;
            localStorage.setItem('bodygram-photo-token', photoToken);
            // Or save to global store: globalPhotoToken = photoToken;

            // Access and save measurements
            const photoMeasurements = photoEstimation.estimations.measurements;
            localStorage.setItem(
              'bodygram-photo-measurements', 
              JSON.stringify(photoMeasurements)
            );
            // Or save to global store: globalPhotoMeasurements = photoMeasurements;
          }

          document.getElementById("get-estimation-token-form").addEventListener("submit", getEstimationToken);
        </script>
    </body>
</html>

The above code does the following: 1. Collects user data (age, gender, height, weight) through a form 2. Calls the SDK's photo estimation API with the collected data and photos 3. Stores the resulting estimation token and measurements in local storage. You can also save them to a global variable if you want to use them in other parts of your application.

{
    "estimations": {
        "estimationToken": {
            "token": "ESTIMATION_TOKEN"
        },
        "measurements": [
          {
            "estimationType": "ESTIMATION_TYPE",
            "value": "ESTIMATION_VALUE",
            "unit": "ESTIMATION_UNIT"
          },
          // ... more measurements
        ],
        "avatarData": null,
        "input": {
          "preferredSystemOfMeasurement": "METRIC",
          "tightness": 0,
          "inputType": "CAMERA_FLOW"
        }
    }
}

See all the measurements returned by the SDK in the SDK reference.

{
    "error": {
        "code": "INVALID_CLIENT_KEY",
        "message": "Provided client key does not exist"
    }
}

This could be due to invalid client key or other issues. See SDK's SDK reference for more details.

Get stat-based estimation token

index.html
<html>
    <head>
        <title>Bodygram Headless SDK</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK</h1>
        <form id="get-estimation-token-form">
            <input type="text" id="age" name="age" placeholder="Age">
            <select id="gender" name="gender">
                <option value="male">Male</option>
                <option value="female">Female</option>
            </select>
            <input type="text" id="height" name="height" placeholder="Height">
            <input type="text" id="weight" name="weight" placeholder="Weight">
            <button type="submit">Get Estimation Token</button>
            <pre id="estimation-token-result"></pre>
        </form>

        <script>
          async function getEstimationToken(event) {
            event.preventDefault();
            const sdk = new BodygramSDK({
              // Replace with your client key
              clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
              locale: "en"
            });

            const formData = new FormData(event.target);
            const age = formData.get("age");
            const gender = formData.get("gender");
            const height = formData.get("height");
            const weight = formData.get("weight");

            const statsEstimation = await sdk.getBody2FitStatsEstimation({
              age,
              gender,
              height,
              weight
            });

            document.getElementById("estimation-token-result").textContent = 
              JSON.stringify(statsEstimation, null, 2);

            // Save the estimation token for future use
            const statsToken = statsEstimation.estimations.estimationToken.token;
            localStorage.setItem('bodygram-stats-token', statsToken);
            // Or save to global store: globalStatsToken = statsToken;

            // Access and save measurements
            const statsMeasurements = statsEstimation.estimations.measurements;
            localStorage.setItem('bodygram-stats-measurements', JSON.stringify(statsMeasurements));
            // Or save to global store: globalStatsMeasurements = statsMeasurements;
          }

          document.getElementById("get-estimation-token-form").addEventListener("submit", getEstimationToken);
        </script>
    </body>
</html>
{
    "estimations": {
        "estimationToken": {
            "token": "ESTIMATION_TOKEN"
        },
        "measurements": [
          {
            "estimationType": "ESTIMATION_TYPE",
            "value": "ESTIMATION_VALUE",
            "unit": "ESTIMATION_UNIT"
          },
          // ... more measurements
        ],
        "avatarData": null,
        "input": {
          "preferredSystemOfMeasurement": "METRIC",
          "tightness": 0,
          "inputType": "MANUAL_STATS"
        }
    }
}

See all the measurements returned by the SDK in the SDK reference.

{
    "error": {
        "code": "INVALID_CLIENT_KEY",
        "message": "Provided client key does not exist"
    }
}

This could be due to invalid client key or other issues. See SDK's SDK reference for more details.

Congratulations! You've successfully created a page that uses the Bodygram SDK to get body measurements and estimation token. You can store the token and use it in other parts of your application to get the body measurements.

In the next section, we'll learn how to use the estimation token to get the body measurements.

Use the estimation token to get the body measurements

So far, we've learned how to get the estimation token and measurements. Now, we'll learn how to use the estimation token to get the body measurements.

The token estimation API is designed to provide a seamless experience for returning users. Instead of requiring users to repeat the entire photo scan or stats estimation process every time they need their measurements, developers can use the previously saved estimation token to retrieve the same measurement data. This eliminates friction in the user journey and improves the overall experience.

In this example, we'll use the estimation token to get the body measurements and display them on the page.

show-measurements-using-estimation-token.html
<html>
    <head>
        <title>Bodygram Headless SDK - Show measurements</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK - Show measurements</h1>
        <h2>Measurements</h2>
        <div id="measurements">Loading...</div>
      </body>

      <script>
        async function getTokenEstimation() {
        const sdk = new BodygramSDK({
          clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
          locale: "en",
        });

        const tokenEstimation = await sdk.getBody2FitTokenEstimation({
          // Replace with your estimation token, that you got from the previous step.
          estimationToken: "<REPLACE_WITH_YOUR_ESTIMATION_TOKEN>"
        });

          const measurements = tokenEstimation.estimations.measurements;
          document.getElementById("measurements").innerHTML = measurements
            .map(m => (
              `<p>${m.estimationType}: ${m.value} ${m.unit}</p>`
            ))
            .join("");
        }

        getTokenEstimation();
      </script>
</html>

See all the measurements returned by the SDK in the SDK reference.

{
    "estimations": {
        "estimationToken": {
            "token": "ESTIMATION_TOKEN"
        },
        "measurements": [
          {
            "estimationType": "ESTIMATION_TYPE",
            "value": "ESTIMATION_VALUE",
            "unit": "ESTIMATION_UNIT"
          },
          // ... more measurements
        ],
        "avatarData": null,
        "input": {
          "preferredSystemOfMeasurement": "METRIC",
          "tightness": 0,
          "inputType": "CAMERA_FLOW" # or "MANUAL_STATS" if you used stats-based estimation token
        }
    }
}

This is same as the response you get from the photo estimation or stat estimation API.

{
    "error": {
        "code": "INVALID_ESTIMATION_TOKEN",
        "message": "Provided estimation token is not a valid format."
    }
}

If the estimation token is not valid, you can try to get the estimation token again.

Use the estimation token to get the size recommendation

We assume you have already obtained the estimation token and measurements. You also need the product information like brandId and garmentSku.

show-size-recommendation-using-estimation-token.html
<html>
    <head>
        <title>Bodygram Headless SDK - Show size recommendation</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK - Show size recommendation</h1>
        <h2>Size recommendation</h2>
        <div id="size-recommendation">Loading...</div>
      </body>

      <script>
        async function getTokenEstimation() {
          const sdk = new BodygramSDK({
            clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
            locale: "en",
          });

          const sizeRecommendations = await sdk.getBody2FitSizeRecommendation({
              estimationToken: "<REPLACE_WITH_YOUR_ESTIMATION_TOKEN>",
              productInfo: [
                {
                  brandId: "<REPLACE_WITH_YOUR_BRAND_ID>",
                  garmentSku: "<REPLACE_WITH_YOUR_GARMENT_SKU>"
                },
                // ... more product info
              ]
            });

            document.getElementById("size-recommendation").innerHTML = JSON.stringify(sizeRecommendations, null, 2);
        }

        getTokenEstimation();
      </script>
</html>

In this example, we've used the estimation token to get the size recommendation. You can pass an array of product info to the getBody2FitSizeRecommendation API. It returns the size recommendation for each product info in the array in the same order.

[
  {
    "recommendation": {
        "recommendedSize": "M" // Product 1 size recommendation
    }
  },
  {
    "recommendation": {
        "recommendedSize": "L" // Product 2 size recommendation
    }
  }
  // ... more product info
]
{
    "error": {
        "__error": {},
        "code": "INVALID_ESTIMATION_TOKEN",
        "message": "Invalid estimation token."
    }
}

If the estimation token is not valid, you can try to get the estimation token again. Note this is an example error response, you can get different error codes and messages depending on the issue.

Use the estimation token to get the size fitting

We assume you have already obtained the estimation token and measurements. You also need the product information like brandId and garmentSku.

show-size-fitting-using-estimation-token.html
<html>
    <head>
        <title>Bodygram Headless SDK - Show size fitting</title>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
    </head>
    <body>
        <h1>Bodygram Headless SDK - Show size fitting</h1>
        <h2>Size fitting</h2>
        <div id="size-fitting">Loading...</div>
      </body>

      <script>
        async function getTokenEstimation() {
          const sdk = new BodygramSDK({
            clientKey: "<REPLACE_WITH_YOUR_CLIENT_KEY>",
            locale: "en",
          });

          const sizeFitting = await sdk.getBody2FitSizeFitting({
              estimationToken: "<REPLACE_WITH_YOUR_ESTIMATION_TOKEN>",
              productInfo: [
                {
                  brandId: "<REPLACE_WITH_YOUR_BRAND_ID>",
                  garmentSku: "<REPLACE_WITH_YOUR_GARMENT_SKU>"
                },
                // ... more product info
              ]
            });

            document.getElementById("size-fitting").innerHTML = JSON.stringify(sizeFitting, null, 2);
        }

        getTokenEstimation();
      </script>
</html>

In this example, we've used the estimation token to get the size fitting. You can pass an array of product info to the getBody2FitSizeFitting API. It returns the size fitting for each product info in the array in the same order.

[
  {
    "result": {
      "estimationToken": {
        "token": "ESTIMATION_TOKEN"
      },
      "sizes": [
        {
          "size": {
            "index": 0,
            "name": "0"
          },
          "recommendationRank": 9,
          "fittingPoints": [
            {
              "fittingPoint": "ANKLE_DRESS_LENGTH",
              "tightness": 0
            },
            // ... more fitting points
          ],
          "tightness": 0,
          "neutralRecommendationRank": 9
        },
        {
          "size": {
            "index": 1,
            "name": "2"
          },
          "recommendationRank": 8,
          "fittingPoints": [
            {
              "fittingPoint": "ANKLE_DRESS_LENGTH",
              "tightness": 0
            },
            // ... more fitting points
          ],
          "tightness": 0,
          "neutralRecommendationRank": 8
        },
        // ... more sizes
      ],
      "sizeGroups": []
    }
  },
  // ... more product info
]
{
    "error": {
        "__error": {},
        "code": "INVALID_ESTIMATION_TOKEN",
        "message": "Invalid estimation token."
    }
}

If the estimation token is not valid, you can try to get the estimation token again. Note this is an example error response, you can get different error codes and messages depending on the issue.