Reputation: 360
For Magento 1.9 I'm working on a module where I defined a custom REST route to retrieve all categories with subcategories. When I call <MAGE>/api/rest/eoarestapi/categories?type=rest
the function _retrieveCollection()
from the class Namespace_Restapi_Model_Api2_Category_Rest_Guest_V1
is being called. So far so good.
Now I am having the problem, that it returns the response in XML only and when I set the header explicitly to Accept: application/json
, then I get the error 406 Not Acceptable An appropriate representation of the requested resource /api/rest/products could not be found on this server. Available variants: api.php , type application/x-httpd-php
This seems very strange to me as I can remember having worked with JSON response back in Magento 1.8.
As a fix I found this and that solution to retrieve JSON which works, but it doesn't seem to be a nice solution as it looks like it disables XML response completely.
Is there a better way to enable JSON output from the REST API in Magento 1.9? Does anybody have some background knowledge on this?
Upvotes: -1
Views: 5290
Reputation: 91
First I defined @return mixed in my API interface
and than in your model I do this
$response = ['success' => 'ok', 'message' => 'json format'];
header('Content-Type: application/json');
echo json_encode($response); exit;
Upvotes: 1
Reputation: 2819
I achieved this by overriding my request model. My Steps are following:
1:Declare new module : Create app/etc/modules/Custom_RestJson.xml
<?xml version="1.0"?>
<config>
<modules>
<Custom_RestJson>
<active>true</active>
<codePool>local</codePool>
</Custom_RestJson>
</modules>
</config>
2. Create /app/code/local/Custom/RestJson/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Custom_RestJson>
<version>1.0.0</version>
</Custom_RestJson>
</modules>
<global>
<models>
<Custom_RestJson>
<class>Custom_RestJson_Model</class>
</Custom_RestJson>
<api2>
<rewrite>
<request>Core_Mage_Api2_Model_Request</request>
</rewrite>
</api2>
</models>
</global>
</config>
3. Create /app/code/local/Custom/RestJson/Model/Api2/Request.php
<?php
class Custom_RestJson_Model_Api2_Request extends Mage_Api2_Model_Request{
public function getAcceptTypes()
{
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
return array_keys(array("application/json" => 1));
}
}
Upvotes: 0