如何通过Magento2 API获取分类下带详情的产品列表
Hey there! I get it—you're building a native app, and when users tap on a category, you want to show a full product list with names, images, prices, etc. But right now, the endpoint http://www.dexample.com/index.php/rest/V1/categories/1680/products only gives you sku, position, and category_id. Let's sort this out with a few straightforward solutions:
1. Use REST API's searchCriteria to Specify Required Fields
Magento's REST API lets you filter and select exactly the fields you need. Instead of using the category-specific product endpoint, use the products search endpoint and filter by category ID, then list the fields you want to retrieve.
Here's an example request URL:
http://www.dexample.com/index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=1680&searchCriteria[fields]=items[sku,name,price,small_image,thumbnail]
Breakdown of the parameters:
searchCriteria[filter_groups][0][filters][0][field]=category_id: Filters products to only those in category 1680searchCriteria[filter_groups][0][filters][0][value]=1680: The category ID you're targetingsearchCriteria[fields]=items[sku,name,price,small_image,thumbnail]: Explicitly lists the product fields you want to fetch (add/remove fields as needed)
2. Switch to Magento's GraphQL API (Recommended for Flexibility)
If your Magento instance supports GraphQL (Magento 2.3+), this is a much cleaner approach. GraphQL lets you request exactly the data you need, no more, no less.
Here's a sample query you can send to the GraphQL endpoint (usually /graphql):
{ category(id: 1680) { products(pageSize: 20) { items { sku name price_range { minimum_price { final_price { value currency } } } small_image { url } thumbnail { url } } } } }
This will return all the product details you need in one request, and you can easily add more fields (like description, stock status) by expanding the query.
3. Extend the Default REST API Response (For Custom Needs)
If you need to stick with the original /categories/{categoryId}/products endpoint, you can create a small Magento module to extend its response. Here's a quick overview:
- Create a plugin for the
Magento\Catalog\Model\Category\Product::getProducts()method - Modify the result set to include additional product attributes (name, image, price, etc.)
- Make sure to declare the attributes as "visible" in your module's
extension_attributes.xmlif needed
Why the Default Response is Minimal
Just to clarify: The default /categories/{categoryId}/products endpoint is designed to return category-product association data, not full product details. That's why you only get sku, position, and category_id out of the box. Using the search endpoint or GraphQL is the intended way to fetch full product info filtered by category.
内容的提问来源于stack exchange,提问作者Parth Dhorda

