Question

I'm working on building REST API which will return data of regions. API is working as expected but problem I'm facing is its 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's 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'm triggering API with above code it returns like,

"{\"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 ?

No correct solution

OTHER TIPS

Try with below code

$data = [
    'status' => true,
    'message' => 'We will let you know!'
];

$response[] = $data;
return $response;

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top