REST API prepared on ColdFusion with FW/1 and DI/1 dressing

  • Jul 6, 2015

Cooking Developing REST API with ColdFusion or Railo is not a big deal now

But what if you don't want to create 'special' CFCs, want to reuse code from other projects and stay in line with rest of your FW/1 application ? Then you want to use FW/1 features to create REST API. I prepared small example which involves user login and returning user data via REST API.

The core of API code is FW/1 routes and CFC methods which are executed when route URL is called. To set up routes, Application.cfc is modified to have variables.framework.routes variable store mapings from REST routes to regular FW/1 application actions.

Note that HTTP method and route is mapped to FW/1 application route. Calling GET method on [siteroot]/users URL (route) is like having the framework to execute list() method in users.cfc controller via /index.cfm/users/list/ call. What is different from regular execution, is that controller method will use variables.fw.renderData method to return data. No view file will be searched for, unlike it happens in regular FW/1 method call.

To get advantages of DI/1 and bean factory we should have two files in our project  


and register bean factory in Application.cfc (see gist above).

The argument for bean factory ('model' in our case) is the path where factory going to look for beans and services. Bean is CFC entity that is created every time we asking factory to get us one. Services are created only once (singletons). Here's folder structure:


User is a bean representing user of the system and Security is a singleton CFC instance which is in charge of user management (retrieves and modifies user details and user permissions.)

Now, the routes are in place, bean factory is setup, we need users.cfc controller method to do actual work (in this case, login user)

First as we see here, component's accessors property set to true, to have ColdFusion add implicit getters/setters methods for component properties. The SecurityService property is declared, following naming convention - we have /model/services/Security.cfc, which became SecurityService (yes, DI/1 is clever enough to understand that singular "service" means plural "services".) So VARIABLES.SecuirtyService will receive singleton object of Security.cfc. Result of SecurityService.login() method is then passed to FW/1's renderData method which will output object in JSON-encoded format. Valid encoding are also XML and plain text. DeserializeJSON method is used to create ColdFusion objects out of JSON-encoded data that is being sent to API with POST method.

Raw request is looking like this:

In following article, I'll describe server setup for proper REST API functioning. For commentaries please check this post in CF User Group Ukraine Facebook group.