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": "[email protected]",
"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– PY Yick2017年06月16日 14:50:00 +00:00Commented Jun 16, 2017 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 expected0xh8h– 0xh8h2017年06月16日 15:16:22 +00:00Commented Jun 16, 2017 at 15:16
-
I didn't try as I don't need to do so, just a reference for you.PY Yick– PY Yick2017年06月16日 15:33:13 +00:00Commented Jun 16, 2017 at 15:33
-
have u found any solution for this in magento2?Nagaraju Kasa– Nagaraju Kasa2017年12月16日 09:42:04 +00:00Commented Dec 16, 2017 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 :)0xh8h– 0xh8h2017年12月18日 03:06:04 +00:00Commented Dec 18, 2017 at 3:06
1 Answer 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?anon– anon2017年09月05日 07:12:58 +00:00Commented Sep 5, 2017 at 7:12
-
I write down the interface only. You will need to define your own class follows the interface above.Hungvt– Hungvt2017年09月07日 16:13:45 +00:00Commented Sep 7, 2017 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– Pini2019年01月15日 12:12:17 +00:00Commented Jan 15, 2019 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– domdambrogia2019年03月19日 17:40:45 +00:00Commented Mar 19, 2019 at 17:40