API Response Trait

Much of modern PHP development requires building API’s, whether simply to provide data for a javascript-heavysingle page application, or as a standalone product. CodeIgniter provides an API Response trait that can beused with any controller to make common response types simple, with no need to remember which HTTP status codeshould be returned for which response types.

Example Usage

The following example shows a common usage pattern within your controllers.

  1. <?php namespace App\Controllers;
  2.  
  3. use CodeIgniter\API\ResponseTrait;
  4.  
  5. class Users extends \CodeIgniter\Controller
  6. {
  7. use ResponseTrait;
  8.  
  9. public function createUser()
  10. {
  11. $model = new UserModel();
  12. $user = $model->save($this->request->getPost());
  13.  
  14. // Respond with 201 status code
  15. return $this->respondCreated();
  16. }
  17. }

In this example, an HTTP status code of 201 is returned, with the generic status message, ‘Created’. Methodsexist for the most common use cases:

  1. // Generic response method
  2. respond($data, 200);
  3. // Generic failure response
  4. fail($errors, 400);
  5. // Item created response
  6. respondCreated($data);
  7. // Item successfully deleted
  8. respondDeleted($data);
  9. // Command executed by no response required
  10. respondNoContent($message);
  11. // Client isn't authorized
  12. failUnauthorized($description);
  13. // Forbidden action
  14. failForbidden($description);
  15. // Resource Not Found
  16. failNotFound($description);
  17. // Data did not validate
  18. failValidationError($description);
  19. // Resource already exists
  20. failResourceExists($description);
  21. // Resource previously deleted
  22. failResourceGone($description);
  23. // Client made too many requests
  24. failTooManyRequests($description);

Handling Response Types

When you pass your data in any of these methods, they will determine the data type to format the results as based onthe following criteria:

  • If $data is a string, it will be treated as HTML to send back to the client.
    • If $data is an array, it will try to negotiate the content type with what the client asked for, defaulting to JSON
    • if nothing else has been specified within ConfigAPI.php, the $supportedResponseFormats property.

To define the formatter that is used, edit Config/Format.php. The $supportedResponseFormats contains a list ofmime types that your application can automatically format the response for. By default, the system knows how toformat both XML and JSON responses:

  1. public $supportedResponseFormats = [
  2. 'application/json',
  3. 'application/xml'
  4. ];

This is the array that is used during Content Negotiation to determine whichtype of response to return. If no matches are found between what the client requested and what you support, the firstformat in this array is what will be returned.

Next, you need to define the class that is used to format the array of data. This must be a fully qualified classname, and the class must implement CodeIgniter\Format\FormatterInterface. Formatters come out of the box thatsupport both JSON and XML:

  1. public $formatters = [
  2. 'application/json' => \CodeIgniter\Format\JSONFormatter::class,
  3. 'application/xml' => \CodeIgniter\Format\XMLFormatter::class
  4. ];

So, if your request asks for JSON formatted data in an Accept header, the data array you pass any of therespond or fail methods will be formatted by the CodeIgniter\API\JSONFormatter class. The resultingJSON data will be sent back to the client.

Class Reference

  • respond($data[, $statusCode=200[, $message='']])

Parameters:

  • $data (mixed) – The data to return to the client. Either string or array.
  • $statusCode (int) – The HTTP status code to return. Defaults to 200
  • $message (string) – A custom “reason” message to return.

This is the method used by all other methods in this trait to return a response to the client.

The $data element can be either a string or an array. By default, a string will be returned as HTML,while an array will be run through json_encode and returned as JSON, unless Content Negotiationdetermines it should be returned in a different format.

If a $message string is passed, it will be used in place of the standard IANA reason codes for theresponse status. Not every client will respect the custom codes, though, and will use the IANA standardsthat match the status code.

Note

Since it sets the status code and body on the active Response instance, this should alwaysbe the final method in the script execution.

  • fail($messages[, int $status=400[, string $code=null[, string $message='']]])

Parameters:

  • $messages (mixed) – A string or array of strings that contain error messages encountered.
  • $status (int) – The HTTP status code to return. Defaults to 400.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:A multi-part response in the client’s preferred format.

The is the generic method used to represent a failed response, and is used by all of the other “fail” methods.

The $messages element can be either a string or an array of strings.

The $status parameter is the HTTP status code that should be returned.

Since many APIs are better served using custom error codes, a custom error code can be passed in the thirdparameter. If no value is present, it will be the same as $status.

If a $message string is passed, it will be used in place of the standard IANA reason codes for theresponse status. Not every client will respect the custom codes, though, and will use the IANA standardsthat match the status code.

The response is an array with two elements: error and messages. The error element contains the statuscode of the error. The messages element contains an array of error messages. It would look something like:

  1. $response = [
  2. 'status' => 400,
  3. 'code' => '321a',
  4. 'messages' => [
  5. 'Error message 1',
  6. 'Error message 2'
  7. ]
  8. ];
  • respondCreated($data = null[, string $message = ''])

Parameters:

  • $data (mixed) – The data to return to the client. Either string or array.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when a new resource was created, typically 201.:

  1. $user = $userModel->insert($data);
  2. return $this->respondCreated($user);
  • respondDeleted($data = null[, string $message = ''])

Parameters:

  • $data (mixed) – The data to return to the client. Either string or array.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when a new resource was deleted as the result of this API call, typically 200.

  1. $user = $userModel->delete($id);
  2. return $this->respondDeleted(['id' => $id]);
  • respondNoContent(string $message = 'No Content')

Parameters:

  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when a command was successfully executed by the server but there is nomeaningful reply to send back to the client, typically 204.

  1. sleep(1);
  2. return $this->respondNoContent();
  • failUnauthorized(string $description = 'Unauthorized'[, string $code=null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when the user either has not been authorized,or has incorrect authorization. Status code is 401.

  1. return $this->failUnauthorized('Invalid Auth token');
  • failForbidden(string $description = 'Forbidden'[, string $code=null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Unlike failUnauthorized, this method should be used when the requested API endpoint is never allowed.Unauthorized implies the client is encouraged to try again with different credentials. Forbidden meansthe client should not try again because it won’t help. Status code is 403.

  1. return $this->failForbidden('Invalid API endpoint.');
  • failNotFound(string $description = 'Not Found'[, string $code=null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when the requested resource cannot be found. Status code is 404.

  1. return $this->failNotFound('User 13 cannot be found.');
  • failValidationError(string $description = 'Bad Request'[, string $code=null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when data the client sent did not pass validation rules.Status code is typically 400.

  1. return $this->failValidationError($validation->getErrors());
  • failResourceExists(string $description = 'Conflict'[, string $code=null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when the resource the client is trying to create already exists.Status code is typically 409.

  1. return $this->failResourceExists('A user already exists with that email.');
  • failResourceGone(string $description = 'Gone'[, string $code=null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when the requested resource was previously deleted andis no longer available. Status code is typically 410.

  1. return $this->failResourceGone('That user has been previously deleted.');
  • failTooManyRequests(string $description = 'Too Many Requests'[, string $code=null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when the client has called an API endpoint too many times.This might be due to some form of throttling or rate limiting. Status code is typically 400.

  1. return $this->failTooManyRequests('You must wait 15 seconds before making another request.');
  • failServerError(string $description = 'Internal Server Error'[, string $code = null[, string $message = '']])

Parameters:

  • $description (string) – The error message to show the user.
  • $code (string) – A custom, API-specific, error code.
  • $message (string) – A custom “reason” message to return.Returns:The value of the Response object’s send() method.

Sets the appropriate status code to use when there is a server error.

  1. return $this->failServerError('Server error.');