Api: How to add success to every responce?

Created on 6 Oct 2016  路  17Comments  路  Source: dingo/api

Hello!

I want to add success responce to every API call. If we have an error, success: false and if all is OK, then success: true.

Final responce must looke like this:

{
"success":true,
"data": [{}, {}]
}

How to do that?

Most helpful comment

I implemented it as @tantam already said. I prefer to put my implementation here for those person who was searching the solution.

Step 1. Create an event listener in your app/Listeners, it was named AddWrapToResponse in my example:

use Dingo\Api\Event\ResponseWasMorphed;

class AddWrapToResponse
{
    public function handle(ResponseWasMorphed $event)
    {
        if ($event->response->isSuccessful())
        {
            $data = $event->response->content();
            $event->response->setContent(json_encode([
                'code' => 0,
                'success' => TRUE,
                'data' => $data,
            ]));
        }
    }
}

Step 2. Register the created event listener into your app/Providers/EventServiceProvider as below:

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use App\Listeners\AddWrapToResponse;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'Dingo\Api\Event\ResponseWasMorphed' => [
            AddWrapToResponse::class,
        ]
    ];
}

After these two steps, all response from your dingo api would be enveloped with your custom data.

All 17 comments

@Sogl,I have same problem , Have you reached a result?

I guess (!!!), that you need to write your own transformer.. Take a look at this wiki entry here!
Custom Transformers

It may help you?!

@johannesschobel All transfomer manipulation add lines into "data" JSON section, but I need "success" near this section.

yeah, but would that be a problem?
Your JSON response would look like this:

{
   "data" : {
      "success" : true,
      "foo" : "bar",
   }
}

another way of doing this, would be to use the setMeta() function of the response. Using this method, you can apply a meta block. In this block, for example, pagination information (what page are you on, how many items are displayed on one page, ...) is stored..

You can simply append your own meta information either by using setMeta() (overwrite the meta block) or by using addMeta() (append to meta block)...

Both methods can be found in the Response class of Dingo/api:
setMeta
addMeta

but would that be a problem?

@johannesschobel , To simplify More. in most of major API that I checked there is comes a simple key like ok or success with a boolean value that shown result status In short. in the other hand, front-end developer has a simpler task too

@johannesschobel So... I use setMeta now where pagination also present and in my frontend framework I set check meta.success.

But things gets complicated. Why I can't simple change server responce in my own way, without hacking?
I need to put the same code in every responce... can I do that in one place when success and no errors?

@ahmadbadpey and @Sogl
that is - at least in my opinion - not good practice, because you should use HTTP status codes for this case.. e.g. 200 means ok (or in your case success), if there is an error in the request (e.g., the requestor asks for an entity that is not available) you should throw a 404 (not found) and so on!

You are trying to "rebuild" functionality, which is already available through common HTTP standards. Why not check the HTTP status of the response?!

It's additional data, not for replace status codes.
ExtJS frontend framework need that data.

then put it in the meta block, as it does not belong to your original data you want to transfer!

Question was "how to put new data near the data block?", not into meta block.

@Sogl how are you letting the response(s) be generated? Just returning models and letting the framework / dingo handle it?

@hskrasek I don't understand what you talking about.. can you rephrase, please?
I explained what I want in the 1st message.

You can follow this article https://github.com/dingo/api/wiki/Responses#morphing-and-morphed-events
Listen to the event and check their status code (or whatever data that you defined) and add what you want to response, example with "AddPaginationLinksToResponse" is clear and you can follow it

i have the same question , Have you reached a result?

I do have same doubt, is anyone knows how we can achieve this?

I implemented it as @tantam already said. I prefer to put my implementation here for those person who was searching the solution.

Step 1. Create an event listener in your app/Listeners, it was named AddWrapToResponse in my example:

use Dingo\Api\Event\ResponseWasMorphed;

class AddWrapToResponse
{
    public function handle(ResponseWasMorphed $event)
    {
        if ($event->response->isSuccessful())
        {
            $data = $event->response->content();
            $event->response->setContent(json_encode([
                'code' => 0,
                'success' => TRUE,
                'data' => $data,
            ]));
        }
    }
}

Step 2. Register the created event listener into your app/Providers/EventServiceProvider as below:

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use App\Listeners\AddWrapToResponse;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'Dingo\Api\Event\ResponseWasMorphed' => [
            AddWrapToResponse::class,
        ]
    ];
}

After these two steps, all response from your dingo api would be enveloped with your custom data.

@Sogl You can use

return $this->response->array(['success' => true, 'data' => $data]);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Kirtsen picture Kirtsen  路  3Comments

sukh-gill picture sukh-gill  路  3Comments

lloricode picture lloricode  路  3Comments

adrian-fjellberg picture adrian-fjellberg  路  4Comments

BartHuis picture BartHuis  路  3Comments