0

Need to Create Rest API for Contact Us form. Submit contact us form via rest API and send an email.

API Name: Contact Us API

Method: POST

API URL: {baseurl}/rest/V1/contactus

1 Answer 1

3

I have created custom contact us API. This is a helpful for submit contact us form via rest API and send an email.

API Name: Contact Us API

Description: Submit a contact us form to send an email.

API URL: http://127.0.0.1/magento2/rest/V1/contactus?contactForm[name]=Kirti&contactForm[email][email protected]&contactForm[telephone]=1234567890&contactForm[comment]=Testcomment

Params:

contactForm[name]                  Kirti
contactForm[email]                 [email protected]
contactForm[telephone]             1234567890
contactForm[comment]               Testcomment

Method: POST

Response:

{    
    "message": "Thanks for contacting us with your comments and questions. We'll respond to you very soon."
}

Follow below file path to create Contact Us custom module For Contact Us API.

File path: magento2/app/code/Vendor/ContactusApi/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_ContactusApi',
    __DIR__
);

File path: magento2/app/code/Vendor/ContactusApi/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="Vendor_ContactusApi" setup_version="1.0.0"/>
</config>

File path: magento2/app/code/Vendor/ContactusApi/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/contactus" method="POST">
        <service class="Vendor\ContactusApi\Api\ContactusManagementInterface" method="submitForm"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>   
</routes>

File path: magento2/app/code/Vendor/ContactusApi/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="Vendor\ContactusApi\Api\ContactusManagementInterface" type="Vendor\ContactusApi\Model\ContactusManagement"/>
</config>

File path: magento2/app/code/Vendor/ContactusApi/Api/ContactusManagementInterface.php

<?php
namespace Vendor\ContactusApi\Api;

/**
 * Interface ContactusManagementInterface
 *
 * @package Vendor\ContactusApi\Api
 */
interface ContactusManagementInterface
{
    /**
     * Contact us form.
     *
     * @param mixed $contactForm
     *
     * @return \Vendor\ContactusApi\Api\Data\ContactusInterface
     */
    public function submitForm($contactForm);
}

File path: magento2/app/code/Vendor/ContactusApi/Api/Data/ContactusInterface.php

<?php
namespace Vendor\ContactusApi\Api\Data;

/**
 * ContactusInterface interface
 *
 * @api
 * @since 100.0.2
 */
interface ContactusInterface
{
    /**
    * @return \Vendor\ContactusApi\Api\Data\ContactusInterface[]
     */
    public function getMessage();

    /**
     * @param string $message
     * @return $this
     */
    public function setMessage($message);
}

File path: magento2/app/code/Vendor/ContactusApi/Model/ContactusManagement.php

<?php
declare(strict_types=1);

namespace Vendor\ContactusApi\Model;

use Magento\Contact\Model\MailInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\DataObject;
use Vendor\ContactusApi\Api\ContactusManagementInterface;

/**
 * Class ContactusManagement
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class ContactusManagement implements ContactusManagementInterface
{ 
    private $mail;

    protected $dataObjectFactory;

    public function __construct(
        MailInterface $mail,
        \Magento\Framework\DataObjectFactory $dataObjectFactory
    ) {
        $this->mail = $mail;
        $this->dataObjectFactory = $dataObjectFactory;
    }

    /**
    * @inheritDoc
    */
    public function submitForm($contactForm) {
        $result = $this->dataObjectFactory->create();

        if (empty($contactForm['name'])) {
            $result->setData('message', 'Enter the Name and try again.');
            return $result;
        }
        if (empty($contactForm['email'])) {
            $result->setData('message', 'Enter the Email and try again.');
            return $result;
        }
        if (false === \strpos($contactForm['email'], '@') || false === \strpos($contactForm['email'], '.com')) {
            $result->setData('message', 'The email address is invalid. Verify the email address and try again.');
            return $result;
        }
        if (empty($contactForm['comment'])) {
            $result->setData('message', 'Enter the Comment and try again.');
            return $result;
        }

        try {
            $this->sendEmail($contactForm);
            $result->setData('message', 'Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.');
        } catch (LocalizedException $e) {
            $result->setData('message', $e->getMessage());
        } catch (\Exception $e) {
            $result->setData('message', 'An error occurred while processing your form. Please try again later.');
        }
        return $result;
    }

    /**
     * @param array $post Post data from contact form
     * @return void
     */
    private function sendEmail($post)
    {
        $this->mail->send(
            $post['email'],
            ['data' => new DataObject($post)]
        );
    }
}
3
  • I am unable to receive an email after submitting data using API, the response is getting correct in Postman. What is missing? need to mention an email template or specific email? Apr 17, 2023 at 10:33
  • Are you checking in local ? Apr 18, 2023 at 13:08
  • No, I am checking on the server. qa-shop.workforceinstitute.io/rest/V1/… Dev&contactForm[comment]=This is testing message Apr 20, 2023 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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