Magento – magento 2 custom api return in json without response tag

apijsonmagento2

I have created a custom api following "inchoo" tutorial. But I am getting the data in string format instead of json.

From my browser I am getting a tag surrounding the api return as below.
enter image description here
But Chrome's postman extension showing a double quote ("") and some extra slashes () in the in the response even after header to "Accept":"application/json" and "Content-Type":"application/json".
enter image description here
I just want to receive the exact same string I am returning in my Model class.

 public function name() {
    //return "Hello, raihanruhin";
    $arr = '[{"name":"MasterCard"},{"name":"VISA"}, {"name":"DBBL-NEXUS"}, {"name":"American Express"}]';
    return $arr;
}

Best Answer

Look how Magento 2 handles api response..

class Magento\Framework\Webapi\ServiceOutputProcessor {
...
public function convertValue($data, $type)
{
    if (is_array($data)) {
        $result = [];
        $arrayElementType = substr($type, 0, -2);
        foreach ($data as $datum) {
            if (is_object($datum)) {
                $datum = $this->processDataObject(
                    $this->dataObjectProcessor->buildOutputDataArray($datum, $arrayElementType)
                );
            }
            $result[] = $datum;
        }
        return $result;
    } elseif ...
}

Magento 2 accept array type to response.

$arr = [
    ['name' => 'MasterCard'],
    ['name' => 'VISA'],
    ['name' => 'DBBL-NEXUS'],
    ['name' => 'American Express'],
];
return $arr;

or just..

$arr = '[{"name":"MasterCard"},{"name":"VISA"}, {"name":"DBBL-NEXUS"}, {"name":"American Express"}]';
return json_decode($arr, true);
Related Topic