Recent events has prompted me to learn very quickly how to write a Restful API. I originally started this project months ago, but recent events at work have now put this in the fast lane. So now I am learning quickly to create a Restful API in ColdFusion.
Before we continue, I do want to mention that: Yes, Adobe ColdFusion 10 and 11 have built in Restful API support. However, in this case, I have the constraint of Adobe ColdFusion 9, so this project is from scratch.
A few things we have decided from the get go:
1. Responses will be in JSON format
2. Will be following as many best practices as possible. Most of which were laid out here in a very well written blog post by Vinay Sahni: Best Practices for Designing a Pragmatic RESTful API
3. We are going to use http header status codes
Here is our problem, we want to write as much as we can in one language type. ColdFusion's CFScript. However, as is often the case with Adobe's ColdFusion Language, much functionality is missing from the scripting language. Including an equivalent for
Fortunately for me, we have Ben Nadel experimenting and sharing his findings with the world. And so I found this post ColdFusion GetPageContext() Massive Exploration. In this post, Ben documents the methods of the
getPageContext() method, which led me to this
pc = getpagecontext().getresponse(); pc.getresponse().setstatus(404);
This effectively allowed me to set the status code in the header of the result. This didn't right off the bat allow me to set a status message.
Thankfully, Ben's documentation includes the Java returned objects. This led me to look up
javax.servlet.ServletResponse and to find that I could pass in a second parameter into setStatus to pass a message.
pc = getpagecontext().getresponse(); pc.getresponse().setstatus(404, "Could Not Find That Page");
Thats my lesson learned for today, Thanks @BenNadel!