3

I Have custom table name like test_table and it contains fields like name, number and city.

I want to insert data using Magento 2 REST API.

Please Let me know if you have any idea?

  • 1
    Hi Rajan please check the answer which i have posted might be which is very useful and simple steps if u have any query please commit me thanks @Rajan – Nagaraju Kasa Aug 14 '17 at 14:33
  • 1
    Hi Rajan let me know whether u tried my answer? If u have any questions comment me thanks – Nagaraju Kasa Aug 15 '17 at 3:18
7

Step 1:- Create a module Stackexchange_Test using silk software module creator Click here to create a module

Step2 :- create a install script using below script in the below path app/code/Stackexchange/Test/Setup/InstallSchema.php

<?php
namespace Stackexchange\Test\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();
        //START: install stuff
        //END:   install stuff

    //START table setup
    $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);
//END   table setup
$installer->endSetup();
    }
}
?>

Now steps to create a api

Step 3: app/code/Stackexchange/Test/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 url="/V1/hello/test/" method="POST">
        <service class="Stackexchange\Test\Api\TestInterface" method="setData"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Step 4: app/code/Stackexchange/Test/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="Stackexchange\Test\Api\TestInterface" type="Stackexchange\Test\Model\Test" />
</config>

Step 5: app/code/Stackexchange/Test/Api/TestInterface.php

<?php
namespace Stackexchange\Test\Api;

interface TestInterface
{

    /**
     * POST for test api
     * @param string[] $data
     * @return string
     */

  public function setData($data);

}

Step 6: app/code/Stackexchange/Test/Model/Test.php

<?php
namespace Stackexchange\Test\Model;
use Stackexchange\Test\Api\TestInterface;
class Test implements TestInterface
{


     /**
     * {@inheritdoc}
     */
    public function setData($data)
    {   
        $id =  $data['id'];
        $name =$data['name'];
        $number =$data['number'];
        $city =$data['city'];
        //Customize the code as per your requirement.

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

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

Step 7:- While do the changes please use di compile and clear cache and page cache and deploy the same

Step 8: Please post the data using postman app as shown in the below screenshot.

Note: Header section [{"key":"Content-Type","value":"application/json","description":""}]

post men header section

Body section:-

enter image description here

Step 9: check the data base table 'test_table'

enter image description here

  • 1
    You are welcome @rajan thanks for giving the reply happy coding – Nagaraju Kasa Aug 16 '17 at 5:28
-1

First you need to extend the rest api by adding a custom route.

An example of this is explained here: https://www.demacmedia.com/magento-commerce/extending-magento-2-rest-web-api/

After that you just need to add your model functionality into your controller.

Examples found here: http://www.mage-world.com/blog/how-to-use-model-and-collection-in-magento-2.html

Hope this helps you out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.