How to Perform CRUD Operations Using API in Magento 2
One of the most commonly required operations in the Magento 2 store while managing a database is to perform CRUD operations. CRUD stands for Create, Read, Update and Delete.
Magento 2 offers the collection to manage data in a database easily. That’s why we don’t have to write many lines of code to create a CRUD.
However, what if we want to perform such kinds of operations based on API requests or integrate API on the frontend?
For instance, you need to send data from other platforms’ registration forms to the Magento database or integrate API in mobile. For such requirements, we have to call an API that sends a request to the server.
In such scenarios, use the below code to perform CRUD operation using API in Magento 2!
Steps to Perform CRUD Operations Using API in Magento 2
- Create module.xml at app/code/Vendor/Module/etc/ and use the below code.
1234<?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="Vendor_Module" setup_version="1.0.0" /></config> - Create registration.php at app/code/Vendor/Module/ and paste the below code:
123456<?php\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,'Vendor_Module',__DIR__); - Create webapi.xml at app/code/Vendor/Module/etc/ with the below code:
12345678910111213141516171819202122232425262728293031323334<?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="Vendor\Module\Api\CustomInterface" method="getPost"/><resources><resource ref="anonymous"/></resources></route><route method="GET" url="/V1/custom/getdata/"><service class="Vendor\Module\Api\CustomInterface" method="getData"/><resources><resource ref="anonymous"/></resources></route><route method="GET" url="/V1/custom/delete/"><service class="Vendor\Module\Api\CustomInterface" method="getDelete"/><resources><resource ref="anonymous"/></resources></route><route method="GET" url="/V1/custom/getbyid/"><service class="Vendor\Module\Api\CustomInterface" method="getById"/><resources><resource ref="anonymous"/></resources></route><route method="POST" url="/V1/custom/edit/"><service class="Vendor\Module\Api\CustomInterface" method="getEdit"/><resources><resource ref="anonymous"/></resources></route></routes> - Create di.xml at app/code/Vendor/Module/etc/ and use the below code:
1234<?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="Vendor\Module\Api\CustomInterface" type="Vendor\Module\Model\Api\Custom"/></config> - Create CustomInterface.php at app/code/Vendor/Module/Api/
1234567891011121314151617181920212223242526272829303132333435363738<?phpnamespace Vendor\Module\Api;interface CustomInterface{/*** GET for Post api* @param string $title* @return string*/public function getPost($title);/*** @return string*/public function getData();/*** @param int $id* @return bool true on success*/public function getDelete($id);/*** @param int $id* @return string*/public function getById($id);/*** GET for Post api* @param string $title* @return string*/public function getEdit($title);} - Create Custom.php at app/code/Vendor/Module/Model/Api/ and use the below code:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788<?php namespace Vendor\Module\Model\Api;use Vendor\Module\Api\CustomInterface;use Vendor\Module\Model\ModuleFactory;class Custom implements CustomInterface{private $moduleFactory;private $quote;protected $response = ['success' => false];public function __construct(moduleFactory $moduleFactory, \Magento\Quote\Model\Quote $quote){$this->quote = $quote;$this->moduleFactory = $moduleFactory;}/** * GET for Post api * @param string $title * @return string */public function getPost($title){$insertData = $this->moduleFactory->create();try {$insertData->setTitle($data['title'])->save();$response = ['success' => true, 'message' => $data];} catch (\Exception $e) {$response = ['success' => false, 'message' => $e->getMessage()];}return $response;}/** * @return string */public function getData(){try {$data = $this->moduleFactory->create()->getCollection()->getData();return $data;} catch (\Exception $e) {return ['success' => false, 'message' => $e->getMessage()];}}/** * @param int $id * @return bool true on success */public function getDelete($id){try {if ($id) {$data = $this->moduleFactory->create()->load($id);$data->delete();return "success";}} catch (\Exception $e) {$response = ['success' => false, 'message' => $e->getMessage()];}return "false";}/** * @param int $id * @return string */public function getById($id){try {if ($id) {$data = $this->moduleFactory->create()->load($id)->getData();return ['success' => true, 'message' => json_encode($data)];}} catch (\Exception $e) {return ['success' => false, 'message' => $e->getMessage()];}}/** * GET for Post api * @param string $title * @return string */public function getEdit($title){$edit = file_get_contents("php://input");$data = json_decode($edit, true);$insertData = $this->moduleFactory->create();$id = $data['id'];if ($id) {try {$insertData->load($id);$insertData->setTitle($data['title'])->save();$response = ['success' => true, 'message' => $data];} catch (\Exception $e) {$response = ['success' => false, 'message' => $e->getMessage()];}}return response;}}
Done!
Also read: Alternative to Magento 2 Deprecated Load, Save and Delete Methods.
Any doubts about the above method can be mentioned in the Comments section below. I’d be happy to help.
Also, do share the post with Magento Community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
Solved: Failed to Load API Definition in Magento 2 Swagger
How to Dynamically Schedule Cron Job in Magento 2 System Configuration
Next