Hikmadh Commerce| Ecommerce Development Consulting | Magento Development and Consulting Service

How to create REST API in Magento 2?

Introduction:

In the fast-paced world of e-commerce, providing a seamless shopping experience for customers is paramount. One way to achieve this is by developing a robust and efficient REST API in your Magento store. In this blog post, we will walk you through the process of creating a REST API in Magento, enabling you to integrate your store with external applications, streamline data exchange, and enhance overall functionality. Let’s dive in!

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 building Magento store. However, in this tutorial, I tried to keep it as easy and understandable as possible.

Create a new extension:

Here I will be creating an extension under Hikmadh 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="Hikmadh_ApiIntegration" setup_version="0.0.1" />
            </config>

				
			

Registration: registration.php

				
					  <?php
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        Hikmadh_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="Hikmadh\ApiIntegration\Api\AddressInterface" method="setDefaultShipping"/>
      <resources>
          <resource ref="self"/>
      </resources>
      <data>
          <parameter name="addressId" force="true">%addressId%
      </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 an 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="Hikmadh\ApiIntegration\Api\AddressInterface" type="Hikmadh\ApiIntegration\Model\CustomerAddress" />
    </config>
				
			

Now, we need to create an 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 Hikmadh\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 Hikmadh\ApiIntegration\Model;
    use \Hikmadh\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;
          }
      }
    }
				
			

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

Conclusion:

Creating a REST API in Magento empowers you to extend the functionality of your online store and integrate it with a wide range of external applications. By following the steps outlined in this comprehensive guide, you’ll be well-equipped to develop a robust and secure REST API in Magento. Embracing the power of APIs will enable you to enhance customer experiences, streamline data exchange, and unlock new business opportunities in the ever-expanding e-commerce ecosystem.