Skip to main content

Magento 2 API – Beginners Guide for API development

 Magento 2 API – Today we are going to learn how to create rest based API for Magento 2.

I have worked on Magento 1 and found it very difficult to create a rest webAPI.

But as I was expecting Magento 2 has a very easy way to define your API resources for the module, specially defining routes for Magento API integration.

Also, check how to create GraphQL API in Adobe Commerce

To create a rest API there are some certain requirements for Magento API integration :

  • you need to create an interface in your module’s API folder.
  • then you need to define all the API methods that you want to expose to the web in the interface.
  • all the methods should have a doc-block.
  • in the doc-block @api must be defined
  • if your method expects parameters than all the parameters must be defined in the doc-block as @params <type> <param> <description>
  • return type of the method must be defined as @return <type> <description>
  • concrete class of the method must be defined and it should give the definition of all the API methods and should inherit the doc-block.

If your API method do not met any of the above requirements then rest API will not work for magento 2 integration API.

Now, for an example lets create a test module named Webkul_TestApi for better understanding :

create your module composer.json, registration.php and module.xml files:

<?php
/**
* Webkul Software.
*
* @category Webkul_MpApi
*
* @author Webkul
* @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
* @license https://store.webkul.com/license.html
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Webkul_TestApi',
__DIR__
);
Explain Code
Powered By
{
"name": "webkul/marketplace-api",
"description": "Marketplace api for magento2",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0",
"magento/module-config": "100.0.*",
"magento/module-store": "100.0.*",
"magento/module-checkout": "100.0.*",
"magento/module-catalog": "100.0.*",
"magento/module-sales": "100.0.*",
"magento/module-customer": "100.0.*",
"magento/module-payment": "100.0.*",
"magento/module-quote": "100.0.*",
"magento/module-backend": "100.0.*",
"magento/module-directory": "100.0.*",
"magento/module-theme": "100.0.*",
"magento/framework": "100.0.*"
},
"type": "magento2-module",
"version": "2.0.0",
"license": [
"proprietary"
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Webkul\\TestApi\\": ""
}
}
}
Explain Code
Powered By
<?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="Webkul_TestApi" />
</config>
Explain Code
Powered By

Now create TestApiManagementInterface.php file in app/code/Webkul/TestApi/Api/ folder:

<?php
namespace Webkul\TestApi\Api;
interface TestApiManagementInterface
{
/**
* get test Api data.
*
* @api
*
* @param int $id
*
* @return \Webkul\TestApi\Api\Data\TestApiInterface
*/
public function getApiData($id);
}
Explain Code
Powered By

the above will define all the api methods you want to expose, all these methods must have doc-block defined with @api, @param and @return else it will not work for Magento 2 integration API.

Now create TestApiManagementInterface implementation file in app/code/Webkul/TestApi/Model/Api folder:

<?php
namespace Webkul\TestApi\Model\Api;
class TestApiManagement implements \Webkul\TestApi\Api\TestApiManagementInterface
{
const SEVERE_ERROR = 0;
const SUCCESS = 1;
const LOCAL_ERROR = 2;
protected $_testApiFactory;
public function __construct(
\Webkul\TestApi\Model\TestApiFactory $testApiFactory
) {
$this->_testApiFactory = $testApiFactory;
}
/**
* get test Api data.
*
* @api
*
* @param int $id
*
* @return \Webkul\TestApi\Api\Data\TestApiInterface
*/
public function getApiData($id)
{
try {
$model = $this->_testApiFactory
->create();
if (!$model->getId()) {
throw new \Magento\Framework\Exception\LocalizedException(
__('no data found')
);
}
return $model;
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$returnArray['error'] = $e->getMessage();
$returnArray['status'] = 0;
$this->getJsonResponse(
$returnArray
);
} catch (\Exception $e) {
$this->createLog($e);
$returnArray['error'] = __('unable to process request');
$returnArray['status'] = 2;
$this->getJsonResponse(
$returnArray
);
}
}
}
Explain Code
Powered By

the above class is the implementation of the interface as you can see I have only created one method getApiData as it is defined in the interface its return type is \Webkul\TestApi\Api\Data\TestApiInterface class

So now we have to create this class and its implementation too for api for magento 2.

Now create a model TestApi.php inside app/code/Webkul/TestApi/Model, this is a fake model it is not connected to any table since its only for testing purpose, I have just defined some setters and getters for some fields.

<?php
namespace Webkul\TestApi\Model;
/**
* Marketplace Product Model.
*
* @method \Webkul\Marketplace\Model\ResourceModel\Product _getResource()
* @method \Webkul\Marketplace\Model\ResourceModel\Product getResource()
*/
class TestApi implements \Webkul\TestApi\Api\Data\TestApiInterface
{
/**
* Get ID.
*
* @return int
*/
public function getId()
{
return 10;
}
/**
* Set ID.
*
* @param int $id
*
* @return \Webkul\Marketplace\Api\Data\ProductInterface
*/
public function setId($id)
{
}
/**
* Get title.
*
* @return string|null
*/
public function getTitle()
{
return 'this is test title';
}
/**
* Set title.
*
* @param string $title
*
* @return \Webkul\Marketplace\Api\Data\ProductInterface
*/
public function setTitle($title)
{
}
/**
* Get desc.
*
* @return string|null
*/
public function getDescription()
{
return 'this is test api description';
}
/**
* Set Desc.
*
* @param string $desc
*
* @return \Webkul\Marketplace\Api\Data\ProductInterface
*/
public function setDescription($desc)
{
}
}
Explain Code
Powered By

the above class has getTitle, getDescription and getId so we must expect that api for magento 2 will return these values in the response.

Now create the interface class for the above implementation in app/code/Webkul/TestApi/Api/Data.

<?php
/**
* Webkul Software.
*
* @category Webkul
*
* @author Webkul
* @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
* @license https://store.webkul.com/license.html
*/
namespace Webkul\TestApi\Api\Data;
/**
* Marketplace product interface.
*
* @api
*/
interface TestApiInterface
{
/**#@+
* Constants for keys of data array. Identical to the name of the getter in snake case
*/
const ENTITY_ID = 'entity_id';
const TITLE = 'title';
const DESC = 'description';
/**#@-*/
/**
* Get ID.
*
* @return int|null
*/
public function getId();
/**
* Set ID.
*
* @param int $id
*
* @return \Webkul\Marketplace\Api\Data\ProductInterface
*/
public function setId($id);
/**
* Get title.
*
* @return string|null
*/
public function getTitle();
/**
* Set title.
*
* @param string $title
*
* @return \Webkul\Marketplace\Api\Data\ProductInterface
*/
public function setTitle($title);
/**
* Get desc.
*
* @return string|null
*/
public function getDescription();
/**
* Set Desc.
*
* @param string $desc
*
* @return \Webkul\Marketplace\Api\Data\ProductInterface
*/
public function setDescription($desc);
}
Explain Code
Powered By

Now You need to create “app/code/Webkul/TestApi/etc/di.xml” file to map interfaces with the concrete classes:

<?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="Webkul\TestApi\Api\TestApiManagementInterface" type="Webkul\TestApi\Model\Api\TestApiManagement" />
<preference for="Webkul\TestApi\Api\Data\TestApiInterface" type="Webkul\TestApi\Model\TestApi" />
</config>
Explain Code
Powered By

Now create a webapi.xml file inside app/code/Webkul/TestApi/etc folder:

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- test api Group -->
<route url="/V1/testapi/custom/me" method="GET">
<service class="Webkul\TestApi\Api\TestApiManagementInterface" method="getApiData"/>
<resources>
<resource ref="self"/>
</resources>
<data>
<parameter name="id" force="true">%customer_id%</parameter>
</data>
</route>
</routes>
Explain Code
Powered By

the above xml file defines the routes and their permissions.
The route tag attributes:

  • attribute url defines the route for the web service
  • attribute method defines the request type GET,PUT,POST or DELETE

Now the service tag attributes:

  • class attribute is the interface class that defines the api methods.
  •  service attribute defines the exposed method

now the resource tag defines the access control these can be three level of access:

  •  Admin : for admin level access you need to define admin resource in the resource tag.
  • Customer: for customer level access you need to set self in the resource.
  • Guest: for guest level resources you need to define anonymous in the resource tag.
  • I have defined self so this resource will work for customer level access.

Originally Published: https://webkul.com/blog/magento2-custom-rest-api/

Comments

Popular posts from this blog

Why Adobe Commerce Cloud is best suited for Headless eCommerce

  Headless architecture is trending now as it is considered the future of eCommerce. In this article, we will cover some points to tell Why Adobe Commerce Cloud is best suited for headless eCommerce?  Magento 2 is the most popular CMS for eCommerce Development. Also, it provides many features and tools which make the headless implementation much easier from developing from scratch. What is Headless eCommerce? Headless  is an approach where you separate the frontend and backend of the eCommerce Website. It means that your customer experience platform ( UI & UX) is independent of your Content Management system.  Today, when eCommerce is moving towards the Omnichannel approach the role of headless eCommerce becomes crucial. With its use, the shop owner can provide a more flexible, speedy, and personalized experience to their customers. Why Adobe Commerce Cloud is best for Headless eCommerce? Adobe Commerce Cloud provides many tools that make the head...

Point Of Sale System For Magento

  It refers to a system where the merchant can create the order from his physical store using the POS and the order will be generated in the Magento. The Basic feature of the POS system for Magento is to create the order in front of the customer so that customer can purchase the goods from his/her physical store as well as from his/her online eCommerce store . With the help of this module, merchants can manage their inventory and customers. And the most important thing is that they can easily manage their day-to-day transactions without any hassle. This module is a powerful tool to manage the sales and revenue. Admin can also set up the physical store along with the online Magento store. Please Note- ·          The Magento POS connects only to the Printer, and barcode reader, whereas it doesn't connect directly with the cash drawer and card swapping machine. ·          POS requires a browser to ...

Aureus ERP: Your Open Source Business Solution

  Aureus ERP: Your Open Source Business Solution Aureus ERP is an open source ERP platform built on Laravel that helps make your business operations easier and better. Whether you need to handle projects, employees, inventory, or purchasing, AureusERP provides a flexible, safe, and easy to use solution that fits the specific needs of your business. AureusERP gives you a flexible, safe, and user friendly platform designed for your business’s specific needs. Why Choose Aureus ERP? Aureus ERP is not just your average ERP solution. It’s built on the Laravel framework, which makes it strong and safe, perfect for dealing with the complicated needs of today’s businesses. Now, let’s explore the features that make AureusERP unique. 1. Free and Open Source: Aureus ERP is open source, which means you can use it for free and customize it however you want. 2. Built on Laravel: Aureus ERP uses Laravel, a strong PHP framework that is famous for being secure and fast. This ensures tha...