Loadsys has released a CakePHP plugin to aid in the creation of JSON APIs. This plug-in contains a few helpful classes for both the API side and a CakePHP JSON API consumer. This post will cover one of the pieces from that plug-in called the Server Response Component.

Installation

cd app/plugins
git clone git@github.com:loadsys/JSON-API.git json_api

GitHub Repo URL:  http://github.com/loadsys/JSON-API

Setup

In the controller that will serve json (or app_controller if the whole app is serving json) add this to the components array:

public $components = array(‘json_api.ServerResponse’);

Prerequisites

This line of code must be in the app/config/routes.php:

Router::parseExtensions(‘json’);

Overview

The purpose of the Server Response Component is to set appropriate HTTP headers for the API’s response to a consumer’s request. By following some REST conventions, there is little extra work for the API developers.

To set data to be sent with the response, just set it like you normally would in the controller. Just before output of the JSON object, the data set is added to another array under the key ‘response’. Additional information is in the array as siblings to the ‘response’ key, such as controller, action, plugin, status code number, status code string, response message and boolean success.

Additionally, the component will check for pagination settings in the $controller->params[‘paging’]. If they do exist, a header will be set for the different paging settings.

The one important thing to remember is that you must manually set the methodType to a valid method type in the action method. Valid methodType’s are view, add, edit and delete. All that needs to be called for methods that are not named one of the valid method names (i.e. ‘search’) is $this->ServerResponse->setMethodType(‘valid method type’); (in the case of ‘search’, you would set the methodType to ‘view’).

Methods

setMethodType/methodType

Getter and Setter for the $methodType property. The methodType is automatically determined if using a basic CRUD method (view, index, add, edit, delete). If method being called is not one of those, the method type must be explicitly set to a valid type: (view, add, edit, delete). The reason for this is that based on the methodType and the methodSuccess, the responseCode is set to the appropriate REST Convention.

$this->ServerResponse->setMethodType(‘view’);

setMethodSuccess/methodSuccess

Getter and Setter for the $methodSuccess property. The methodSuccess is set to true by default, so it only needs to be set to false when the controller method fails. Optionally, a second parameter can be sent with the setMethodSuccess() method to also set the responseMessage property. See responseMessage below for more information.

$this->ServerResponse->setMethodSuccess(false, $message);

setResponseCode/responseCode

Getter and Setter for the $responseCode property. If the responseCode is set before the the method for generating one is called, then the code that exists will be used. Response codes are generated during the component beforeRender callback.

$this->ServerResponse->setResponseCode(200);

setResponseMessage/responseMessage

Getter and Setter for the $responseMessage property. Same as the resonseCode, if the responseMessage is already set before the responseCode generator is called, then the existing message is used. Otherwise, generic messages are created based on methodType if the methodSuccess is false. If methodSuccess is true and no message is explicitly set, then the message will be null.

$this->ServerResponse->setResponseMessage($message);

Callbacks

string beforeCompareMethodType(string $methodType)

In the components beforeRender method, the methodType, that was determined in initialize method, is checked against valid method types and the request type. If the method type does not match a valid method type for the right request type, the response code is set to 405 Method Not Allowed and the response is rendered. An example would be if the method type was ‘edit’, but the request type was GET. This call back is called just before the comparison, and is the last chance to modify the method type. Whatever string is returned is set to the methodType property.

array beforeSetResponseInfo(array $params)

Just after the response code is automatically generated, but before the value is set to properties, this callback is called. The array passed in contains 3 keys: ‘status’, ‘message’, ‘success’. This is the last chance to modify responseCode, responseMessage and methodSuccess. Return an array with the same keys as the parameter array.

array beforeJsonRender(array $array)

This is the last method called before the component echo’s the JSON encoded response data and exits. The array passed into the method is the return data that will be set to the ‘response’ key in the array that gets json_encoded(). Whatever array is returned will be set in place of the return data that currently exists.

Code Example

<?php

class ExampleController extends AppController {

      public $components = array(‘json_api.ServerResponse’);      
      public function index() {
            $var = $this->paginate();
            if (empty($var)) {
                  $this->ServerResponse->setMethodSuccess(false, ‘Example empty’);
            }
            $this->set(compact(‘var’));
      }
}
?>

 

Joey Trapp
Web Developer
Loadsys