phpmagento2magento-rest-api

Magento Product's API


I have magento2 for my store and I want to fetch all configurable/simple product and their child (variant) product with REST API. I am able to fetch all products in single REST API call but it doesn't provide me configurable product's child.

I need configurable products something like below:

{
    "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,
            .................
        }               
    ]   
}

Solution

  • How use REST APIs

    1. Authentication

    Magento allows developers to define web API resources and their permissions in a configuration file webapi.xml. Here are more details on exposing services as Web APIs.

    Before you can make web API calls, you must authenticate your identity and have necessary permissions (authorization) to access the API resource. Authentication allows Magento to identify the caller’s user type. Based on the user’s (administrator, integration, customer or guest) access rights, API calls’ resource accessibility is determined.

    2. Construct a request

    Each Magento web API call contains of a combination of these elements:

    2.1 HTTP verb

    2.2 Endpoints for 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 headers

    To specify an HTTP header in a cURL command, use the -H or --header option.

    Specify one or more of the following HTTP headers in your web API calls:

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

    Where <TOKEN> is the authentication token returned by the Magento token service. See Authentication.

    Where <FORMAT> is either JSON or XML.

    2.4 Call payload

    The call payload is set of input parameters and attributes that you supply with the request. API operations have both required and optional inputs.

    You specify input parameters in the URI.

    You specify input attributes in a JSON- or XML-formatted request body.

    2.5 Construct a request

    1. Prepare Authorization, Accept and Content-Type headers to be passed to a request object. Use the Authorization token returned by the Magento token service.

      $token = 'token';
      $httpHeaders = new \Zend\Http\Headers();
      $httpHeaders->addHeaders([
         'Authorization' => 'Bearer ' . $token,
         'Accept' => 'application/json',
         'Content-Type' => 'application/json'
      ]);
      
    2. Open the Magento/ConfigurableProduct/etc/webapi.xml configuration file and find the getChildren method from Magento\ConfigurableProduct\Api\LinkManagementInterface interface.

    3. Set the headers, URI and method to a request object.

      $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. Prepare a HTTP Curl client object and pass the request object to Client::send() method.

      $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. This request returns a list of all childrens in JSON format. You can also specify XML format by changing Accept header of the request.

    3. Use cURL to run the request

    cURL is a command-line tool that lets you transmit and receive HTTP requests and responses from the command line or a shell script. It is available for Linux distributions, Mac OS X, and Windows.

    To use cURL to run your REST web API call, use the cURL command syntax to construct the cURL command.

    To create the endpoint in the call, append the REST URI that you constructed in Step 2.5 Construct a request to this URL:

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

    For a complete list of cURL command options, see curl.1 the man page.

    4. Review the response

    Each web API call returns a HTTP status code and a response payload. When an error occcurs, the response body also returns an error message.

    HTTP status codes

    Each web API call returns an HTTP status code that reflects the result of a request:

    .===========.=================.=================================================.
    | 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.      |
    '==========='================='================================================='
    

    Response payload

    POST, PUT, and GET web API calls return a response payload. This payload is a JSON- or XML-formatted response body. The Accept: application/ header in the request determines the format of the response body, where FORMAT is either json or xml.

    A successful DELETE call returns true. An unsuccessful DELETE call returns a payload similar to the other calls.

    Error format

    When an error occurs, the response body contains an error code, error message, and optional parameters.

    .------------.---------------------------------------------------------------.
    |     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.                |
    '------------'---------------------------------------------------------------'