Setup HATEOAS hal+json API responses

I’m busy setting up HAL on our API (see the spec here http://stateless.co/hal_specification.html), which we’re building in Symfony 3. We have used the FOSRestBundle, and JMS Serialiser to set up the API to begin with, and the incredible Swagger for documenting it.

If you aren’t using Symfony, you can integrate this package yourself:

composer require willdurand/hateoas

And if you do use Symfony, there’s a bundle.

composer require willdurand/hateoas-bundle

Register the bundle in app/AppKernel.php.

// .. in array of bundles
new Bazinga\Bundle\HateoasBundle\BazingaHateoasBundle(),

Self Link

Open your entity, add the use statement,  and edit the class DocBlock:

use Hateoas\Configuration\Annotation as Hateoas;
@Hateoas\Relation("self", href = "expr('/employees/' ~ object.getId())")

This annotation says that the REST link to an employee is /employees/:id.

Collections with pagination links

Here’s a testAction I made in my EmployeeController:

/**
 * @Rest\Post("/employees/test/test")
 *
 * @SWG\Post(
 *     path="/employees/test/test",
 *     description="Fake call for testing purposes",
 *     operationId="test",
 *     produces={"application/hal+json"},
 *     tags={"employees"},
 *     @SWG\Parameter(
 *         name="page",
 *         in="query",
 *         type="integer",
 *         description="the page you want",
 *         required=false,
 *         default=1
 *     ),
 *     @SWG\Parameter(
 *         name="limit",
 *         in="query",
 *         type="integer",
 *         description="the number of results per page",
 *         required=false,
 *         default=1
 *     ),
 *     @SWG\Response(
 *         response=200,
 *         description="Returned when successful",
 *         @SWG\Schema(ref="#/definitions/listEmployee")
 *     ),
 *     @SWG\Response(
 *         response="default",
 *         description="unexpected error",
 *         @SWG\Schema(
 *             ref="#/definitions/ErrorModel"
 *         )
 *     )
 * )
 *
 *
 * @return PaginatedRepresentation
 */
public function testAction(Request $request)
{
    $page = $request->get('page') ?? 1;
    $numPerPage = $request->get('limit') ?? 1;

    $co = new Company();
    $co->setName('KGB Inc.')
       ->setCode(999999.1);
    $employee = new Employee();
    $employee
        ->setCompany($co)
        ->setId(666)
        ->setEmployeeId(999)
        ->setName('Vladimir Putin');

    $collection = new EntityCollection();
    $collection->add($employee);

    $co = new Company();
    $co->setName('MAGA Inc.')
       ->setCode(999999.1);
    $employee = new Employee();
    $employee
        ->setCompany($co)
        ->setId(999)
        ->setEmployeeId(666)
        ->setName('Donald J Trump');

    $collection->add($employee);

    $numPages = ceil (count($collection) / $numPerPage);

    $filter = new CollectionFilter();
    $filter->getPaginationFilter()
        ->setNumPerPage(1)
        ->setPage($page);

    $collection = $filter->filterArrayResults($collection->toArray());

    $halCollection = new CollectionRepresentation(
        $collection,
        'employees',
        'employees'
    );

    $pager = new PaginatedRepresentation(
        $halCollection,
        'test',
        array(),
        $page,
        $numPerPage,
        $numPages
    );

    return $pager;
}

There’s quite a bit here, but let me explain.

The @Rest\Post(“/employees/test/test”) annotation is the FOSRestBundle. When we call thae URL, it ensures we send POST otherwise we get a 405 response.

The @SWG stuff is Swagger documentation annotation, which hopefully should be self explanatory. The only part you might question is the Schema, which you docblock annotate in the entity class itself. See full Swagger docs for that, but here’s our annotation for a single employee:

* @SWG\Definition(
*   definition="singleEmployee",
*   type="object",
*   allOf={
*       @SWG\Schema(
*           @SWG\Property(property="id", type="integer"),
*           @SWG\Property(property="employeeId", type="integer"),
*           @SWG\Property(property="name", type="string"),
*           @SWG\Property(property="firstName", type="string"),
*           @SWG\Property(property="company",type="object", ref="#/definitions/singleCompany"),
*           @SWG\Property(property="functionDescription", type="string"),
*           @SWG\Property(property="nationalRegisterNumber", type="string"),
*       ),
*   }
* )

@return PaginatedRepresentation returns our collection, wrapped in HAL stuff now.

In the method itself, I create two fake employees (Trump & Putin), add them to the EntityCollection, then I run CollectionFilter on it (https://github.com/delboy1978uk/collection-filter, which I made last week as a filter/paginator system for working with full resultsets). So the interesting bit is $halCollection & $pager. We pass our $collection into CollectionRepresentation, and pass that into PaginatedRepresentation.

So now, we go to https://api.yoursite.com/docs, try our endpoint, and you should see…

Screen Shot 2017-10-30 at 4.43.34 PM

Have fun! 😀

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s