What is Magento 2 Web API calls - REST and SOAP

What is Magento 2 Web API calls - REST and SOAP

Magento Web API is a key feature of Magento which supports developers to use web services that communicate with the Magento system. For instance, a developer can create a customer account, product record through web service.

Magento Web API framework includes the following features:

 

  • It supports both REST (Representational State Transfer) and SOAP (Simple Object Access Protocol)
  • Magento Web API requires authentication to perform any task. There are 3 types of authentication:

 

Token-Based Authentication based on REST and SOAP

Oauth-Based Authentication based on OAuth 1.0a

Session-Based Authentication based on the current logged-in session of admin/customer

 

Here, in this article, I will explain you about REST Web API.

Construct A Request:

There are many Web APIs in Magento and these are defined in webapi.xml file of a module that is <module root dir>/vendor/<vendor-name>/<module-name>/etc/webapi.xml, where <vendor-name> is vendor name (e.g. magento) and <module-name> is module name (e.g. module-customer). For example, the web API for the Customer service is defined in the <Magento dir>/vendor/magento/module-customer/etc/webapi.xml.

 

A Web API call has the following elements to perform an action:

 

  • HTTP verb - The action to perform against the endpoint. There are:


   GET (default)
   PUT
   POST
   DELETE

 

  • Endpoint - An endpoint is a combination of the server that fulfils a request, the web service, the store code, the resource against which the request is being made, and any template parameters.

            To create the endpoint in the call -

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

 

            For instance -

            http://your-domain.com/index.php/rest/default/V1/customerGroups/:id

 

            Here,

            your-domain.com/index.php/  is the server name

            rest is the name of web service

            default is the code of default store of Magento Store. It can be a code of specific code or all         can be specified to perform an action on all stores.

            V1/customerGroups is the resource

            id is a template parameter

 

  • HTTP Headers – These are:

Authorization: It is required and specifies the token for authentication.

Accept: It is optional and specifies the format of response that is json (default) and xml.

Content-Type: It is required if request body is specified. Format of request body can either be json or xml

 

  • Call Payload – It is a set of input parameters and attributes that is supplied with the request. This is actually a request body in either json or xml format.

 

REST Web API are run through cURL. CURL is a command-line tool that lets you transmit and receive HTTP requests and responses from the command line or a shell script.

 

To make a Web API call, it requires an authenticated token for the cURL requests for admin and customer. To get a token, following are the REST URLs:

 

  • Admin Token - POST /V1/integration/admin/token
  • Customer Token - POST /V1/integration/customer/token

 

Following is the code to retrieve a token for admin -

 


	<?php
	$adminData = array("username" => "admin", "password" => "admin@1234");
	$ch = curl_init("http://your-domain.com/index.php/rest/V1/integration/admin/token");
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Length: " . strlen(json_encode($adminData))));
	$token = curl_exec($ch);
	curl_close($ch);

 

This code will assign Admin Token to $token variable.

 

Now, following is the code to create a new customer account:

 


<?php
/*********CREATE A CUSTOMER ACCOUNT*************/
$post = '{
        "customer": {
            "email": "user@example.com",
            "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"
            }
        ],
        "password": "test@1234"
}';
 
$ch = curl_init("http://your-domain.com/index.php/rest/V1/customers");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
echo '<pre>'; print_r(json_decode($result)); echo '</pre>';
curl_close($ch);

 

/*********CREATE A CUSTOMER ACCOUNT ENDS HERE*************/

 

For the above example to create a customer account, REST Web API call has been constructed in the following way:

 

  • Open <Magento Dir>/vendor/module-customer/etc/webapi.xml file.

 

  • Find the route element that defines createAccount call -

 


            <route url="/V1/customers" method="POST">
                        <service class="Magento\Customer\Api\AccountManagementInterface"                            method="createAccount"/>
                        <resources>
                                    <resource ref="anonymous"/>
                        </resources>
            </route>

 

            Here, endpoint of cURL request is having resource – V1/customers which is as same as    route url defined above under url attribute in <route> tag.

 

  • Now, open <Magento Dir>/vendor/module-customer/Api/AccountManagementInterface.php file.

 

 

            Here, you will see a function:

 


            public function createAccount(
                        \Magento\Customer\Api\Data\CustomerInterface $customer,
                        $password = null,
                        $redirectUrl = ''
            );
 
            There are 3 parameters of createAccount function - 
            $customer – is a data object which is required.
            $password – is optional
            $redirectUrl – is optional

 

To pass the customer data object in the POST call payload, specify JSON or XML request body on the call.

 

Following is the code to retrieve information about a customer:

 


<?php
/*****VIEW A CUSTOMER RECORD*********/
$ch = curl_init("http://your-domain.com/index.php/rest/V1/customers/1");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
 
$result = curl_exec($ch);
 
echo '<pre>'; print_r(json_decode($result)); echo '</pre>';
curl_close($ch);
exit();
/*****VIEW A CUSTOMER RECORD ENDS HERE*********/
 
Here, this code will fetch the record of customer having ID – 1.
 
Following is the code to retrieve the information about a product:
 
<?php
/*****VIEW A PRODUCT RECORD*********/
$request = "http://your-domain.com/index.php/rest/V1/products/24-MB01";  
$ch = curl_init($request);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
   
$result = curl_exec($ch);
echo '<pre>'; print_r($result); echo '</pre>';
curl_close($ch);
/*****VIEW A PRODUCT RECORD ENDS HERE*********/

Here, this code will fetch the record of product having code – 24-MB01.

 

I hope that this article would be helpful to you. I will continue to explain about SOAP and OAuth in next article.