Creating Recommendations Service and Getting Recommendations Using REST API

On this page, you will find guidelines for fetching recommendations from a REST API. It covers the following content:

  • Creating a new Recommendations Service through the Infinity UI.

  • The Recommendations Service API request and response format, including both mandatory and optional parameters.

  • A simplified way to fetch recommendations using JavaScript from a web page.

Creating a Recommendations Service

The Recommendations Service defines a strategy of recommending items.

It includes selecting a recommendations algorithm that best fits the business objective and entering the appropriate filter criteria. Optionally, you can also select "fallback items," which will be returned if the model does not return enough recommended items for the given filter criteria.

Tip: See Recommendation Strategies for further information about the different available models.

To create a Recommendations Service:

  1. On the Recommendations home screen, scroll to the Recommendations Services section and click the Create Service button.
  2. Define the service Name and Description.
  3. Select a Recommendations Model from the drop down.
  4. Define Item Filters .
  5. Select Exclude recent history if you want to avoid users seeing items with which they recently interacted with.
  6. Check the Apply Localized Recommendations checkbox to generate locale/geography-based recommendations dynamically

    Note: Localized Recommendations require the Inventory file to have items for different locales. Ensure that your system detects and sends the user's locale with the recommendation request. If you select this option, fallback items will be disabled.

    Example:

    Service Creation Page

  7. Click Save.
  8. Once you save the service configuration, you will be redirected to the "Recommendations Service details" page. On this page, you can copy the URL String for your service. You will need this URL for the next steps.

    Getting Service URL

  9. You can display recommendations on your web page using the Recommendations widget in the Web Personalization Canvas. Learn how to setup recommendations using the Web Personalization Canvas.
  10. Alternatively, you can add recommendations directly on your web page by adding custom code to your website as shown in the sections below.

Recommendations Service REST API

The API retrieves personalized recommendations for users based on historical data and co-occurrence.

Note: The steps outlined below require basic JavaScript knowledge to understand and implement it on your site pages.

Request method and URL

  • Method: POST
  • URL: Copied from Recommendations Services page.

Request format

To fetch recommendations, send a JSON object in the body of your POST request with the following parameters:

  • count (mandatory): An integer between 1 and 50 indicating the number of recommendations to return.
  • history (mandatory): An array of event objects that represent the user's interaction history. Each event object must contain:
    • id: The ID of the product involved in the event.
    • date: Unix datetime stamp in milliseconds for when the event occurred.
    • type: Type of event, which can be either "view" or "purchase".
  • productIdsList (optional): An array of product IDs for which to generate co-occurrence based recommendations. If provided, the array must contain at least one element; otherwise, it can be omitted from the request.
  • locale (optional): A string representing the user's locale, used to filter recommendations and show only those which match the locale in their inventory attribute.

Example:

{ "count": 50, "history": [ { "id": "SKU_1", "date": 1689006365000, "type": "view" }, { "id": "SKU_2", "date": 1689006424000, "type": "purchase" } ], "productIdsList": ["SKU_4", "SKU_5", "SKU_6"], "locale": "en_US" }

The API responds with a JSON object containing a field "recommendations", which is an array of recommendation objects. Each object contains all inventory attributes for a recommended item, along with formatted versions of some attributes.

Example:

{ "recommendations": [ { "Product ID": "SKU1", "Name": "Product Name 1", "Price": 1159.99, "Formatted Price": "$1,159.99", ... }, { "Product ID": "SKU2", "Name": "Product Name 2", "Price": 2159.99, "Formatted Price": "$2,159.99", ... } ] }

If there are no recommendations generated for the selected recommendations strategy, an empty JSON response will be returned.

Expected Response Codes

Here is the list of various response codes that you can expect to see:

  • 200 OK: The request was successful, and recommendations are returned in the response.
  • 400 Bad Request: The request body is malformed. See the error message for details.
  • 404 Not Found: The requested service ID is not found, or the URL is invalid.
  • 500 Internal Server Error: Indicates an internal server issue.
  • 503 Server Unavailable: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance.

Fetching recommendations on a web page using the ORA.recommender.getRecommendations method

Note: To fetch recommendations, you must have the CX tag enabled and configured Recommendations module present on the web page. Recommendations module version should be 5.0.1. If you do not see the ORA.recommender.getRecommendations method, check How to upgrade Recommendations module version.

The ORA.recommender.getRecommendations method is designed to asynchronously fetch personalized product recommendations from a REST API endpoint, ensuring flexibility and customization for various use cases.

The method accepts the following arguments:

  1. serviceURL (String, Mandatory): The URL of the REST API service from which to fetch recommendations. This argument specifies the endpoint to be queried for retrieving personalized product recommendations.

  2. count (Integer, Mandatory): A number between 1 and 50 indicating the number of recommendations to return. The greater the number, the longer the API will take to fetch the recommendations.
  3. options (Object, Optional): An object containing additional parameters to customize the recommendations fetch request. The options object can include the following properties:

    • productIDs (Array of String values | Promise that resolves to an Array of String values, Optional): A list of product IDs for which recommendations are sought. This can be directly provided as an array of strings or indirectly via a promise that resolves to such an array, allowing for dynamic scenarios where product IDs are determined asynchronously.

    • locale (String, Optional): A locale identifier in the format of a string, used to tailor the recommendations to specific regional or cultural preferences. Providing a locale helps ensure that the recommendations are relevant to the user's geographical or linguistic context.

Return Value:

  • Promise (Object): The method returns a Promise that resolves with the recommendations fetched from the specified REST API service. The resolved object contains the recommended products and any additional information provided by the API, enabling the integration of personalized content into web applications.

The below examples cover various scenarios, including fetching without product IDs, with a specific list of product IDs, using an asynchronous method to obtain product IDs, and specifying a locale. Replace displayRecommendations(data.recommendations) with your own implementation of adding recommendations to the web page.

Example: Basic Fetch without any history and product IDs

To fetch recommendations without specifying product IDs or a locale, use the following code:

ORA.recommender.getRecommendations('YourServiceURL',5)
  .then(data => {
    displayRecommendations(data.recommendations);
  })
  .catch(error => console.error('Fetching recommendations failed:', error)); 

Example: Fetching with predefined product IDs

If you have a list of product IDs, you can fetch recommendations as follows:

const arrayOfProductIDs = ['SKU_1', 'SKU_2']; // Example product IDs
ORA.recommender.getRecommendations('YourServiceURL', 5, { productIDs: arrayOfProductIDs })
    .then(data => {
    displayRecommendations(data.recommendations);
    })
    .catch(error => console.error('Fetching recommendations failed:', error));

Example: Getting product IDs asynchronously with getProductIDs or setProductIDs methods

If product IDs are collected asynchronously in another part of the code

ORA.recommender.getRecommendations('YourServiceURL', 5, { productIDs: ORA.recommender.getProductIDs() })
    .then(data => {
        displayRecommendations(data.recommendations);
    })
    .catch(error => console.error('Fetching recommendations failed:', error));

Example: Fetching localized Recommendations

If your service has "Apply Localized Recommendations" option enabled, you need to provide user's locale with the request

ORA.recommender.getRecommendations('YourServiceURL', 5, { locale: 'en_US' })
                .then(data => {
                  displayRecommendations(data.recommendations);
                })
                .catch(error => console.error('Fetching recommendations failed:', error));

Example: Displaying Recommendations on your web page

Here is the example of displayRecommendations function used above. It converts the recommendations into HTML elements and inserts them into your web page.

 function displayRecommendations(recommendations) {
    const container = document.getElementById('recommendationsContainer'); // Ensure you have a div with this ID in your HTML
    container.innerHTML = ''; // Clear previous recommendations

    recommendations.forEach(item => {
        const element = document.createElement('div');
        element.innerHTML = `<h3>${item['Name']}</h3><p>Price: ${item['Formatted Price']}</p>`;
        container.appendChild(element);
    });
}

Learn more

Adding Email Recommendations

Adding Recommendations to a Website Using Web Personalization