Skip to main content

Examples and Use Cases

This page provides practical examples of how to use the Recommendations API for different scenarios.

Product Detail Page (PDP) Recommendations

GET https://<PA_END_POINT>/3.0/recommendations?currentUrl=https://www.example.com/product/12345&refId=12345&expandProductDetails=true

Shopping Cart Recommendations

GET https://<PA_END_POINT>/3.0/recommendations?currentUrl=https://www.example.com/cart&productsInCart[0]=product123&productsInCart[1]=product456&expandProductDetails=true

Personalized Homepage Recommendations

GET https://<PA_END_POINT>/3.0/recommendations?currentUrl=https://www.example.com&customerId=customer123&expandProductDetails=true

Category/Search Page with Filtering

GET https://<PA_END_POINT>/3.0/recommendations?currentUrl=https://www.example.com/category/shoes&indexFilterValue=price:[50 TO 200] AND category:running&customerSegments[0]=premium_member&expandProductDetails=true

Best Practices

Caching Recommendations

For better performance, consider caching recommendations where appropriate:

// Cache recommendations with appropriate TTL based on page type
function getCachedRecommendations(params, cacheKey, cacheDuration) {
// Check if we have a valid cached version
const cachedData = localStorage.getItem(cacheKey);
if (cachedData) {
const parsed = JSON.parse(cachedData);

// Check if the cache is still valid
if (parsed.timestamp && (Date.now() - parsed.timestamp < cacheDuration)) {
console.log(`Using cached recommendations for ${cacheKey}`);
return Promise.resolve(parsed.data);
}
}

// No valid cache, fetch from API
return fetch(`https://<PA_END_POINT>/3.0/recommendations?${params.toString()}`, {
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Cache the result
localStorage.setItem(cacheKey, JSON.stringify({
timestamp: Date.now(),
data: data
}));

return data;
});
}

// Example usage
function getProductPageRecommendations(productId) {
const params = new URLSearchParams({
currentUrl: window.location.href,
refId: productId,
expandProductDetails: 'true'
});

// Cache PDP recommendations for 5 minutes (300000 ms)
return getCachedRecommendations(params, `pdp_recommendations_${productId}`, 300000);
}

Progressive Loading

Implement progressive loading for better user experience:

// Load recommendations asynchronously as sections scroll into view
function setupLazyLoadedRecommendations() {
// Set up intersection observer to load recommendations when in view
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const element = entry.target;
const sectionType = element.dataset.recommendationType;
const params = element.dataset.params ? JSON.parse(element.dataset.params) : {};

// Show loading state
element.innerHTML = '<div class="loading-spinner"></div>';

// Load recommendations based on section type
if (sectionType === 'pdp') {
const productId = params.productId;

// Set up parameters
const apiParams = new URLSearchParams({
currentUrl: window.location.href,
refId: productId,
expandProductDetails: 'true'
});

// Fetch recommendations
fetch(`https://<PA_END_POINT>/3.0/recommendations?${apiParams.toString()}`, {
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
renderRecommendationsToElement(element, data);
})
.catch(error => {
console.error('Error loading recommendations:', error);
element.innerHTML = '<p>Unable to load recommendations at this time.</p>';
});
}

// Once loaded, stop observing this element
observer.unobserve(element);
}
});
}, {
rootMargin: '100px 0px', // Load recommendations 100px before they come into view
threshold: 0.1
});

// Observe all recommendation containers
document.querySelectorAll('.recommendation-container[data-recommendation-type]').forEach(container => {
observer.observe(container);
});
}

function renderRecommendationsToElement(element, data) {
if (!data.recommendations?.route?.widgets || data.recommendations.route.widgets.length === 0) {
element.style.display = 'none';
return;
}

let html = '';

data.recommendations.route.widgets.forEach(widget => {
if (!widget.slots || widget.slots.length === 0) return;

html += `<h2>${widget.name}</h2>`;
html += '<div class="products-carousel">';

widget.slots.forEach(slot => {
if (slot.products && slot.products.length > 0) {
slot.products.forEach(product => {
html += `
<div class="product-card">
<img src="${product.images?.[0] || 'placeholder.jpg'}" alt="${product.name}" loading="lazy">
<h3>${product.name}</h3>
<p class="price">$${product.prices?.[0]?.price || 'N/A'}</p>
<button>View Product</button>
</div>
`;
});
}
});

html += '</div>';
});

element.innerHTML = html;

// Initialize carousel if needed
if (window.initProductCarousel) {
window.initProductCarousel(element.querySelector('.products-carousel'));
}
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', setupLazyLoadedRecommendations);

These examples demonstrate how to integrate the Recommendations API into various parts of your eCommerce website, from product detail pages to shopping carts and personalized homepages, along with best practices for performance optimization.