How to extend magento2 rest api in 7 easy steps ?

extend magento2 rest api

Recently, we were working on Hotel Booking marketplace to provide a partial day booking and real time pricing. As per recent study most of the users prefer to have mobile app for Hotel Booking, so our client also wanted an mobile app ( ios/android ) for his marketplace. He also wanted some custom features which were out of the box for magento. Though the magento rest api have most of the required feature but we also need to customize some api to support mobile client. So we have implemented custom api and would like to demonstrated How to extend magento2 rest api in 7 easy steps  ? We hope this article would help those who wanted to extend the current API and utilize it on their mobile client or third party integration. Let’s dive into creating custom API for Myorders using the below steps :

7 Easy steps to extend magento2 REST API

Step 1: Create Separate module for extend magento2 REST API

Let’s use the vendor name “Ipragmatech” and module name as a “Restfulapi”.  There are two ways to create module  :

  • Create Module using Online Tools : There are many online tools available to create module. We can use the CED  Module Creator , because its easy and straight forward.
  • Create Module Manually : We can create module manually. We need to remember the Folder structure of Magento 2. Please follow this article to create module manually.

We assume that you have successfully created the module.

Step 2: Create di.xml into app/code/Ipragmatech/Restfulapi/etc/

<?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="Ipragmatech\Restfulapi\Api\OrderInterface" type="Ipragmatech\Restfulapi\Model\Order" />
</config>

Step 3: Create webapi.xml into app/code/Ipragmatech/Restfulapi/etc/

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- Routing define -->
<route url="/V1/order/myorder" method="GET">
 <service class="Ipragmatech\Restfulapi\Api\OrderInterface" method="myorder"/>
 <resources>
  <resource ref="self"/>
 </resources>
 <data>
  <parameter name="customerId" force="true">%customer_id%</parameter>
 </data>
</route>
</routes>

Step 4: Create OrderInterface.php into app/code/Ipragmatech/Restfulapi/Api/

<?php

namespace Ipragmatech\Restful\Api;

use Ipragmatech\Restfulapi\Api\Data\PointInterface;

interface OrderInterface
{
public function myorder($customerId);
}

Step 5: Create Order.php into app/code/Ipragmatech/Restfulapi/Model/

<?php

namespace Ipragmatech\Restfulapi\Model;

use Ipragmatech\Restfulapi\Api\OrderInterface;

/**
* Defines the implementaiton class of the calculator service contract.
*/
class Order implements OrderInterface
{
public function myorder($customerId) {
 if(empty($customerId) || !isset($customerId) || $customerId == ""){
 throw new InputException(__('Id required'));
}
else{
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $orders = $objectManager->create('Magento\Sales\Model\Order')->getCollection()->addFieldToFilter('customer_id',$customerId);
 $orderData = array();
  if(count($orders)){
   foreach ($orders as $order){
   $data = array("order_id"=>$order->getEntityId(),"status"=>$order->getStatus(),
"amount"=>$order->getBaseGrandTotal(),
"order_date"=>$order->getUpdatedAt()
  );
   $orderData[] = $data;
  }
  return $orderData;
 }
 else{
  return $orderData;
 }
}
}
}

Step 6: Create the di.xml file into app/code/Ipragmatech/Restfulapi/etc/webapi_rest/ for customer authoriaztion:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Authorization">
<plugin name="customerAuthorization" type="Magento\Customer\Model\Plugin\CustomerAuthorization" />
</type>
<type name="Magento\Authorization\Model\CompositeUserContext">
<arguments>
<argument name="userContexts" xsi:type="array">
<item name="customerSessionUserContext" xsi:type="array">
<item name="type" xsi:type="object">Magento\Customer\Model\Authorization\CustomerSessionUserContext</item>
<item name="sortOrder" xsi:type="string">20</item>
</item>
</argument>
</arguments>
</type>
</config>

Step 7: Check the myorder api on postman

  • As we know that magento 2 provide three way of authorization : Token based, oauth and session based authorization.
  • Let’s try the token based authorization.
  • curl -X POST "https://magento.host/index.php/rest/V1/integration/customer/token" \
    -H "Content-Type:application/xml" \
    -d '<login><username>[email protected]</username><password>123123q</password></login>'
  • Let’s try myorder api (Get Request ) on postman. Use https://magento.host/rest/V1/order/myorder . Set content-type: application/json  and authoriaztion : bearer token_number in header.
  • We will get the json response of myorder like :
  •  
    [
        {
            "order_id": "5",
            "status": "pending",
            "amount": "85.0000",
            "order_date": "2016-06-01 17:48:32"
        }
    ]
    

Looking for ready-made solution

If you are looking for ready-made solution of magento mobile app. There are the following available solutions:

MagentoShop by iPragmatech

SimiCart by magestore

Conclusion

As per recent study most of the users prefer to have mobile app for Hotel Booking, so our client also wanted an mobile app ( ios/android ). So we would like to demonstrated How to extend magento2 rest api in 7 easy steps  ? We hope this article would help those who wanted to extend the current API and utilize it on their mobile client or third party integration. Feel free to contact us if you have any further query.

References

How to extend magento2 rest api in 7 easy steps ? was last modified: June 3rd, 2016 by Ajay Mehta