Magento 2 REST API

In the previous post, we have just look into what is Magento 2 API, the benefits of it, and how to get started. Now I’m going to provide you more information about API, specifically is the REST APT.

REST API

What is REST API

The Magento 2 REST API identifies various functions which can be used to perform requests and receive responses. A developer can perform these interactions by using the HTTP protocol.

The caller leads to an HTTP request which includes the below elements:

  • An HTTP header which provides not only authentication but also other instructions
  • A verb which is the action against the endpoint, it can be GET, POST, PUT, and DELETE.
  • An endpoint is a Uniform Resource Indicator (URI). This endpoint identifies the server, the web service, and also the resource which is acted on.
  • The call payload includes set of input parameters and attributes which you supply with the request.

A response payload and an HTTP status code will be returned

To help you understand easier, below are the details information about these four elements:

HTTP headers

Below is the table which describes three HTTP headers in your web API calls:

HTTP header Description Syntax  
Authorization This HTTP header is required. It specifies the authentication token which proves that you are the owner of a Magento account. The token is specified in the Authorization request header with the HTTP authorization scheme Bearer. Authorization: Bearer <TOKEN>. <TOKEN> is the authentication token which is returned by the Magento token service.  
Accept This HTTP header is optional. It specifies the response body’s format. JSON is the default. Accept: application/<FORMAT>. <FORMAT> is JSON or XML.  
Content-Type This HTTP header is required for operations with a request body. It specifies the request body’s format. Content-Type:application/<FORMAT>. <FORMAT> is JSON or XML.  

HTTP verb

  • GET: This verb requests a current representation transfer of the target resource. If the verb is omitted, the default is GET.
  • PUT: This verb requests the target resource’s state be created or replaced with the state which is defined by the representation enclosed in the request message payload.
  • POST: This verb requests the representation enclosed which is in the request to be accepted as data for the target resource to process.
  • DELETE: This verb requests the target resource to be deleted by the origin server.

Endpoint

This is a combination of the server, web service, store code, resource against and template parameters.

For instance, in the endpoint http://magento.ll/index.php/rest/default/V1/customerGroups/:id, magento.ll/index.php/ is the server, rest is the web service, /V1/customerGroups is the resource, and id is the template parameter.

A store code can include one of the values which are mentioned below:

  • The assigned store code of the store.
  • default which is the default value when there are no store code provided.
  • all only applies to endpoints which are defined in the CMS and Product modules. The API call will affect all of the merchant’s stores if this value is specified.

Call payload

This element is a set of input parameters and attributes which are supplied with the request. Both required and optional inputs are included in API operations.

Input parameters are specified in the URI. For instance, in the URI GET/V1/customers/:customerId, the customerId template parameter must be specified.

Input attributes are specified in a JSON- or XML-formatted request body. For example, in the POST /V1/customers call, a request body must be specified like this:

{
    "customer": {
        "email": "[email protected]",
        "firstname": "John",
        "lastname": "Doe"
    },
    "addresses": [
        {
            "defaultShipping": true,
            "defaultBilling": true,
            "firstname": "John",
            "lastname": "Doe",
            "region": {
                "regionCode": "CA",
                "region": "California",
                "regionId": 12
            },
            "postcode": "90001",
            "street": ["Zoe Ave"],
            "city": "Los Angeles",
            "telephone": "555-000-00-00",
            "countryId": "US"
        }
    ]
}

This includes a customer object which has customer email, first name, last name, and address information. This information is used to populate the new customer account.

How to call a request

Below I will provide you an example on how to construct a REST web API call to create an account.

<route url="/V1/customers" method="POST">
   <service class="Magento\Customer\Api\AccountManagementInterface" method="createAccount"/>
   <resources>
      <resource ref="anonymous"/>
   </resources>
</route>
  • Step 3: To construct the URI, the method and url values are used on the route element. Here, POST /V1/customers is the URI.

  • Step 4: The class attribute is used on the service element to identify the service interface. The service interface in this example is the AccountManagementInterface PHP file.

In the AccountManagementInterface.php file, the createAccount method can be found like this:

public function createAccount(
     \Magento\Customer\Api\Data\CustomerInterface $customer,
     $password = null,
     $redirectUrl = ''
 )

A customer data object is required while the password and redirectUrl values are optional. Null is the default password value, the default redirectUrl value is blank.

  • Step 5: Specify JSON or XML request body on the call to pass the customer data object in the POST call payload.

Example of Customers Search API request

This is an example of generating a Customers Search request according to search criteria. This request will return a customers’ list which matches the given search criteria.

  • Step 1: Authorization, Accept and Content-Type headers need to be passed to a request object. The Authorization token which is returned by the Magento token service is used.
$token = 'token';
$httpHeaders = new \Zend\Http\Headers();
$httpHeaders->addHeaders([
   'Authorization' => 'Bearer ' . $token,
   'Accept' => 'application/json',
   'Content-Type' => 'application/json'
]);
  • Step 2: Open the Magento/Customer/etc/webapi.xml configuration file. Then find the interface CustomerRepositoryInterface with the method getList.

  • Step 3: The headers, URI and method need are set to a request object. URI /V1/customers/search and method GET values are used. The searchCriteria parameter is used to complete the Customer Search query.

Below is the example which finding the customers who have the first name contains Ver and the last name contains Costello.

 $request = new \Zend\Http\Request();
 $request->setHeaders($httpHeaders);
 $request->setUri('http://magento.ll/rest/V1/customers/search');
 $request->setMethod(\Zend\Http\Request::METHOD_GET);

 $params = new \Zend\Stdlib\Parameters([
     'searchCriteria' => [
         'filterGroups' => [
             0 => [
                 'filters' => [
                     0 => [
                         'field' => 'firstname',
                         'value' => '%ver%',
                         'condition_type' => 'like'
                     ],
                     1 => [
                         'field' => 'lastname',
                         'value' => '%Costello%',
                         'condition_type' => 'like'
                     ]
                 ]
             ]
         ]
     ],
     'current_page' => 1,
     'page_size' => 10
 ]);
    
 $request->setQuery($params);
  • Step 4: A HTTP Curl client object is prepared and the request object is pass 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);

A list of customers in JSON format will be returned:

{
    "items": [
        {
            "id": 1,
            "group_id": 1,
            "default_billing": "1",
            "default_shipping": "1",
            "created_at": "2017-12-05 09:50:11",
            "updated_at": "2018-09-22 06:32:50",
            "created_in": "Default Store View",
            "dob": "1973-12-15",
            "email": "[email protected]",
            "firstname": "Veronica",
            "lastname": "Costello",
            "gender": 2,
            "store_id": 1,
            "website_id": 1,
            "addresses": [
                {
                    "id": 1,
                    "customer_id": 1,
                    "region": {
                        "region_code": "MI",
                        "region": "Michigan",
                        "region_id": 33
                    },
                    "region_id": 33,
                    "country_id": "US",
                    "street": [
                        "6146 Honey Bluff Parkway"
                    ],
                    "telephone": "(555) 229-3326",
                    "postcode": "49628-7978",
                    "city": "Calder",
                    "firstname": "Veronica",
                    "lastname": "Costello",
                    "default_shipping": true,
                    "default_billing": true
                },
                {
                    "id": 19,
                    "customer_id": 1,
                    "region": {
                        "region_code": "London ",
                        "region": "London ",
                        "region_id": 0
                    },
                    "region_id": 0,
                    "country_id": "GB",
                    "street": [
                        "1 Studio 103 The Business Centre 61"
                    ],
                    "telephone": "1234567890",
                    "postcode": "CF24 3DG",
                    "city": "Tottenham ",
                    "firstname": "Veronica",
                    "lastname": "Costello"
                }
            ],
            "disable_auto_group_change": 0
        }
    ],
    "search_criteria": {
        "filter_groups": [
            {
                "filters": [
                    {
                        "field": "firstname",
                        "value": "%ver%",
                        "condition_type": "like"
                    }
                ]
            }
        ]
    },
    "total_count": 1
}

An XML format can also be specified by changing the Accept header of the request.

Conclusion

Above I have just provided you all the information about what is REST API and how a request can be called. I hope this post is useful for you. If you have further questions or new ideas, feel free to leave a comment below.

Enjoyed the tutorial? Spread it to your friends!