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, 2019 at 9:18
  • maybe put your type_redirect inside your execute method
    – fmsthird
    Feb 14, 2019 at 9:19
  • There is no execute method... it's a REST API, not a controller...
    – Pini
    Feb 14, 2019 at 9:22

2 Answers 2


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(

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

  • i was struck with this can u plz help to solve it @Ram Feb 14, 2019 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, 2019 at 7:35
  • Welcome @Pini :) Feb 17, 2019 at 16:51

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

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.