1

I have an API endpoint that expects a GET request.
On some scenarios, I want to be able to perform a redirect instead of responding with a result.

e.g., If you'll open the API endpoint URL in a browser, you'll be redirected to a specific page.

  • I KNOW that I can use a controller for that instead of REST API, but this is the current situation & I need to solve it without changing the endpoint URL.
  • I tried to use Magento\Framework\Controller\ResultFactory & return a TYPE_REDIRECT response from the API method, but it just returns an empty array & not redirecting.

Any idea?

  • post your execute function with the code – fmsthird Feb 14 '19 at 9:18
  • maybe put your type_redirect inside your execute method – fmsthird Feb 14 '19 at 9:19
  • There is no execute method... it's a REST API, not a controller... – Pini Feb 14 '19 at 9:22
0

You can give a try to this. Create a around plugin of Magento\Webapi\Controller\Rest class. Your around plugin will look like below.

 public function __construct(
    \Magento\Framework\Message\ManagerInterface $messageManager,
    \Magento\Framework\Controller\ResultFactory $resultFactory,     
    \Magento\Framework\App\Response\RedirectInterface $redirect     
    ) 
{
    $this->messageManager = $messageManager;
    $this->resultFactory = $resultFactory;
    $this->redirect = $redirect;
}

public function aroundExecute(\Magento\Webapi\Controller\Rest $subject, $proceed) 
{
    $resultRedirect = $this->resultFactory->create(
            \Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT
        );

    You can check request type from native $_SERVER['HTTP_USER_AGENT']
    if(Your condition)
    {
       $this->messageManager->addWarningMessage(__('You cannot access the endpoint browser directly.'));
       $result = $resultRedirect->setUrl($this->redirect->getRefererUrl());
    } else {
        $result = $proceed();
    }

    return $result;

}

}

I don't know if it can be done with before plugin. Let me know if you need further help. Happy Coding :)

| improve this answer | |
  • i was struck with this can u plz help to solve it @Ram – divya sekar Feb 14 '19 at 12:29
  • Seems a bit too much to me, I hoped that there's an out-of-the-box way to achieve that. But thanks for the idea. – Pini Feb 17 '19 at 7:35
  • Welcome @Pini :) – Ramkishan Suthar Feb 17 '19 at 16:51
0

Please, check this implementation for REST API endpoint

public function __construct(
    \Magento\Framework\App\ResponseInterface $response
) {
    $this->response = $response;
}

// Your handling method
public function handle() {
    $this->response->setRedirect('...YOUR URL...')->sendResponse();
}
| 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.