Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
ARTICLE

How to use web API call in Magento 2

Magento 2 Web API Call: Today we will learn how to use the Magento 2 webapi as Ajax request in Magento 2 for Fetching, saving and for any operation in your module.

Magento 2 webapi : To know about Magento Web Api please refer to our wonderful blog WEB API .
You can use the Magento WebApi on any page. But here I am going to Guide you , how to use in Customer registration page.

If you are new to Magento 2 then first please refer to Magento 2’s basic Directory Structure.

1 : I am assuming that you have a basic idea of Magento 2 Structure and Web API now.
so let start with the create Layout handle.

Create handle  in this location : app/code/<namespace>/<module_name>/view/frontend/layout/customer_account_create.xml and paste the below code :

<?xml version="1.0"?>
<!--
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Ajaxwebapi
 * @author    Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer_form_register">
        	<action method="setTemplate">
        		<argument name="template" xsi:type="string">Webkul_Ajaxwebapi::customer/form/ajaxcall.phtml</argument>
        	</action>
          <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="ajaxlist-content" xsi:type="array">
                            <item name="component" xsi:type="string">Webkul_Ajaxwebapi/js/ajaxcall</item>
                            <item name="config" xsi:type="array">
                                <item name="template" xsi:type="string">Webkul_Ajaxwebapi/ajaxcall</item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

In above I have used knockout Component you can do this with widgets as well.

2: Now add Script in ajaxcall.phtml

<script type="text/x-magento-init">
    {
        "*": {
                "Magento_Ui/js/core/app":  <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
            }
        
    }
</script>

3 : Create webapi.xml in this location app/code/<namespace>/<module_name>/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Ajaxwebapi
 * @author    Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
 -->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/ajax/save/" method="POST">
        <service class="Webkul\Ajaxwebapi\Api\AjaxSaveInterface" method="ajaxSave"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

4 : Create service contract in this location app/code/<namespace>/<module_name>/Api/XyzInterface.php

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Ajaxwebapi
 * @author    Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\Ajaxwebapi\Api;

interface AjaxSaveInterface
{
    /**
     * Returns string
     *
     * @api
     * @param string $ajaxval
     * @return string
     */
    public function ajaxSave($ajaxval);

}

5 : create file for dependencies in this location : app/code/<namespace>/<module_name>/etc/di.xml

<?xml version="1.0"?>
<!--
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Ajaxwebapi
 * @author    Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Webkul\Ajaxwebapi\Api\AjaxSaveInterface" type="Webkul\Ajaxwebapi\Model\Ajax\AjaxSaveManagement" />
</config>

6 :  Create a Model and Implement the Interface defined (I hope you are aware of it else check Repositories ).

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Ajaxwebapi
 * @author    Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\Ajaxwebapi\Model\Ajax;

use Webkul\Ajaxwebapi\Api\AjaxSaveInterface;

class AjaxSaveManagement implements AjaxSaveInterface
{
   

   /**
    * Returns string
    *
    * @api
    * @param string $ajaxval
    * @return string
    */
    public function ajaxSave($ajaxval)
    {
        try{
          return "Saved";
        }catch(\Exception $e){

        }

    }

}

Step 7 

Api call : In Magento two we have a javascript module named as mage/storage , this class or module is used for ajax calling, here is the sample code to  use it .

/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Ajaxwebapi
 * @author    Webkul
 * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
define([
    'jquery',
    'mage/translate',
    'mage/storage'
    'uiComponent',
    'ko',
   'Magento_Ui/js/modal/alert'
   ], function (
        $,
        $t,
        storage,
        Component,
        ko,
        alert
    ) {
    'use strict';
     return Component.extend({
        initialize: function () {
           //#ajaxcall button id selector
          $('#ajaxcall').on('click',function(){
            if($('#ajaxcallvalue').val()){
                var serviceUrl,payload;

                 /**
                  * Save  values .
                  */
                 serviceUrl        = 'rest/V1/ajax/save';
                 payload           = {
                     ajaxval: $('#ajaxcallvalue').val()
                 };
                 storage.post(
                     serviceUrl,
                     JSON.stringify(payload)
                 ).done(function (response) {
                   alert({
                       content: $t('Action Successfully completed.')
                   });
                 }).fail(function (response) {
                    alert({
                        content: $t('There was error during saving data')
                    });
                });
              }
          });
        }
      })
    });

The above is the complete sample.  by which you can use the Magento knockout storage module for any operation of Ajax.

Note: Run the above JS code on any event. I have used a button and a text box for a sample.
Please read the links as well that I have added in between the blog If not checked yet.

That was much about the Magento 2 Web API Call.

You can also check our complete Magento 2 extensions.

Hope this will help and if you have any queries then feel free to ask below in the comment section.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • liz
    • Nishad Bhan (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home