Magento – Magento 2: How shipping rest api function called On Checkout

ajaxcheckoutjavascriptmagento2rest

When u click on "Ship here" on Checkout Page it calls

magento/rest/default/V1/carts/mine/estimate-shipping-methods-by-address-id

Then it goes to below JS files

magento\vendor\magento\module-checkout\view\frontend\web\js\model\shipping-rate-processor\customer-address.js

magento\vendor\magento\module-checkout\view\frontend\web\js\model\resource-url-manager.js

getUrlForEstimationShippingMethodsByAddressId: function(quote) {
    var params = (this.getCheckoutMethod() == 'guest') ? {quoteId: quote.getQuoteId()} : {};
    var urls = {
        'default': '/carts/mine/estimate-shipping-methods-by-address-id'
    };
    return this.getUrl(urls, params);
}

magento\vendor\magento\module-quote\Model\ShippingMethodManagement.php

 public function estimateByAddressId($cartId, $addressId)
    {
      echo 1;exit;
    }

How above function estimateByAddressId is Called?

Best Answer

As you pointed out, when you click "Ship here" a HTTP POST request is dispatched to "/V1/carts/mine/estimate-shipping-methods-by-address-id" REST API (from module-quote). If you take a look at module-quote/etc/webapi.xml you will find the url:

<route url="/V1/carts/mine/estimate-shipping-methods-by-address-id" method="POST">
  <service class="Magento\Quote\Api\ShippingMethodManagementInterface" method="estimateByAddressId"/>
  <resources>
    <resource ref="self" />
  </resources>
  <data>
    <parameter name="cartId" force="true">%cart_id%</parameter>
  </data>
</route>

You can notice that under the <route> element there is <service> element with the class="Magento\Quote\Api\GuestShipmentEstimationInterface" and method="estimateByExtendedAddress". Now obviously, the estimateByAddressId method cannot be instantiated from an interface.

Here comes in scene the magento 2 dependency injection. Look at module-quote/etc/di.xml file that maps an interface(Magento\Quote\Api\ShippingMethodManagementInterface) dependency to a preferred implementation class(Magento\Quote\Model\ShippingMethodManagement).

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Quote\Api\ShippingMethodManagementInterface" type="Magento\Quote\Model\ShippingMethodManagement" />
    ...................
</config>

This is how estimateByAddressId method is called.

Useful links:

Magento 2 Web APIs:
http://devdocs.magento.com/guides/v2.0/get-started/bk-get-started-api.html
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/service-contracts/service-to-web-service.html

Magento 2 Dependency injection:
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html
http://magento-quickies.alanstorm.com/post/68129858943/magento-2-injecting-interfaces