magentooauth-2.0magento-1.7magento-1.4magento-rest-api

How to get Response of REST API in JSON format by Default in Magento


In magento as we use the REST url to access the data,as http://localhost/magemto/api/rest/products it returns in XML format.

But as my team requirement, I should send the data in JSON format to access AJAX calls easily.. I have used REST client to include a header as 'Content-Type:appilcation/json'.. Then it returns in JSON format.. But I want it as defaultly by the magento API..


Solution

  • Hey, I do have a solution for this, I would like to share with you.

    First go to your magento root folder then go to following path

    \app\code\core\Mage\Api2\Model\Request.php

    Go to the method getAccepTypes() and change with this code below it will fulfill your requirement.

    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;
        }
    
        unset($orderedTypes);
        $orderedTypes=Array
            ("application/json" => 1);
    
        return array_keys($orderedTypes);
    }
    

    Hope this help you.