How to create REST API in Magento 2?

By: Vishal Sutariya, Sep 25th, 2018 # How to # Magento # Magento 2

How to create REST API in Magento 2
In this post, I work through a working example of how to create REST API in Magento 2. It seems a bit difficult and tricky when you have to work with REST web services and that too in Magento. However, in this tutorial, I tried to keep it as easy and understandable as possible. Follow the below quick steps carefully and create your RESTful service in a matter of minutes. Create a new module. Here I will be creating a Module under AureateLabs directory named as “ApiIntegration”. Create Module Configuration File & Registration File under ApiIntegration directory. Module Configuration: etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="AureateLabs_ApiIntegration" setup_version="0.0.1" />
</config>
Registration: registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    AureateLabs_ApiIntegration,
    __DIR__
);
Here we will be creating a simple API service which will set customers’ default shipping address from the address id parameter. Now, create a webapi.xml configuration file to configure the access rights and API interface that will specify which method it will use. Create a webapi.xml file under the etc directory. And paste the following code into it.
<?xml version="1.0" encoding="UTF-8"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/customers/set-default-shipping" method="POST">
  <service class="AureateLabs\ApiIntegration\Api\AddressInterface" method="setDefaultShipping"/>
  <resources>
      <resource ref="self"/>
  </resources>
  <data>
      <parameter name="addressId" force="true">%addressId%</parameter>
  </data>
</route>
</routes>
  • Route tag defines an endpoint(URL) & Method (Valid values are GET, POST, PUT, and DELETE) of the REST API.
  • Resource tag defines what resources user needs to have to be able to access this API call.
  • Possible options are self, anonymous or Magento resource like Magento_Catalog::products or Magento_Customer::group.
Now, create a di.xml file to define interface and model that defines which model will be called by the defined interface. Create di.xml File under an etc directory and add following code into it.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
  <preference for="AureateLabs\ApiIntegration\Api\AddressInterface" type="AureateLabs\ApiIntegration\Model\CustomerAddress" />
</config>
Now, we need to create interface and model, please note that you need to take care of the comments as well. Interface: Api/AddressInterface.php
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace AureateLabs\ApiIntegration\Api;
/**
* @api
*/
interface AddressInterface
{
  /**
   * Set default shipping address
   *
   * @return boolean|array
   */
  public function setDefaultShipping();
}
Now, We will create the Model and within the model, we will add the functionality that will be executed by the call to API method. Model: CustomerAddress.php
<?php
namespace AureateLabs\ApiIntegration\Model;
use \AureateLabs\ApiIntegration\Api\AddressInterface;
class CustomerAddress implements AddressInterface
{
  /**
   * @var \Magento\Customer\Api\Data\AddressInterfaceFactory
   */
  protected $addressFactory;
  /**
   * @var \Magento\Framework\App\RequestInterface
   */
  protected $request;
  /**
   * CustomerAddress constructor.
   * @param \Magento\Customer\Model\AddressFactory $addressFactory
   * @param \Magento\Framework\App\RequestInterface $request
   */
  public function __construct(
      \Magento\Customer\Model\AddressFactory $addressFactory,
      \Magento\Framework\App\RequestInterface $request
  )
  {
      $this->addressFactory = $addressFactory;
      $this->request = $request;
  }
  public function setDefaultShipping() {
      $array = array();
      $params = $this->request->getParams();
      $addressId = trim($params['addressId'] ?? null);
      if (empty($addressId) || !is_numeric($addressId)) {
          $arr['msg'] = 'Address ID is invalid!';
          array_push($array, $arr);
          return $array;
      }
      $address = $this->addressFactory->create()->load($addressId);
      $address->setIsDefaultShipping(1);
      if($address->save()){
          return true;
      }else{
          return false;
      }
  }
}
Above function will set the default shipping address of the customer using address id which is provided as the parameter. This is all you need to know to create a successful RESTful web service in Magento 2. We hope you followed the above procedure carefully taking care of every bit of code. Even though you have any doubt or queries related to this, feel free to reach us.