在Magento 2中,您可以调用API轻松获取所有产品。多个 REST 调用会返回数千甚至数百个参数。解析所有这些数据有时可能很麻烦。

此外,移动应用程序开发人员可能会发现处理不合理的请求需要带宽。为了处理这些问题,为 REST 请求提供了基于查询参数的语法,该语法返回部分响应。

<host>/rest/<store_code>可以替换为您的网站。

查询searchCriteria参数使您能够搜索集合中的多个对象。fields 查询参数可以与 结合使用来searchCriteria限制输出。本文档中所有示例中字段前面的问号 (?) 将替换为与号 (&)。

获取所有产品、订单、类别

  • 获取所有产品
  • 获取具有类别的产品
  • 获取所有订单
  • 获取类别

获取所有产品

以下查询仅返回category_gear 属性包含值 86 的产品项目的 sku 和名称参数。

GET <host>/rest/<store_code>/V1/products/?searchCriteria[filter_groups][0][filters][0][field]=category_gear&searchCriteria[filter_groups][0][filters][0][value]=86&searchCriteria[filter_groups][0][filters][0][condition_type]=finset&fields=items[sku,name]

{
"items":
  {
    "sku": "24-MG04"
    "name": "Aim Analog Watch"
  }
  {
    "sku": "24-MG01"
    "name": "Endurance Watch"
  }
  {
    "sku": "24-MG03"
    "name": "Summit Watch"
  }
  {
    "sku": "24-MG05"
    "name": "Cruise Dual Analog Watch"
  }
  {
    "sku": "24-MG02"
    "name": "Dash Digital Watch"
  }
  {
    "sku": "24-WG09"
    "name": "Luma Analog Watch"
  }
  {
    "sku": "24-WG01"
    "name": "Bolo Sport Watch"
  }
  {
    "sku": "24-WG03"
      "name": "Clamber Watch"
  }
  {
    "sku": "24-WG02"
    "name": "Didi Sport Watch"
  }
}

每页限制 20 项:/V1/products?searchCriteria[pageSize]=20

获取具有类别的产品

GET <host>/rest/<store_code>/V1/products/MT12?fields=name,sku,extension_attributes[category_links,stock_item[item_id,qty]]

{
  "sku": "MT12"
  "name": "Cassius Sparring Tank"
  "extension_attributes": {
    "category_links": {
      "position": 1
      "category_id": "18"
    }
    "stock_item": {
      "item_id": 732
      "qty": 0
      }
  }
}

上面的示例返回以下结果:

  • 产品sku的和name
  • 整个category_links物体。这是定义在extension_attributes
  • 对象stock_itemitem_id字段qty。这些也定义在extension_attributes

获取所有订单

GET <host>/rest/<store_code>/V1/orders/2?fields=billing_address,customer_firstname,customer_lastname

{
  "customer_firstname": "Veronica"
  "customer_lastname": "Costello"
  "billing_address": {
    "address_type": "billing"
    "city": "Calder"
    "country_id": "US"
    "customer_address_id": 1
    "email": "roni_cost@example.com"
    "entity_id": 4
    "firstname": "Veronica"
    "lastname": "Costello"
    "parent_id": 2
    "postcode": "49628-7978"
    "region": "Michigan"
    "region_code": "MI"
    "region_id": 33
    "street": "6146 Honey Bluff Parkway"
    "telephone": "(555) 229-3326"
    }
  }

上面的示例返回客户的名字和姓氏以及billing_address指定订单的整个对象。

当您希望返回对象的所有内容时,请勿在对象名称后添加括号[]。

获取类别

POST <host>/rest/<store_code>/V1/categories?fields=id,parent_id,name

Payload

{
  "category": {
    "name": "New Category",
    "is_active": true
  }
}

Response

{
  "id": 43,
  "parent_id": 2,
  "name": "New Category"
}

上述 POST 操作和有效负载用于创建名为 的目录类别New Category。这里仅返回idparent_id和属性。name