2

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.

  • Give you a reference first, you can edit the format as you like: magento.stackexchange.com/questions/92105/… – PY Yick Jun 16 '17 at 14:50
  • Thank you. But did you try this? I tried, at the moment, this interface has only one method left, it is sendResponse. And it seems not work as we expected – Hoang Trinh Jun 16 '17 at 15:16
  • I didn't try as I don't need to do so, just a reference for you. – PY Yick Jun 16 '17 at 15:33
  • have u found any solution for this in magento2? – Nagaraju Kasa Dec 16 '17 at 9:42
  • @NagarajuKasa: No, I didn't find the kind of solution I needed. And I had to use response format that Magento team force us to use :) – Hoang Trinh Dec 18 '17 at 3:06
-1

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

  • how to return it? – Robert Limanto Sep 5 '17 at 7:12
  • I write down the interface only. You will need to define your own class follows the interface above. – Hungvt Sep 7 '17 at 16:13
  • @Hungvt, Is it possible to build that data interface without a getter method for every field? (What can you do when you have, for example, 200 fields? or dynamic number of fields?) – Pini Jan 15 at 12:12
  • This is a terrible answer. This doesn't explain anything other than how to create an interface for a few necessary fields. – domdambrogia Mar 19 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.