Blog

Daniel Garcia

June 16, 2023

Spread the word


Share your thoughts

5 Benefits of Using ColdBox to Build Your REST API

ColdBox is an excellent MVC framework that can be used to solve many problems, from creating simple websites to enterprise-level applications. With built-in support for logging, caching, routing, dependency injection, testing, documentation, and more, it covers most of your needs as a developer. It also supports a modular architecture that allows you to grow your application as needed.

I regularly build REST APIs in CFML, and using ColdBox allows me to stub out the API structure quickly, focus more on the business logic, and deliver data. Many useful features within ColdBox help with development, but here are five that I find particularly beneficial.

  1. Routing
  2. Security
  3. Validation
  4. Testing
  5. Debugging

An easy way to start is to use the ColdBox HMVC template to create an initial site. Using CommandBox, run this command to get started: coldbox create app-wizard

When going through the wizard, indicate that you are making an API and use the Modular (API/REST) template. This will generate an HMVC API, install dependencies, and stub out the files. When done, you will also want to install the ColdBox Debugger module: install cbDebugger

Routing

You can create routes to your API by defining them in the router. If you are building an endpoint that will create, read, update, or delete a record (CRUD), you can define a single route and use the HTTP verb to differentiate which handler function gets called. For example:

// Map route to specific user.  Different verbs call different actions!
component{

    function configure(){
        setFullRewrites( true );

        // User Resource
        route( "/api/user/:userID" )
            .withAction( {
                GET    = 'view',
                POST   = 'save',
                PUT    = 'save',
                DELETE = 'remove'
            } )
            .toHandler( "api.user" );

        route( ":handler/:action?" ).end();
    }

}

We have a route that sends all requests to the api.user handler and executes the specified function. This makes it very easy to set up different handlers and use a standard for accessing the functions.

One caveat, when creating handlers, it is a best practice to limit the functions to using the set CRUD type functions to avoid having too complicated a handler. If you have to make a call that doesn't belong in the current handler, just make a new handler. :) Here is a great video called Cruddy By Design that covers this concept.

Check out the ColdBox documentation for more information on routing.

Security

You can use the ColdBox Security module to lock down your APIs to ensure that only allowed users can access them. If requiring authentication, you can use JWT authentication and require the token on each request to confirm authorization. If using role-based security, you can also annotate your handler or functions to limit access. The API template you generated will set this up for you automatically and stub out an example user login process. Securing your handler can be as simple as

component secured{
	function index(event,rc,prc){}
	function list(event,rc,prc){}
}

If you want to get fancy, you can also use roles to further restrict access.

// Secure this handler
component secured="admin,users"{

	function index(event,rc,prc) secured="list"{

	}
	
	function save(event,rc,prc) secured="write"{

	}

}

Check out the documentation on JWT Services and Security Annotations to learn more.

Validation

When building APIs, validating the data you receive is one of the most important things. Allowing bad data through can cause many issues, including server errors. ColdBox Validation is a module that makes adding validation in your handler easy. You can define what you want to validate and how, then if the validation fails, it can return a standard error message.

Here is an example of using cbValidation. I require that values for x and y are passed in, and that y is numeric and between 1 and 10. If validation fails, a standard error will be returned, letting the user know what validation failed. If validation passes, the rest of the function gets executed.

function index( event, rc, prc ){
	var validationResult = validateOrFail(
		target      = rc,
		constraints = {
			"x" : { "required" : true },
			"y" : {
				"required" : true,
				"type"     : "numeric",
				"min"      : 1,
				"max"      : 10
			}
		}
	);

	var result = myService.getItem( argumentCollection = validationResult );
	event.getResponse().setData( result );
}

Learn more about cbValidation at the documentation site.

Testing

Now that you have written your API, testing it is essential to confirm everything works as expected. With ColdBox, you can use TestBox to write tests that will call your API and verify the result. Although you can do different types of testing, this is called BDD (Behavior Driven Development) Integration testing, where your tests simulate calling the API, the same as an end user.

Here is an example of a test. Note, this is just one test function in the test CFC.

story( "I want to view the results of my API", function(){
	given( "a valid call", function(){
		then( "I will view the results", function(){
			var event    = this.get( route = "/api/v1/first", params = {} );
			var response = event.getPrivateValue( "Response" );
			expect( response.getData() ).toBeArray();
			expect( response.getData().len() ).toBeGT( 0 );
		} );
	} );
} );

In this example, I am calling the /api/v1/first API endpoint without passing any values into it, and then I am testing that my return data is an array format and is not empty. Tests can get as complex as you need them, but the idea here is to make the call, and the check for what you expect to receive.

You can learn more about testing at the TestBox documentation site.

Debugging

When working with APIs, debugging can sometimes be challenging. You can always add dumps and aborts, or write the output to a file, but that can get cumbersome. Fusion Reactor is an excellent tool for troubleshooting, but that may not always be available. I like to use the ColdBox Debugger, which allows me to easily monitor my API calls, and when configured, also to see the results of my database queries. It even allows you to inspect the cache, which is fantastic!

Once installed and configured, you can just go to /cbdebugger on your API site to view the activity.

This tool has many great features, so be sure to check out ColdBox Debugger on ForgeBox.

Conclusion

ColdBox is an excellent framework for building REST APIs. It provides many benefits that greatly improve the development process and overall performance of your application. It can be your foundation for building an application that can be as simple or complex as you need. In particular, these five things are highly beneficial when using ColdBox for my REST API projects.

There are many, many more reasons to use ColdBox and the Ortus Solutions tools too (CommandBox and qb anyone?)! Please check them out!

Add Your Comment

(1)

Jun 19, 2023 19:50:50 UTC

by Joe

Great and to the point. CommandBox is really helpful doing the scaffolding for you.

Recent Entries

ColdBox 7.2.0 Released

ColdBox 7.2.0 Released

ColdBox, a widely used development platform for ColdFusion (CFML), has unveiled version 7.2. Packed with compelling new features, bug fixes, and enhancements, this release is designed to empower developers by boosting productivity, refining scheduled task capabilities, and enhancing the overall reliability and efficiency of application development. This article will delve into the key highlights of ColdBox 7.2 and elucidate how these advancements can positively impact developers in their daily coding endeavors.

Luis Majano
Luis Majano
November 20, 2023
Into the Box 2023 Series on CFCast

Into the Box 2023 Series on CFCast

Excitement is in the air as we unleash the highly anticipated ITB 2023 series exclusively for our valued CFCast subscribers – and the best part? It's FREE for CFCast members! Now is the perfect time if you haven't joined the CFCast community yet. Plus, we've got an incredible End-of-Year deal that's too good to miss

Maria Jose Herrera
Maria Jose Herrera
November 20, 2023
Ortus Deals are Finally Here!

Ortus Deals are Finally Here!

The much-anticipated Ortus End-of-the-Year Sale has arrived, and it's time to elevate your development experience! Whether you're a seasoned developer, a tech enthusiast, or someone on the lookout for top-notch projects, Ortus has something special in store for you. Brace yourself for incredible discounts across a wide array of products and services, including Ortus annual events, books, cutting-edge services, and more.

Maria Jose Herrera
Maria Jose Herrera
November 15, 2023