3

This is something I used to be able to do in 2.2, but in 2.3 I can't.

A simple controller to handle a POST method, and only receive and send application/json content type.

It works for GET/PUT methods, but if POST, it will render home page (html).

<?php

namespace <vendor>\<module>\Controller\Api;

class MyApi extends \Magento\Framework\App\Action\Action
{

    public function execute()
    {
        $result = $this->createResultJson();

        $result->setData([
            'message' => 'All Good.'
        ]);

        $result->setHttpResponseCode(200);

        return $result;
    }


    /**
     * @return \Magento\Framework\Controller\ResultInterface|\Magento\Framework\Controller\Result\Json
     */
    protected function createResultJson()
    {
        return $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON);
    }

}
5

To handle the POST method in your controller class, you have to implement the Magento\Framework\App\Action\HttpPostActionInterface interface:

<?php

namespace Vendor\Module\Controller\Api;

use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;

class MyApi extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface
{
    public function execute()
    {
        // ...
    }
}

You can check how the Login controller does it:

vendor/magento/module-customer/Controller/Ajax/Login.php

Also, you should send the Headers correctly, for example:

"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
| improve this answer | |
  • 1
    You made my day. I was banging my head over this customer login API itself. As it was not working. Adding this header "X-Requested-With": "XMLHttpRequest" made it work. – Pandurang Patil Apr 25 at 15:50
1

This solves the problem, but after that your module will not work on Magento 2.2 and earlier https://magento.stackexchange.com/a/255082/75860

| improve this answer | |
0

If you cannot change the headers values, you can do as follows:

Import these classes:

use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;

Implement CsrfAwareActionInterface :

class MyApi extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface

And implement the following methods:

public function createCsrfValidationException(RequestInterface $request): ? InvalidRequestException
{
  return null;
}

public function validateForCsrf(RequestInterface $request): ?bool
{
     return true;
}

Source

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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