Magento 2 API: Definition and How to use it

Magento 2 API

Magento 2 API is a framework that permits developers and integrators a mechanism to make use of web services that interact well with the Magento 2 system. API is an crucial framework for ecommerce software, and even if you are only beginners working with Magento, you must have already heard of it. This post will provide you an overview of what is Magento 2 Web API, the kind of it and how to work with each of them.

What is Magento 2 API?

API stands for Application Programming Interface. In common, it enables you to access the data from an application. In other words, API can be considered as a middleman between a programmer and an application.  The main functions of Magento 2 API include REST (Representational State Transfer) and SOAP (Simple Object Access Protocol). Also, it  supports 3 types of authentication:

  1. Administrators and customers are validated via login credentials.
  2. Mobile applications are validated via tokens.
  3. Third-party applications are validated via OAuth 1.0a.
  • Each and every accounts and integration are assigned resources that they can access. The API framework checks whether the call has access to the request.
  • You can configure any Magento or third-party modules as a web API using few lines of XML code in the webapi.xml configuration file. If the service is not defined, it will not be shown.
  • The framework is depended on the CRUD model that stands for Generate, Read, Update and Delete.
  • The API framework provides field filtering responses in order to conserve mobile bandwidth.
  • The single web API call can run multiple services at once with the support of Integration-style web APIs.

Although there are 2 architectural kinds of the web APIs: REST  and SOAP . However, in the official documentation, they only come with raw curl request without any example. In order to connect and start with Magento 2 API effectively, we will show you PHP examples in specific.

Snippet API

File: etc/webapi.xml

<?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
	<route method="GET" url="/V1/magesolution-helloworld/post">
		<service class="Magesolution\HelloWorld\Api\PostManagementInterface" method="getPost"/>
		<resources>
			<resource ref="anonymous"/>
		</resources>
	</route>
</routes>

File: etc/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<preference for="Magesolution\HelloWorld\Api\PostManagementInterface" type="Magesolution\HelloWorld\Model\PostManagement"/>
</config>

File: Model/PostManagement.php

<?php 
namespace Magesolution\HelloWorld\Model;
 
 
class PostManagement {

	/**
	 * {@inheritdoc}
	 */
	public function getPost($param)
	{
		return 'api GET return the $param ' . $param;
	}
}

File: Api/PostManagementInterface.php

<?php 
namespace Magesolution\HelloWorld\Api;
 
 
interface PostManagementInterface {


	/**
	 * GET for Post api
	 * @param string $param
	 * @return string
	 */
	
	public function getPost($param);
}

What can Magento 2 web APIs be used for

Magento 2 APIs allow you to perform a wide array of tasks which are:

  • Create a shopping app which can be a traditional one which user can download on a mobile device. Besides, an app which an employee uses to help shoppers to make purchases on a showroom floor can also be generated.
  • It allows to integrate with the backend systems of CRM or ERP like Salesforce or Xero.
  • It enables you to integrate with a CMS. However, at the moment, it not support content tagging.
  • JavaScript widgets which make AJAX calls to access services can be generated in the Magento storefront or on the Admin panel.

How to work with Magento 2 API

To get started with Magento 2 API, firstly you need to register a web service on Magento Admin and follow the below steps:

 1. Create a Web Services User

From Magento admin move to System > Permission > All Users > Add New User to generate a web services user. In case you are using session-based or OAuth authentication, you need not generate a new web services user.

2. Create a new Integration

From Magento Admin navigate to System > Extensions > Integration > Add New Integration** to generate an integration. Ensure that you restrict the access of resources for the integration.

Magento 2 API

 

3. Configure Authentication

Make use of REST or SOAP for configuring the authentication.

How to Create Custom Rest API in Magento 2

  • Create module.xml at app/code/Magesolution/CustomApi/etc/module.xml by following the below code
<?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="Magesolution_CustomApi" setup_version="1.0.0" />
</config>
  • Generate registration.php at app/code/Magesolution/CustomApi/registration.php and use the below code
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magesolution_CustomApi',
    __DIR__
);
  • Create webapi.xml at app/code/Magesolution/CustomApi/etc/webapi.xml by following this syntax
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
    <route method="POST" url="/V1/custom/custom-api/">
        <service class="Magesolution\CustomApi\Api\CustomInterface" method="getPost"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>
  • Create di.xml at app/code/Magesolution/CustomApi/etc/di.xml by following the below code:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magesolution\CustomApi\Api\CustomInterface" type="Magesolution\CustomApi\Model\Api\Custom"/>
</config>
  • Create CustomInterface.php in path app/code/Magesolution /CustomApi/Api/CustomInterface.php
<?php

namespace Magesolution\CustomApi\Api;

interface CustomInterface
{
    /**
     * GET for Post api
     * @param string $value
     * @return string
     */

    public function getPost($value);
}
  • Create Custom.php in path app/code/Magesolution /CustomApi/Model/Api/Custom.php
<?php

namespace Magesolution\CustomApi\Model\Api;

use Psr\Log\LoggerInterface;

class Custom
{
    protected $logger;

    public function __construct(
        LoggerInterface $logger
    )
    {

        $this->logger = $logger;
    }

    /**
     * @inheritdoc
     */

    public function getPost($value)
    {
        $response = ['success' => false];

        try {
            // Your Code here
            
            $response = ['success' => true, 'message' => $value];
        } catch (\Exception $e) {
            $response = ['success' => false, 'message' => $e->getMessage()];
            $this->logger->info($e->getMessage());
        }
        $returnArray = json_encode($response);
        return $returnArray; 
    }
}

At last, run the setup upgrade and deploy commands and you are performed with generating a custom rest API in Magento 2. You can check the generated custom rest API using [webiste/domain]/swagger

Conclusion

Hence, this was all about the Magento 2 API and its uses, and how you can work with it. In case you have any more questions or any further questions regarding Magento, then you can get in touch with Magento experts for any free support

121 Total Views 5 Views Today