Rest Controller

What is a Rest controller?

A Rest Controller is an extension of the Base Controller which has RESTful support built in. This will allow you to build API's with ease.

Please note: if you have a before() or router method in your REST controller extension you must call the parent method parent::before() (or router) for it to keep working properly.

Using the Rest controller

Like all Controllers, you create a class in the fuel/app/classes/controller directory. They need to extend the Controller_Rest class and are prefixed by default by "Controller_". Below is an example of the controller "test":

class Controller_Test extends Controller_Rest
{

	public function get_list()
	{
		return $this->response(array(
			'foo' => Input::get('foo'),
			'baz' => array(
				1, 50, 219
			),
			'empty' => null
		));
	}
}

This controller method "list" is called by the following URL:

http://localhost/test/list.json?foo=bar

You'll notice that instead of the usual "action_" prefix the Rest Controller uses the HTTP method as a prefix. When no method with the corresponding HTTP method prefix is found it will fall back to the "action_" prefix. All common HTTP methods are supported by the Rest Controller, such as:

HTTP Method Description
GET Used to fetch information about an existing resource. This is used by browsers when you enter a URL and hit go, or when you click on a link, so it perfect for fetching information on one of your resources (like user). Forms can also use this method to fetch information submitting a query string (i.e. Search forms).
POST Used to create a new resource. It is also used to update a resource because of the lack of HTML support for the PUT method. Most forms use POST method except when their intend is to fetch information submitting a query string.
PUT Used to create or update a resource with a known id. You are expected to pass all properties. Missing ones should be set to NULL. Less commonly used as it is not yet supported by HTML (v.5). It is although supported for XMLHttpRequests by most browsers.
DELETE Used to delete an existing resource. As for PUT, it is not supported by HTML (v.5) but supported for XMLHttpRequests by most browsers.
PATCH Used to update a resource with a known id. You only pass properties you want to update. Less commonly used as it is not yet supported by HTML (v.5). It is although supported for XMLHttpRequests by most browsers.

This is not a restrictive list, the FuelPHP framework accepts any HTTP method accepted by your webserver.

Output

{
	"foo":"bar",
	"baz":[1,50,219],
	"empty":null
}

This is output as json because a file extension was defined in the URL. By default, responses will be formatted as XML or whichever format is set in fuel/core/config/rest.php.

Configuration

The REST controllers can be globally configured via the fuel/core/config/rest.php configuration file. It is already populated with a default configuration. You can override this configuration adding a config file with the same name to your application config directory, and set the values you want to change there. These will overwrite the core config but keep what you didn't overwrite.

The following global configuration values can be defined:

Param Type Default Description
default_format string
'xml'
The default format to return the result in. This will only be used when no format is defined in the controller, and all autodetection mechanisms fail.
xml_basenode string
'xml'
The basenode XML tag to be used when outputting XML structures.
realm string
'REST API'
The name for the password protected REST API displayed on login dialogs.
auth string
''
Defines the type of authentication needed. Valid values are 'basic' and 'digest'. You can also define a name of controller method which must be called to check authorization. This method may return a boolean (true will allow the request, false will return a default 401 response is returned), or a Response object.
Leave this empty if no autorization need to be performed.
valid_logins array
array('admin' => '1234')
An array of key/value pairs, defining valid usernames and passwords for the 'basic' and 'digest' authorization methods.
ignore_http_accept boolean
false
Whether or not the HTTP_ACCEPT header should be parsed on a REST request to determine the format to return.

Supported Formats

If your controller method returns an array, but the requested output format is something that an array can not be converted to (such as html), you will get a 406 NOT ACCEPTABLE status returned when your application runs in a production environment, or a warning message and a JSON dump of the array when in any other environment.

Format determination

To determine the format in which the result should be returned, the REST controller uses the following algorithm:

In most cases the HTTP_ACCEPT is present and contains (at least) text/html, which is a valid result format. This has the implication that the $rest_format, and any global default defined in the rest.php configuration file, will never be used.

To disable the HTTP_ACCEPT as a valid format source, set the configuration key ignore_http_accept in the rest.php to true.

Note that it is considered bad practice to hardcode any result format in your REST controller. It should be up to the client to specify in which format the result should be returned. In case of HTTP_ACCEPT, most ajax solutions like for example jQuery.ajax() allow you to set the accept header to application/json.

XML Base Node Name

When using XML output you can set the XML basenode by setting the $xml_basenode param.

class Controller_Test extends Controller_Rest
{
	// Set it for the whole controller
	protected $xml_basenode = 'my_basenode';

	// Or inside your controller function
	public function get_items()
	{
		$this->xml_basenode = 'other_basenode';

		return $this->response(array(
			'foo' => Input::get('foo'),
			'baz' => array(
				1, 50, 219
			),
			'empty' => null
		));
	}
}

Special controller methods

response($data = array(), $http_code = 200)

This method is used to send your response data through the formatting and output logic. You can optionally set a status code as the 2nd parameter.