REST Handler

RestHandler & ColdBox Response

ColdBox 6 has integrated a base handler and a response object into the core, so developers can have even more support when building RESTful services. This new rest handler will provide you with tons of utilities and approaches to make all of your RESTFul services:
  • Uniformity on Responses
  • A consistent and extensible response object
  • Error handling
  • Invalid route handling
  • Events
  • Much more
In previous versions of ColdBox support for RESTful services was provided by adding the base handler and the response object to our application templates. Integration into the core brings ease of use, faster handling and above all: a uniform approach for each ColdBox version in the future.
RestHandler UML

Base Class: RestHandler

For the creation of REST handlers you can inherit from our base class coldbox.system.RestHandler, directly via extends="coldbox.system.Resthandler" or our using the restHandler annotation.
ColdBox Docs
RestHandler API Docs
This will give you access to our enhanced API utilities and the native response object via the request context's getResponse() method.
1
component extends="coldbox.system.RestHandler"{
2
3
function index( event, rc, prc ){
4
event.getResponse()
5
.setData( "Hello from restful Land" );
6
}
7
}
8
9
component resthandler{
10
11
function index( event, rc, prc ){
12
event.getResponse()
13
.setData( "Hello from restful Land" );
14
}
15
16
}
Copied!
You will then leverage that response object (https://apidocs.ortussolutions.com/coldbox/current/index.html?coldbox/system/web/context/Response.html) to do the following actions:
  • Set the data to be converted to JSON, XML or whatever
  • Set pagination data
  • Set errors
  • Set if the data is binary or not
  • Set location headers
  • Set message arrays
  • Set json call backs
  • Set json query formats
  • Set response contentType
  • Set response statusCode
  • Set response headers
  • Much More
ColdBox Docs
Response API Docs
Upgrade Pointers: The response object will be accessible using the event.getResponse() method but will still be available as prc.response.
If you are using cbORM make sure to check the chapter Automatic Rest Crud

Base Rest Handler Actions

The Rest handler gives you the following actions coded for you out of the box. You can override them if you want, but the idea is that this base takes you a very long way.
Core Actions
Purpose
aroundHandler()
Wraps all rest actions uniformly to provide consistency and error trapping.
onError()
An implicit error handler is provided just in case anything explodes in your restful actions. Sends an appropriate 500 error
onValidationException()
Traps any and makes sure it sends the appropriate 400 response with the invalid data. Useful for using cbValidation, for example with the validateOrFail() methods.
onEntityNotFoundException()
Traps any or exceptions and makes sure it send an appropriate 404 response. Useful for leveraging cborm or Quick ORM
onInvalidHTTPMethod()
Traps any invalid HTTP method security exception and sends the appropriate 405 not allowed response
onMissingAction()
Traps any invalid actions/resource called in your application and sends the appropriate 404 response
onAuthenticationFailure()
Traps InvalidCredentials exceptions and sends the appropriate 403 invalid credentials response. If you are using cbSecurity it will also verify jwt token expiration and change the error messages accordingly.
onAuthorizationFailure()
Traps PermissionDenied exceptions and sends the appropriate 401 response. This Action can be used when a user does not have authorization or access to your application or code. Usually you will call this manually or from a security library like cbSecurity or cbGuard. It will send a 401 not authorized response.
onInvalidRoute()
Action that can be used as a catch all from your router so it can catch all routes that are invalid. It will send a 404 response accordingly.
onExpectationFailed()
Utility method for when an expectation of the request fails ( e.g. an expected parameter is not provided ). This action is called manually from your own handlers and it will output a 417 response back to the user.
onAnyOtherException
Fires when ANY exception that is not excplicitly trapped is detected. This basically logs the issue and offers a 500 error. You can now intercept it and do whatever you need on ANY type of untrapped exception.

AroundHandler in Detail

The aroundHandler() provided in the RestHandler will intercept all rest calls in order to provide consistency and uniformity to all your actions. It will try/catch for major known exceptions, time your requests, add extra output on development and much more. Here are a list of the features available to you:

Exception Handling

Automatic trapping of the following exceptions:
  • EntityNotFound
  • InvalidCredentials
  • PermissionDenied
  • RecordNotFound
  • TokenInvalidException
  • ValidationException
If the trapped exception is not one from above, then we will call the onAnyOtherException() action. This action will log automatically the exception with extra restful metadata according to the environment you are executing the action with. It will also setup an exception response for you.
If in a development environment it will respond with much more information necessary for debugging both in the response object and headers

Development Responses

If you are in a development environment it will set the following headers for you in the response object automatically.
  • x-current-event
  • x-current-route
  • x-current-routed-url
  • x-current-routed-namespace

Global Headers

The following headers are sent in each request no matter the environment:
  • x-response-time : The time the request took in CF
  • x-cached-response : If the request is cached via event caching

Output Detection

The aroundHandler() is also smart in detecting the following outputs from a handler, which will ignore the REST response object:
  • Handler return results
  • Setting a view or layout to render
  • Explicit renderData() calls

Response Object

The Response object is used by the developer to set into it what the response will be by the API call. The object is located at coldbox.system.web.context.Response and can be retrieved by the request context object's getResponse() method.
ColdBox Docs
Response API Docs

Response Format

Every response is created from the internal properties in the following JSON representation:
1
{
2
"error" : getError() ? true : false,
3
"messages" : getMessages(),
4
"data" : getData(),
5
"pagination" : getPagination()
6
};
Copied!
You can change this response by extending the response object and doing whatever you want.

Properties

The Response object has the following properties you can use via their getters and setter methods.
Property
Type
Default
Usage
binary
boolean
false
If the data property is binary
contentType
string
---
Custom content type of the response
data
struct
---
The data struct marshalled in the response
error
boolean
false
Boolean bit denoting an exception or problem in the API call
format
string
json
The response format of the API. Defaults to json.
jsonCallback
string
---
If using a callback then set the callback method here.
jsonQueryFormat
string
true
This parameter can be a Boolean value that specifies how to serialize ColdFusion queries or a string with possible values row, column, or struct
location
string
---
The location header to send with the response
messages
array
---
Array of messages to send in the response packet
pagination
struct
{ offset, maxRows, page, totalRecords, totalPages }
A pagination struct to return
responseTime
numeric
0
The time the request and response took
statusCode
numeric
200
The status code to send
statusText
string
OK
The status text to send

Convenience Methods

A part from the setters/getters from the properties above, the response object has some cool convenience methods:
1
/**
2
* Utility function to get the state of this object
3
*/
4
struct function getMemento()
5
6
/**
7
* Add some messages to the response
8
*
9
* @message Array or string of message to incorporate
10
*/
11
Response function addMessage( required any message )
12
13
/**
14
* Get all messages as a string
15
*/
16
string function getMessagesString()
17
18
/**
19
* Add a header into the response
20
*
21
* @name The header name ( e.g. "Content-Type" )
22
* @value The header value ( e.g. "application/json" )
23
*/
24
Response function addHeader( required string name, required string value )
25
26
/**
27
* Set the pagination data
28
*
29
* @offset The offset
30
* @maxRows The max rows returned
31
* @page The page number
32
* @totalRecords The total records found
33
* @totalPages The total pages found
34
*/
35
Response function setPagination(
36
numeric offset = 0,
37
numeric maxRows = 0,
38
numeric page = 1,
39
numeric totalRecords = 0,
40
numeric totalPages = 1
41
)
42
43
/**
44
* Returns a standard response formatted data packet using the information in the response
45
*
46
* @reset Reset the 'data' element of the original data packet
47
*/
48
struct function getDataPacket( boolean reset = false )
49
50
/**
51
* Sets the status code with a statusText for the API response
52
*
53
* @code The status code to be set
54
* @text The status text to be set
55
*
56
* @return Returns the Response object for chaining
57
*/
58
Response function setStatus( required code, text )
59
60
/**
61
* Sets the data and pagination from a struct with `results` and `pagination`.
62
*
63
* @data The struct containing both results and pagination.
64
* @resultsKey The name of the key with the results.
65
* @paginationKey The name of the key with the pagination.
66
*
67
* @return Returns the Response object for chaining
68
*/
69
Response function setDataWithPagination(
70
data,
71
resultsKey = "results",
72
paginationKey = "pagination"
73
)
74
75
/**
76
* Sets the error message with a code for the API response
77
*
78
* @errorMessage The error message to set
79
* @statusCode The status code to set, if any
80
* @statusText The status text to set, if any
81
*
82
* @return Returns the Response object for chaining
83
*/
84
Response function setErrorMessage(
85
required errorMessage,
86
statusCode,
87
statusText = ""
88
)}
Copied!

Status Text Lookup

The response object also has as STATUS_TEXTS public struct exposed so you can use it for easy status text lookups:
1
this.STATUS_TEXTS = {
2
"100" : "Continue",
3
"101" : "Switching Protocols",
4
"102" : "Processing",
5
"200" : "OK",
6
"201" : "Created",
7
"202" : "Accepted",
8
"203" : "Non-authoritative Information",
9
"204" : "No Content",
10
"205" : "Reset Content",
11
"206" : "Partial Content",
12
"207" : "Multi-Status",
13
"208" : "Already Reported",
14
"226" : "IM Used",
15
"300" : "Multiple Choices",
16
"301" : "Moved Permanently",
17
"302" : "Found",
18
"303" : "See Other",
19
"304" : "Not Modified",
20
"305" : "Use Proxy",
21
"307" : "Temporary Redirect",
22
"308" : "Permanent Redirect",
23
"400" : "Bad Request",
24
"401" : "Unauthorized",
25
"402" : "Payment Required",
26
"403" : "Forbidden",
27
"404" : "Not Found",
28
"405" : "Method Not Allowed",
29
"406" : "Not Acceptable",
30
"407" : "Proxy Authentication Required",
31
"408" : "Request Timeout",
32
"409" : "Conflict",
33
"410" : "Gone",
34
"411" : "Length Required",
35
"412" : "Precondition Failed",
36
"413" : "Payload Too Large",
37
"414" : "Request-URI Too Long",
38
"415" : "Unsupported Media Type",
39
"416" : "Requested Range Not Satisfiable",
40
"417" : "Expectation Failed",
41
"418" : "I'm a teapot",
42
"421" : "Misdirected Request",
43
"422" : "Unprocessable Entity",
44
"423" : "Locked",
45
"424" : "Failed Dependency",
46
"426" : "Upgrade Required",
47
"428" : "Precondition Required",
48
"429" : "Too Many Requests",
49
"431" : "Request Header Fields Too Large",
50
"444" : "Connection Closed Without Response",
51
"451" : "Unavailable For Legal Reasons",
52
"499" : "Client Closed Request",
53
"500" : "Internal Server Error",
54
"501" : "Not Implemented",
55
"502" : "Bad Gateway",
56
"503" : "Service Unavailable",
57
"504" : "Gateway Timeout",
58
"505" : "HTTP Version Not Supported",
59
"506" : "Variant Also Negotiates",
60
"507" : "Insufficient Storage",
61
"508" : "Loop Detected",
62
"510" : "Not Extended",
63
"511" : "Network Authentication Required",
64
"599" : "Network Connect Timeout Error"
65
};
Copied!

Extending The RestHandler

If you would like to extend or modify the behavior of the core RestHandler then you will have to create your own base handler that inherits from it. Then all of your concrete handlers will inherit from your very own handler.
1
// BaseHandler
2
component extends="coldbox.system.Resthandler"{
3
4
// Modify it here
5
6
}
7
8
// Then make your own handlers extend from it
9
component extends="BaseHandler"{
10
11
}
Copied!

Extending The Response Object

The response object can be found here: coldbox.system.web.context.Response and the rest handler constructs it by calling the request context’s getResponse() method. The method verifies if there is a prc.response object and if it exists it returns it, else it creates a new one. So if you would like to use your very own, then just make sure that before the request you place your own response object in the prc scope.
Here is a simple example using a preProcess() interceptor. Create a simple interceptor with commandbox e.g
1
coldbox create interceptor name=MyInterceptor points=preProcess
Copied!
and add the following method:
1
function preProcess( event, interceptData, rc, prc ){
2
prc.response = wirebox.getInstance( "MyResponseObject" );
3
}
Copied!
Don't forget to register your interceptor in config/Coldbox.cfc:
1
interceptors = [
2
{
3
class : "interceptors.MyInterceptor",
4
name : "MyInterceptor",
5
properties : {}
6
}
7
];
Copied!
That’s it. Once that response object is in the prc scope, ColdBox will utilize it. Just make sure that your custom Response object satisfies the methods in the core one. If you want to modify the output of the response object a good place to do that would be in the getDataPacket() method of your own MyResponseObject. Just make sure this method will return a struct.