Return JSON response instead of JSON String
-
05-05-2021 - |
Question
I am working on building REST API which will return data of regions. API is working as expected but problem I am facing is, it is returning response with JSON string and not able to parse that. Would like to get JSON response.
webapi.xml
<route url="/V1/getRegions" method="GET">
<service class="Vendor\Module\Api\RegionsInterface" method="getRegions"/>
<resources>
<resource ref="self"/>
</resources>
</route>
Interface
<?php
namespace Vendor\Module\Api;
interface RegionsInterface
{
/**
* @return mixed
*/
public function getRegions();
}
Next I added preference for interface and here is that class.
<?php
declare(strict_types=1);
namespace Vendor\Module\Model;
use Vendor\Module\Api\RegionsInterface;
class Regions implements RegionsInterface
{
public function getRegions()
{
$data = [
'status' => true,
'message' => 'We will let you know!'
];
return json_encode($data);
}
}
When I am triggering API with above code, it returns like this,
"{\"status\":true,\"message\":\"We will let you know!\"}"
I want response to be like,
{"status":true,"message":"We will let you know!"}
Any idea how to achieve this ?
Solution
Try with below code
$data = [
'status' => true,
'message' => 'We will let you know!'
];
$response[] = $data;
return $response;
OTHER TIPS
The concept of repository pattern comes here. Instead of returning a string, your API call should return Object. Refer how Magento's '/V1/customers/:customerId/billingAddress' API of Magento_Customer module works. It might give you some insight. It is a good starting point.
Also I found this content useful for API development - https://webkul.com/blog/magento2-custom-rest-api/
Try to strip slashes and other useless things from string
Try something like this
$response="{\"status\":true,\"message\":\"We will let you know!\"}";
$response=stripslashes($response);
echo $response;