How to redirect to third party URL from the REST API Response Magento 2?

You can redirect to a third-party URL from the response of the rest API operation in Magento with some simple code snippets.

We can redirect to a third-party URL with a PHP method header(“Location: URL”) in the REST API but this is the not standard way to redirect using the header method in Magento.

Magento\Framework\App\Response\Http class used to redirect to third party URL from the REST API.

Use setRedirect(arg1, arg2) method to redirect to a specific URL using REST API.

arg1 used to define Full URL to redirect.
arg2 is optional, the default value is 302. If you want to move to the permanent URL set 301 in the second argument.

Model Class to response for the Web API method,

<?php
namespace Rbj\WebRestApi\Model;

use Magento\Framework\App\Response\Http;
use Rbj\WebRestApi\Api\ProductUrlInterface;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Exception\NoSuchEntityException;

class RestRedirect implements ProductUrlInterface
{
    /**
     * @var Http
     */
    private $response;

    /**
     * @var ProductRepository
     */
    private $productRepository;

    public function __construct(
        Http $response,
        ProductRepository $productRepository
    ) {
        $this->response = $response;
        $this->productRepository = $productRepository;
    }

    /**
     * Set Product URL to redirect
     * @param string $sku
     * @param int $websiteId
     * @return bool
     * @throws NoSuchEntityException
     */
    public function redirectToProduct(string $sku, int $websiteId): bool
    {
        $redirectSuccess = false;
        try {
            $product = $this->productRepository->get($sku, false, $websiteId);
        } catch (NoSuchEntityException $exception) {
            throw new $exception;
        }

        if ($product) {
            $redirectSuccess = true;
            $productUrl = $product->getProductUrl();
            $this->response->setRedirect($productUrl, 301); // Here second argument optional and default value is 302
        }
        return $redirectSuccess;
    }
}

This is the basic code to redirect to the given URL from the REST API response.

You might be interested to read How to redirect from Observer in Magento 2?