How to Create Custom Rest API in Magento 2
Rest API in Magento 2 defines a set of functions used by the developers to perform requests and get responses using the HTTP protocol. By default, Magento 2 provides some predefined rest APIs like Product API, Order API, Customer data API with which you can take virtual control of everything happening on the site. You can read our complete guide on Magento 2 API if you are just getting started.
Even though Magento 2 has these many rest APIs, they are not enough when it comes to using the custom data and their values. To manage your custom data and fields, you need to create custom rest API in Magento 2 and today, I have come up with the steps for the same 🙂
Steps to Create Custom Rest API in Magento 2:
- Create module.xml at app/code/Meetanshi/CustomApi/etc/module.xml with 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="Meetanshi_CustomApi" setup_version="1.0.0" /></config> - Create registration.php at app/code/Meetanshi/CustomApi/registration.php and paste the below code:
123456<?php\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,'Meetanshi_CustomApi',__DIR__); - Create webapi.xml at app/code/Meetanshi/CustomApi/etc/webapi.xml with the below code:
123456789<?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="Meetanshi\CustomApi\Api\CustomInterface" method="getPost"/><resources><resource ref="anonymous"/></resources></route></routes> - Create di.xml at app/code/Meetanshi/CustomApi/etc/di.xml with 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="Meetanshi\CustomApi\Api\CustomInterface" type="Meetanshi\CustomApi\Model\Api\Custom"/></config> - Create CustomInterface.php in path app/code/Meetanshi/CustomApi/Api/CustomInterface.php
1234567891011121314<?phpnamespace Meetanshi\CustomApi\Api;interface CustomInterface{/*** GET for Post api* @param string $value* @return string*/public function getPost($value);} - Create Custom.php in path app/code/Meetanshi/CustomApi/Model/Api/Custom.php
1234567891011121314151617181920212223242526272829303132333435363738<?phpnamespace Meetanshi\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;}}
Finally, run the setup upgrade and deploy commands and you are done with creating a custom rest API in Magento 2. You can check the created custom rest API using [webiste/domain]/swagger
Don’t forget to share your suggestions and queries through the comment section below. Also, let me know which type of custom rest API did you create and how you used the data. Don’t forget to share this simple guide to help your fellow Magento developers!
Still need help? Hire our Adobe-certified Magento experts.
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.
16 Comments
Outstanding article over again. Thank you;)
Hello Kennan,
We’re glad that the above solution helped you. Thanks for the appreciation.
Thank you
Helllo,
I need to craeate api to get all region on magento 2
Thanks
Hello Walid,
You need to apply custom code for that requirement.
Please refer the below blogs as a reference:
https://meetanshi.com/blog/get-region-code-by-region-id-magento-2/
https://meetanshi.com/blog/magento-2-get-region-id-by-region-country-code/
Thank You
I have a question all the events in Magento2 will work regardless of REST API, frontend, and admin?
Hello Duke Rin,
No, it does not only work with events.
Thank You.
After upload this module, I can see this issue.
PHP Parse error: syntax error, unexpected ‘ ‘ (T_STRING), expecting ‘)’ in /var/www/html/testmage2/app/code/Meetanshi/CustomApi/registration.php on line 3
Please let me know about this issue reason.
Thanks
Best Regards.
Hello Harry,
There may be an issue in copying the code.
Please try as:
Thank You.
getting 404 error
{
“message”: “Request does not match any route.”,
“trace”: null
}
Hello,
Please clear the cache and check again.
Thank you.
Failed to load API definition.
Hey,
Can you explain the issue or provide a screenshot of any error you are facing?
It will help me to solve the issue quicker.
Thank you.
after hitting url, I am getting this
“message”: “\”%fieldName\” is required. Enter and try again.”,
“parameters”: {
“fieldName”: “value”
},
Hello,
You have not passed the parameter in API created which is causing the error.
You won’t get the output by directly hitting the URL.
Thanks.
unexpected ‘ ‘ (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /app/app/code/ciscomodule/custom/Api/Custom.php on line 9
Hello,
It seems as if the file is not properly copied.
Thank you.