0

I'm trying to use Dingo API to implement RESTful backend APIs for our webapp. Best practices say that response payload should contain links to the returned resource objects. It can be in the form of _link or href. I don't see a way to include this in the response without handcrafting resource URL. I would like to have the response something like...

[
 { 
  'person': "Joe",
  '_link': 'http://api.mydomain.com/v1/persons/2'
 },
 {
  'person': "Pat",
  '_link': 'http://api.mydomain.com/v1/persons/3'
 }
]

Is there a way I can include a resource link in the response?

donnie
  • 2,981
  • 2
  • 16
  • 24

1 Answers1

1

Are you using transformations to generate your response data. Dingo API uses Fractal as the default transformation layer. So you will need a PersonTransformer for instance as below:

<?php
namespace App\Transformer;

use App\Model\Person;
use League\Fractal;

class PersonTransformer extends Fractal\TransformerAbstract
{
    public function transform(Person $person)
    {
        return [
            'id' => (int) $person->id,
            'person' => $person->name,
            'links' => [
                [
                    'rel' => 'self',
                    'uri' => '/persons/' . $person->id,
                ],
            ],
        ];
    }
}

You can refer to the following link for more information about transformations and how to use them specific to Fractal. Fractal Transformers

tnash
  • 385
  • 4
  • 12
  • Yes, I'm using Transformers. Thank you. This worked. How do I just append the `$person->id` to the current URL? In this case, I have the knowledge of my URI in the Transformer which I would like to avoid so that, it will continue to work when I change the API version on the URI. – donnie May 31 '16 at 10:21
  • One way you can do this is replacing 'uri with the following to get the current request and that will always work when you change the url structure 'uri' => \Request::url() . '/' . $person->id,. However, this may not work correctly when you use includes as well as when you return a single item. So it may not be the job of the api, rather your client should already know the endpoint for the api. If you however still need to provide the absolute path you can use a helper function that returns the endpoint. – tnash May 31 '16 at 16:24
  • Thank you. That makes sense. – donnie Jun 03 '16 at 14:23