Magento – Product POST call to Magento REST API results in 302 and redirect (Nginx)

magento-1.9nginxpost-dataresturl-rewrite

Having an issue when POST'ing to the Magento 1.9 REST API. Magento is being served by Nginx 1.8.0 using OAuth (successfully authenticating).

My Magento rewrite config for the API looks like this:

location /api {
    rewrite ^/api/rest /api?type=rest last;
    }

Creating a product using JSON POST:
http://www.mywebsite.com/api/rest/product

The product is created successfully, but the API responds with HTTP status code 302 and sets the Location header using this function (from app/code/core/Mage/Api2/Model/Resource.php around line 227):

                // The create action has the dynamic type which depends on data in the request body
            if ($this->getRequest()->isAssocArrayInRequestBody()) {
                $this->_errorIfMethodNotExist('_create');
                $filteredData = $this->getFilter()->in($requestData);
                if (empty($filteredData)) {
                    $this->_critical(self::RESOURCE_REQUEST_DATA_INVALID);
                }
                $newItemLocation = $this->_create($filteredData);
                $this->getResponse()->setHeader('Location', $newItemLocation);

This results in the REST client being redirected to the the new location (not what they want). The REST client is expecting a 200 response and Location of newly created resource to be returned in the headers.

I found some other posts where people experienced similar issues and suggested inserting this:

$this->getResponse()->setHttpResponseCode(202);

just after this line:

$this->getResponse()->setHeader('Location', $newItemLocation);

This partially works, but the REST client is expecting a 200, so it thinks the action has failed.

However, if I set a 200 response:

$this->getResponse()->setHttpResponseCode(200);

The API returns a 302 with the Location and redirects the REST client.

After researching, the two possible issues I think are:

  1. Nginx rewriting issue (note: this works as expected when using Apache)
  2. Something to do with PHP apache_request_headers

Thanks!

Best Answer

For anyone running into this, we had the same error for our Magento 1.8.0.0 on NginX. It always returned 302 (even though the post did work). We found this : https://community.magento.com/t5/Programming-Questions/REST-API-issue-created-a-product-success-but-returned-header-404/td-p/14496

And added the line $oauthClient->disableRedirects(); to our Rest Client and it works. Code example (of Rest client):

$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$oauthClient->disableRedirects(); // prevents redirection resulting in 302 error
$resourceUrl = "$apiUrl/myextension/myfunction/{$productId}/";
$oauthClient->fetch($resourceUrl, json_encode($myData), OAUTH_HTTP_METHOD_POST, array(
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
    ));

And the Rest client gets a 200