Magento – Magento 2 – How to return custom json response from API

apimagento2response

I'm working with Magento 2 API and I'm really struggled with response of it

How can I return some kind of response like this:

{
    "status": 200,
    "error": false,
    "message": "Request processed successfully.",
    "data": {
        "id": "1",
        "email": "us@test.com",
        "first_name": "user1",
        "last_name": "user01"
    }
}

It's simple with other framework like Laravel or Express. But it seems really hard to achieve this with Magento 2 API.

Anyone has idea?
Thank you.

Best Answer

First you need to define the interface/class of the result type. The interface will look like this.

namespace Vnecoms\SampleAPI\Api;

interface Result
{
    /**
     * @return int
     */
    public function getStatus();

    /**
     * @return bool
     */
    public function getError();

    /**
     * @return string
     */
    public function getMessage();

    /**
     * @return \Vnecoms\SampleAPI\Api\ResultData
     */
    public function getData();
}

Next is the ResultData interface

namespace Vnecoms\SampleAPI\Api;

interface ResultData
{
    /**
     * @return int
     */
    public function getId();

    /**
     * @return string
     */
    public function getEmail();

    /**
     * @return string
     */
    public function getFirstName();

    /**
     * @return string
     */
    public function getLastName();
}

Now in your API just return an object of \Vnecoms\SampleAPI\Api\Result