INSERT DATA in Custom Table using REST API in Magento 2

2
782
INSERT DATA in Custom Table using REST API in Magento 2
INSERT DATA in Custom Table using REST API in Magento 2

In this article we going to see How to INSERT DATA in Custom Table using REST API in Magento 2?

First we going see what exactly the REST API.

The main purpose of REST API is to suggests for creating an object of data requested by client and send the values of the object in response to user.

For example it’s very simple if a user is requesting for movie ticket in Mumbai at specific place and time, then you can create an object on the server side for movie ticket.

Main scenario regarding why we need REST API ?

Important point regarding REST API is that, it stands for Representation State Transfer.

It depends on a stateless, client-server, cache-able communication protocol for that HTTP protocol is used.

The REST is architecture style which is designed for NET-WORK application.

Another important point regarding REST applications is that, it is used for HTTP requests to post data that is [POST & PUT], read data[GET], and delete[DELETE] data.

From these we can say that REST using HTTP doing all four CRUD operation ie ['Create'/'Read'/'Update'/'Delete'].

As you come to know about REST. Now we move toward main topic of REST API in Magento 2

Let Start with the point: (REST API Magento 2)

Lets do this practically, you need to follow step by step REST API in Magento 2

Step 1: Create a new module called Techone_TestApi: (REST API Magento 2)

Create the namespace Techone in the path app\code. Create the module name TestApi in the path app\code\Techone. Now, Create the file named registration.php, with the path app\code\Techone\TestApi.
<?php
use \Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Techone_TestApi', __DIR__);
  • Create the file name module.xml with the path app\code\Techone\TestApi\etc.
<?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="Techone_TestApi" setup_version="1.0.0">
    </module>
</config>
Create an Install Script using below script in the below path Create the file name installSchema.php in the path app\code\Techone\TestApi\Setup
It will create a table named "test_table" in the database.
<?php
namespace Techone\TestApi\Setup;
class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{
    public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, 
    \Magento\Framework\Setup\ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();




        $table = $installer->getConnection()->newTable(
        $installer->getTable('test_table')
        )->addColumn(
            'id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            [ 'identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true, ],
            'Entity ID'
        )->addColumn(
            'name',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [ 'nullable' => false, ],
            'Name'
        )->addColumn(
            'number',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [ 'nullable' => false, ],
            'Number'
        )
        ->addColumn(
            'city',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [ 'nullable' => false, ],
            'City'
        );
        $installer->getConnection()->createTable($table);

        $installer->endSetup();
    }
}
?>

End of step #1, I have been completed the step to create new module called Techone_TestApi

Step 2: Now steps to create an API: (REST API Magento 2)

  • Create the file name webapi.xml in the path app\code\Techone\TestApi\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">
 <route url="/V1/hello/test/" method="POST">
        <service class="Techone\TestApi\Api\TestInterface" method="setData"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Step 3: Declare di.xml

  • Moving to next step is to , Create the file name di.xml in the path app\code\Techone\TestApi\etc.
<?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="Techone\TestApi\Api\TestInterface" type="Techone\TestApi\Model\Test" />
</config>

Step 4: Declare TestInterface.php

  • Next step is, Create the file name TestInterface.php in the path app\code\Techone\TestApi\Api\TestInterface.php
<?php
namespace Techone\TestApi\Api;
interface TestInterface
{
  public function setData($data);
}

Step 3: Declare Model Test.php

  • Create the file name Test.php in the path app\code\Techone\TestApi\Model\Test.php
<?php
namespace Techone\TestApi\Model;
use Techone\TestApi\Api\TestInterface;
class Test implements TestInterface
{

    public function setData($data)
    {   
        $id =  $data['id'];
        $name =$data['name'];
        $number =$data['number'];
        $city =$data['city'];


        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $tableName = $resource->getTableName('test_table');

        $sql = "Insert Into " . $tableName . " (id, name, number, city) Values ('".$id."','".$name."','".$city."','".$id."')";     
        $connection->query($sql);       
        return 'successfully saved';
    }
}

Step 4: Test and see the results

Run the command lines following:
php bin/magento setup:upgrade
php bin/magento cache:flush

Step 5: Please POST the DATA using POSTMAN APP as shown in the below screenshot.

Imporatant Note: Header section [{"key":"Content-Type","value":"application/json","description":""}]
header postman
POSTING DATA

Body section:-

JSON DATA
JSON DATA

Ajax Call in Magento 2 Module

Step 9: Now next step is to check the data base table

Database
Database

I hope you liked my this article. If you have any queries or any question regarding this, Feel free to comment on Me.

2 COMMENTS

  1. After php bin/magento s:up command

    This Comes.

    Each method must have a doc block. See Techone\TestApi\Api\TestInterface::setData()

Comments are closed.