Magento产品的API

时间:2016-07-25 08:27:55

标签: php rest product magento2

我的商店有magento2,我想用REST API获取所有可配置/简单的产品及其子(变体)产品。我可以在单个REST API调用中获取所有产品,但它不能为我提供可配置产品的孩子。

我需要可配置的产品,如下所示:

{
    "id":1,
    "parent_id":1,
    "name":"myProduct",
    "is_active":true,
    .................
    "children_data":[

        {
            "id":1,
            "parent_id":1,
            "name":"myProduct",
            "is_active":true,
            .................
        },
        {
            "id":1,
            "parent_id":1,
            "name":"myProduct",
            "is_active":true,
            .................
        }               
    ]   
}

2 个答案:

答案 0 :(得分:4)

您需要使用以下REST API来获取子数据

  

GET / V1 / configurable-products / {sku} / children

回应:

[
  {
    "sku": "MH01-XS-Black",
    "name": "Chaz Kangeroo Hoodie-XS-Black",
    "attribute_set_id": 9,
    "price": 52,
    "status": 1,
    "type_id": "simple",
    "created_at": "2015-11-20 08:12:24",
    "updated_at": "2015-11-20 08:12:24",
    "weight": 1,
    "extension_attributes": [],
    "product_links": [],
    "tier_prices": [],
    "custom_attributes": [
      {
        "attribute_code": "required_options",
        "value": "0"
      },
      {
        "attribute_code": "has_options",
        "value": "0"
      },
      {
        "attribute_code": "tax_class_id",
        "value": "2"
      },
      {
        "attribute_code": "image",
        "value": "/m/h/mh01-black_main.jpg"
      },
      {
        "attribute_code": "category_ids",
        "value": [
          "2",
          "15",
          "36"
        ]
      },
      {
        "attribute_code": "size",
        "value": "167"
      },
      {
        "attribute_code": "color",
        "value": "49"
      },
      {
        "attribute_code": "small_image",
        "value": "/m/h/mh01-black_main.jpg"
      },
      {
        "attribute_code": "thumbnail",
        "value": "/m/h/mh01-black_main.jpg"
      },
      {
        "attribute_code": "url_key",
        "value": "chaz-kangeroo-hoodie-xs-black"
      },
      {
        "attribute_code": "msrp_display_actual_price_type",
        "value": "0"
      }
    ]
  },
...
]

如果您需要所有可配置选项并调用以下API

  

GET / V1 / configurable-products / {sku} / options / all

回应:

[
  {
    "id": 3,
    "attribute_id": "90",
    "label": "Color",
    "position": 0,
    "values": [
      {
        "value_index": 49
      },
      {
        "value_index": 52
      },
      {
        "value_index": 56
      }
    ],
    "product_id": 67
  },
  {
    "id": 2,
    "attribute_id": "137",
    "label": "Size",
    "position": 0,
    "values": [
      {
        "value_index": 167
      },
      {
        "value_index": 168
      },
      {
        "value_index": 169
      },
      {
        "value_index": 170
      },
      {
        "value_index": 171
      }
    ],
    "product_id": 67
  }
]

答案 1 :(得分:1)

如何使用REST API

1.身份验证

Magento允许开发人员在配置文件webapi.xml中定义Web API资源及其权限。以下是有关公开services as Web APIs的详细信息。

在进行Web API调用之前,您必须验证您的身份并拥有访问API资源所需的权限(授权)。身份验证允许Magento识别呼叫者的用户类型。根据用户(管理员,集成,客户或访客)访问权限,确定API调用的资源可访问性。

2。构建请求

每个Magento Web API调用都包含以下元素的组合:

2.1 HTTP动词

  • GET。请求传输目标的当前表示 资源。如果省略动词,则GET是默认值。
  • PUT。要求 用目标资源创建或替换目标资源的状态 由请求消息中包含的表示定义的状态 有效载荷。
  • POST。请求原始服务器接受 请求中包含的表示作为要处理的数据 目标资源。
  • DELETE。请求原始服务器删除 目标资源。

2.2 ConfigurableProduct的端点

GET    /V1/configurable-products/:sku/children
DELETE /V1/configurable-products/:sku/children/:childSku
PUT    /V1/configurable-products/variation
POST   /V1/configurable-products/:sku/child
GET    /V1/configurable-products/:sku/options/:id
GET    /V1/configurable-products/:sku/options/all
POST   /V1/configurable-products/:sku/options
PUT    /V1/configurable-products/:sku/options/:id
DELETE /V1/configurable-products/:sku/options/:id

2.3 HTTP标头

  

要在cURL命令中指定HTTP标头,请使用-H--header选项。

在Web API调用中指定以下一个或多个HTTP标头:

.---------------.-----------------------------------.
|  HTTP header  |                Syntax             |
|---------------|-----------------------------------|
| Authorization | Authorization: Bearer <TOKEN>     |
| Accept        | Accept: application/<FORMAT>      |
| Content-Type  | Content-Type:application/<FORMAT> |
'---------------'-----------------------------------'

其中<TOKEN>是Magento令牌服务返回的身份验证令牌。请参阅身份验证。

其中<FORMAT>JSONXML

2.4呼叫有效负载

呼叫有效负载是您随请求提供的输入参数和属性的集合。 API操作具有必需可选输入。

您可以在URI中指定输入参数。

您可以在JSON或XML格式的请求正文中指定输入属性。

2.5构建请求

  1. 准备要传递给请求对象的AuthorizationAcceptContent-Type标头。使用Magento令牌服务返回的授权令牌。

    $token = 'token';
    $httpHeaders = new \Zend\Http\Headers();
    $httpHeaders->addHeaders([
       'Authorization' => 'Bearer ' . $token,
       'Accept' => 'application/json',
       'Content-Type' => 'application/json'
    ]);
    
  2. 打开Magento/ConfigurableProduct/etc/webapi.xml配置文件,然后从Magento\ConfigurableProduct\Api\LinkManagementInterface界面找到getChildren方法。

  3. 将标头,URI和方法设置为请求对象。

    $request = new \Zend\Http\Request();
    $request->setHeaders($httpHeaders);
    $request->setUri('http://yourdomain.com/rest/V1/configurable-products/:sku/children');
    $request->setMethod(\Zend\Http\Request::METHOD_GET);    
    $params = new \Zend\Stdlib\Parameters([
       'sku' => 'sku-needed-for-example'
    ]);
    $request->setQuery($params);
    
  4. 准备HTTP Curl客户端对象并将请求对象传递给Client::send()方法。

    $client = new \Zend\Http\Client();
    $options = [
       'adapter'   => 'Zend\Http\Client\Adapter\Curl',
       'curloptions' => [CURLOPT_FOLLOWLOCATION => true],
       'maxredirects' => 0,
       'timeout' => 30
    ];
    $client->setOptions($options);  
    $response = $client->send($request);
    
  5. 此请求以JSON格式返回所有子项的列表。您还可以通过更改请求的XML标头来指定Accept格式。

  6. 3。使用cURL运行请求

    cURL是一个命令行工具,可让您从命令行或shell脚本发送和接收HTTP请求和响应。它适用于Linux发行版,Mac OS X和Windows。

    要使用cURL运行REST Web API调用,请使用cURL命令语法构造cURL命令。

    要在调用中创建端点,请附加在步骤2.5中构造的REST URI构造对此URL的请求:

    https://<MAGENTO_HOST_OR_IP>/<MAGENTO_BASE_INSTALL_DIR>/rest/

    有关cURL命令选项的完整列表,请参阅curl.1 the man page

    4。查看回复

    每个Web API调用都返回HTTP状态代码和响应有效负载。当出现错误时,响应主体也会返回错误消息。

    HTTP状态代码

    每个Web API调用都会返回一个反映请求结果的HTTP状态代码:

    .===========.=================.=================================================.
    | HTTP code |     Meaning     |                     Description                 |
    |===========|=================|=================================================|
    |    200    |      Success    | M2 return HTTP 200 to the caller upon success.  |
    |-----------|-----------------|-------------------------------------------------|
    |           |                 | If service implementation throws either         |
    |           |                 | `Magento_Service_Exception` or its derivative,  |
    |           |                 | the framework returns a HTTP 400 with a error   |
    |           |                 | response including the service-specific error   |
    |    400    |   Bad Request   | code and message. This error code could         |
    |           |                 | indicate a problem such as a missing required   |
    |           |                 | parameter or the supplied data didn't pass      |
    |           |                 | validation.                                     |
    |-----------|-----------------|-------------------------------------------------|
    |    401    |   Unauthorized  | The caller was not authorized to perform the    |
    |           |                 | request. For example, the request included an   |
    |           |                 | invalid token or a user with customer           |
    |           |                 | permissions attempted to access an object that  |
    |           |                 | requires administrator permissions.             |
    |-----------|-----------------|-------------------------------------------------|
    |    403    |    Forbidden    | Access is not allowed for reasons that are not  |
    |           |                 | covered by error code 401.                      |
    |-----------|-----------------|-------------------------------------------------|
    |    404    |    Not found    | The specified REST endpoint does not exist. The |
    |           |                 | caller can try again.                           |
    |-----------|-----------------|-------------------------------------------------|
    |    405    |   Not allowed   | A request was made of a resource using a method |
    |           |                 | that is not supported by that resource. For     |
    |           |                 | example, using GET on a form which requires data|
    |           |                 | to be presented via POST, or using PUT on a     |
    |           |                 | read-only resource.                             |
    |-----------|-----------------|-------------------------------------------------|
    |    406    | Not acceptable  | The requested resource is only capable of       |
    |           |                 | generating content that is not acceptable       |
    |           |                 | according to the Accept headers sent in the     |
    |           |                 | request.                                        |
    |-----------|-----------------|-------------------------------------------------|
    |    500    | System Errors   | If service implementation throws any other      |
    |           |                 | exception like network errors, database         |
    |           |                 | communication, framework returns HTTP 500.      |
    '==========='================='================================================='
    

    响应有效负载

    POST,PUT和GET Web API调用返回响应有效负载。此有效内容是JSON或XML格式的响应正文。请求中的Accept:application / header确定响应主体的格式,其中FORMAT是json或xml。

    成功的DELETE调用返回true。不成功的DELETE调用返回与其他调用类似的有效负载。

    错误格式

    发生错误时,响应正文包含错误代码,错误消息和可选参数。

    .------------.---------------------------------------------------------------.
    |     Part   |                          Description                          |
    |------------|---------------------------------------------------------------|
    |     code   | The status code representing the error.                       |
    |------------|---------------------------------------------------------------|
    |   message  | The message explaining the error.                             |
    |------------|---------------------------------------------------------------|
    | parameters | Optional. An array of attributes used to generate a different |
    |            | and/or localized error message for the client.                |
    '------------'---------------------------------------------------------------'