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).


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

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

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

            'message' => 'All Good.'


        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);


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


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:


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

"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
  • 2
    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 '20 at 15:50

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;



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

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.