<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=262721675103356&amp;ev=PageView&amp;noscript=1">

How to create a simple web API in Magento2

Imagineer favicon
Aug 12, 2022 3:41:09 PM
How to create a simple web API in Magento 2

Webservices are vital mechanisms for two or more systems to communicate, since they allow information to be transferred, procedures to be executed or user data to be captured. 

Imagine that you fill out a form with your personal data, then these are sent to a server and processed, it can be to participate in a raffle, to request a particular service or make a claim. This article will cover a simple guide to create a webservice in Magento 2, which will be used as an example to capture the data of a customer who is filling out a contact form.

First, the form must be created for the client side, for this we are going to use the tool to create an HTML form quickly and easily:


You must copy the HTML code of the form and paste it where you want to show it to the user. For this exercise, a "contact" page will be created:


Additionally, the following javascript code will be used to submit the form when the user presses the Submit button (we invite you to add more functionality such as validations or a captcha, since this example is just a basic demo):

<script type="text/javascript" defer>
  require(['jquery','jquery/ui'], function($) {
    $('#submit').on('click', function(){
      var formData = new FormData($("#contact-form")[0]);
      formData = JSON.stringify(Object.fromEntries(formData));
        type: "POST",
                 url: "/rest/V1/custom/contact-form/",
        data: formData,
        success: function(){
        error: function (xhr, ajaxOptions, thrownError) {
        dataType: 'json',
        contentType: 'application/json',

From the previous javascript code, you must replace "contact-form" with the name that you want to give to the route of your webservice. With this we finish our form, now we are going to create the API and the execution of the server side.

In the folder, app/code of our Magento directory, we are going to create a module, in this example it will be named "Imagineer_Contact" (create the folder app/code/Imagineer/Contact).

Inside our module we will add the following files (replace "Imagineer" and "Contact" to match the name of your module):

registration.php   :



<?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="Imagineer_Contact" setup_version="1.0.0" />
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="Imagineer\Contact\Api\Contact" type="Imagineer\Contact\Model\Api\Contact"/>  
etc/webapi.xml  (you must replace "contact-form" with the same name that you assigned in the previous javascript code):
<?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/contact-form/">
        <service class="Imagineer\Contact\Api\Contact" method="getPost"/>
            <resource ref="anonymous"/>

Api/Contact.php (Here the parameters that the webservice receives must be indicated, in this case there are only 2, the name and the contact information, both are strings and their names must match the names of the HTML form fields):

namespace Imagineer\Contact\Api;
interface Contact
     * GET for Post api
     * @param string $name
     * @param string $info
     * @return string
    public function getPost($name, $info);

Model/Api/Contact.php (Here we are going to add the functionality of our getPost method, we must keep the same parameters and names as in the API that was defined in the previous interface):

namespace Imagineer\Contact\Model\Api;
use Psr\Log\LoggerInterface;
class Contact
    protected $logger;
    public function __construct(
        LoggerInterface $logger
        $this->logger = $logger;
     * @inheritdoc
    public function getPost($name, $info);
        $response = ['success' => false];
        try {
            // Your Code here
            $response = ['success' => true, 'message' => $name . " " . $info];
        } catch (\Exception $e) {
            $response = ['success' => false, 'message' => $e->getMessage()];
        return  json_encode($response);

Inside the getPost function, you can add the desired behavior, such as saving the information to a database, sending an email, or whatever you want to do. In any case, we always recommend that you do both client-side and server-side security validations, to avoid code injection attacks or simply clean up invalid data formats.

Once we have these files ready in our module, we only need to install and compile our Magento2 instance, to do this run the following commands:

bin/magento setup:upgrade

bin/magento setup:di:compile

bin/magento cache:flush

Now try entering the data in the form, I recommend opening the inspection console of your browser (in the case of Chrome, pressing F12 or right click > inspect). Then navigate to the Network tab and check what happens when you Submit the form.

Form contact name_Magento

You should see a 200 code with the response message. If the error code is 400, check the syntax of your javascript, and if it's error 500, check the files located at:



/var/log/apache2/error.log  (si usas apache)

/var/log/nginx/nginx_error.log (si usas nginx)

I hope that this guide has been useful to create a basic webservice in Magento2, if you want more information or have any comments about it, you can contact me at cliddell@imagineer.co and I will gladly try to answer you. If you want to download the code used in this guide, visit the following link: Imagineer_Contact.zip

Sobre este blog

Customer Experience Insights is a blog to share ideas, experiences and the vision of how to adopt better Customer Experiences in our organizations.


Suscríbase hoy

For weekly special offers and new updates!


Publicaciones por tema




Subscribe today

For weekly special offers and new updates!

Other Blogs

You may be interested

Subscribe today

For weekly special offers and new updates!