Getting Product Reviews and Ratings via Magento APIs
Hello Preeti,
Thank you for reaching out! I understand your need to retrieve product reviews and ratings using Magento’s SOAP APIs. While the core API documentation doesn’t explicitly list methods for this, we can achieve what you’re looking for by combining some existing resources.
Retrieving Product Reviews
To get the review information (ID, name, text, date), you’ll first need the product ID and then call the reviews.info method with that ID. Here’s an example:
$soap = new SoapClient('http://example.com/api/soap/?wsdl');
$sessionId = $soap->login('xxxxxxx', 'xxxxxxxx');
// Assume 123 is your desired product ID
$reviewInfo = $soap->call($sessionId, 'reviews.info', array(123));
// Print the review information
print_r($reviewInfo);
The reviews.info method returns an array of reviews for the specified product. Each entry in this array contains the following keys:
review_id: The unique ID of the review.created_at: The date and time when the review was created (in timestamp format).title: The title given to the review by the customer.detail: The actual text content of the review.
Retrieving Product Ratings
Unfortunately, Magento’s default APIs don’t provide a direct method for getting product ratings. However, we can work around this limitation using the following approach:
- Retrieve all reviews for the product using the code above.
- Calculate the average rating by summing up the
ratingfield of all reviews and dividing it by the total number of reviews.
Here’s an example function to calculate the average rating:
function getAverageRating($reviews, $totalReviews) {
if ($totalReviews == 0) return 0;
$sum = array_reduce($reviews, function($carry, $review) { return $carry + (int)$review['rating']; }, 0);
return $sum / $totalReviews;
}
You can use this in your script like so:
// Assuming you've already retrieved the reviews and stored them in $reviewInfo
$totalReviews = count($reviewInfo);
if ($totalReviews > 0) {
$averageRating = getAverageRating(array_column($reviewInfo, 'rating'), $totalReviews);
echo "Average rating: " . round($averageRating, 2);
} else {
echo "No reviews found.";
}
Conclusion
While Magento’s SOAP APIs don’t have a dedicated method for retrieving product ratings, you can achieve this by combining the reviews.info method with some custom logic. This approach allows you to retrieve both review information and calculated average ratings for any given product.
Don’t forget that working with APIs involves handling session IDs and network requests, so make sure your code is robust against failures and timeouts.
I hope this helps! Let me know if you have any other questions. You can always find more Magento-related resources on our blog at Laravel Company.
Best regards, [Your Name]