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));
$('body').trigger('processStart');
$.ajax({
type: "POST",
url: "/rest/V1/custom/contact-form/",
data: formData,
success: function(){
$('body').trigger('processStop');
alert("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
$('body').trigger('processStop');
alert("Error");
},
dataType: 'json',
contentType: 'application/json',
});
});
});
</script>
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 :
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Imagineer_Contact',
__DIR__
);
etc/module.xml:
<?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" />
</config>
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):
<?php
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):
<?php
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()];
$this->logger->info($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.
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/system.log
var/log/exception.log
/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: