I used the resources in “Creating a New REST Web Service in Magento 2” and “Creating a New REST Web Service in Magento 2” to create a custom API module, but the response is in XML format. I need a response in JSON format with key value pairs. How can I do this?
4 Answers
Below are the custom api module with key pair value
To get JSON response, in client set Response headers to "Content-Type: application/json; charset=utf-8"
and if you need key pair value that is in response should have key and value as like /rest/V1/categories
we need to create data interface
To test in Chrome download plugin called rest client app call the url
below module url will be http://yourdomein.com/magento2/rest/V1/getinfo
app\code\Sugarcode\Customapi\registration.php:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Sugarcode_Customapi',
__DIR__
);
app\code\Sugarcode\Customapi\etc\module.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Sugarcode_Customapi" setup_version="2.0.0"/>
</config>
app\code\Sugarcode\Customapi\etc\di.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Sugarcode\Customapi\Api\TestInterface"
type="Sugarcode\Customapi\Model\Test" />
<preference for="Sugarcode\Customapi\Api\Data\TestdataInterface" type="Sugarcode\Customapi\Model\Testmodel" />
</config>
app\code\Sugarcode\Customapi\etc\webapi.xml:
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<!-- Example: curl http://127.0.0.1/index.php/rest/V1/calculator/add/1/2 -->
<route url="/V1/getinfo" method="GET">
<service class="Sugarcode\Customapi\Api\TestInterface" method="getinfo" />
<resources>
<resource ref="anonymous" />
</resources>
</route>
</routes>
app\code\Sugarcode\Customapi\Api\TestInterface.php:
<?php
namespace Sugarcode\Customapi\Api;
use Sugarcode\Customapi\Api\Data\TestdataInterface;
interface TestInterface
{
/**
* Retrieve list of info
*
* @throws \Magento\Framework\Exception\NoSuchEntityException If ID is not found
* @return \Sugarcode\Customapi\Api\Data\TestdataInterface containing Tree objects
*/
public function getinfo();
}
don't remove comments its most important
app\code\Sugarcode\Customapi\Api\Data\TestdataInterface.php (set and get data):
<?php
namespace Sugarcode\Customapi\Api\Data;
/**
* @api
*/
interface TestdataInterface
{
/**
* Get name
*
* @return string
*/
public function getName();
/**
* Set name
*
* @param string $name
* @return $this
*/
public function setName($id);
}
app\code\Sugarcode\Customapi\Model\Test.php:
<?php
namespace Sugarcode\Customapi\Model;
use Sugarcode\Customapi\Api\TestInterface;
/**
* Defines the implementaiton class of the calculator service contract.
*/
class Test implements TestInterface
{
/**
* Return the sum of the two numbers.
*
* @api
* @param int $num1 Left hand operand.
* @param int $num2 Right hand operand.
* @return int The sum of the two values.
*/
protected $dataFactory;
public function __construct(\Sugarcode\Customapi\Api\Data\TestdataInterfaceFactory $dataFactory)
{
$this->dataFactory = $dataFactory;
}
public function getinfo() {
$page_object = $this->dataFactory->create();
$page_object->setName('Hello');
return $page_object;
}
}
app\code\Sugarcode\Customapi\Model\Testmodel.php:
<?php
namespace Sugarcode\Customapi\Model;
class Testmodel extends \Magento\Framework\Model\AbstractModel implements
\Sugarcode\Customapi\Api\Data\TestdataInterface
{
const KEY_NAME = 'name';
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
public function getName()
{
return $this->_getData(self::KEY_NAME);
}
/**
* Set name
*
* @param string $name
* @return $this
*/
public function setName($name)
{
return $this->setData(self::KEY_NAME, $name);
}
}
-
This is by far the best way to handle json key value pair response. I know you have another solution here magento.stackexchange.com/questions/94618/… but it seems not a natural approach. Thank you.– 0xh8hCommented Jun 19, 2017 at 9:14
-
Response format (XML or JSON) is selected based on Accept
header, set it to application/json
on the client side.
-
:- if i put api url (get method )in browser it coming in xml format, how to make it in json format is there any option to set response format Commented Dec 21, 2015 at 8:42
-
If you need this just for testing/dev purposes, remove all renderers except for JSON in
Magento/Webapi/etc/di.xml
. Otherwise use some plugin for browser to set proper headers (e.g. REST client for Firefox). Anyway, it is possible to access only 'anonymous' resources withoutAuthorization
header. Commented Dec 21, 2015 at 9:08 -
is it mandatory api/data for node that i in array i want to key pair value in that case how to do with out data folder Commented Dec 21, 2015 at 9:25
-
1
-
when i call my api i need response in key value pair , for that in core module they wrote api/data interface , with out that can we end back response with key pair value as like above screen shot of categories Commented Dec 21, 2015 at 9:35
Use a cURL :
$URL = curl_init( $www );
curl_setopt( $URL, CURLOPT_HEADER, 0 );
curl_setopt( $URL, CURLOPT_CUSTOMREQUEST, "GET" );
curl_setopt( $URL, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $URL, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Authorization: Bearer " . $token_API
) );
In this step on json_decode()
PHP function, the second paramter true
returns JSON in array fortmat, see more: http://php.net/json_decode
$URL = json_decode(curl_exec($URL), true);
And then:
curl_close( $URL ); //close cURL conn
print_r( $URL ); //result
-
1how can i get this $token_API of customer programmatically?– NewbieCommented Mar 31, 2017 at 13:34
-
@Newbie Get an admin token POST /V1/integration/admin/token integrationAdminTokenServiceV1 Get a customer token POST /V1/integration/customer/token integrationCustomerTokenServiceV1 If you get this programmatucally create a PHP Script and request from API URL land Take a Return Value From WEB API. Font: devdocs.magento.com/guides/v2.0/get-started/authentication/… Commented Mar 31, 2017 at 15:02