Welcome back to our series, CF Camp 2018: Madness in Munich! This is our series that highlights some of the upcoming conference sessions at the ONLY CF conference in Europe. In Part One, we talked about the importance of Java security, how it pertains to ColdFusion, and the benefits of Elasticsearch. Today, we draw inspiration from Matt Gifford’s upcoming session: Building an API with cffractal and ColdBox. While I will leave the API construction process down to Matt; let’s discuss what APIs are, how important they are to modern programming, and what cffractal & ColdBox can do for you.
“…we’re really doing some modern things and using up to date ColdBox standards with MVC. We’re doing a lot of RESTful APIs. We’re doing some of these cutting edge things and it really makes it enjoyable and I’ve been really impressed with how ColdFusion has kept up with that, and how it’s led the way on some of those things”- Scott Coldwell, Developer and Sysadmin at Computer Know How
What You Need to Know as CIO
APIs have taken the programming world by storm. They are regularly used by industry giants such as Google and Amazon, yet still make appearances in small local businesses as well. In modern programming, APIs must be considered for nearly every project. So… What exactly is an API?
Defining an API
An API or (Application Programming Interface) as defined by Wikipedia is:
“a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components.”
David Berlind, Editor-in-Chief of ProgrammableWeb.com creates a useful metaphor for defining APIs. He likens them to electrical wall sockets. He states:
“In North America and other parts of the world, the electrical sockets found in the walls of homes and businesses are essentially interfaces to a service: the electricity that’s consumed by everything from our computers and smartphones to appliances like vacuum cleaners and hair dryers. In other words, it’s important to think of the electricity as a service and of each device that uses electricity as a consumer of that service. In this scenario, instead of having its own source of power (the way a car does), the consumer is outsourcing its power requirements to the provider of a service.
While they may differ depending on where they are in the world, electrical sockets have predictable patterns of openings into which electrical plugs that match those patterns fit. The service itself also conforms to certain specifications. For example, in North America, most wall sockets deliver 120 volts of alternating current (AC) operating at 60Hz (the frequency at which the current alternates directions). This specification essentially sets an expectation on behalf of consuming devices. For example, your microwave oven has an expectation of the wall socket that it’s plugged-into and the wall-socket has an expectation of the microwave oven. Likewise, an API specifies how software components should interact with each other.”
This is a great metaphor which shows the connection between components and just how beneficial a set standard can be. It would be rather silly and a huge waste of resources if you needed to purchase specific appliances that only fit a particular socket. The same principle applies with APIs. Time, money, and other resources may be minimized by setting a standard for how software components speak and interact with each other. Not only that, but creating APIs allows you and your company to reach out to consumers and clients on a much grander scale.
Common Uses for APIs
APIs have many more uses than just providing a great metaphor for wall sockets. Here are some of the areas in which APIs are showcased and how they are used.
Social Media APIs– Each social media platform has their very own APIs used to enhance their users experience. These APIs provide functions such as:
- Searching Social Media Content
- Logging in to Social Media Accounts
- Allow for User Sharing
- Allow for Likes, Pins, Reacts, etc…
- View Groups, Connections, Friends, and Communities
- Creating and Uploading New Content
- Generation of Relevant Ads
This list goes on and on, but I think you get the point. Social media as a whole could not exist in its current form without APIs.
Marketplace APIs- These particular types of APIs are largely responsible for the development of online retail and classified sites. These types of APIs are used by companies such as eBay, Amazon, FourSquare, and Craigslist.
Marketing APIs- APIs of this nature help to collect data for marketing services. The data collected and help generate targeted ads, track ad campaigns, and develop new marketing schemes for products.
The Rise of the API
This can be directly attributed to the need for applications to deliver cheaper, faster, and stronger results. APIs have allowed businesses to become much more customer-centric by optimizing customer engagement. APIs target three main facets of this revolution.
- They allow for enriched customer experiences and interaction. Many APIs are extremely simple to navigate– often times without being recognized. Without a doubt, almost every person reading this has used an API today without even knowing it. Whether it’s just checking your Facebook or Googling some random factoid, APIs accelerate consumer life.
- APIs improve computing and programming processes. This goes back to the wall socket scenario. By applying a programming standard, APIs can help your apps to reach out wider and work better.
- APIs optimize your workforce. Not only do they make your IT department’s lives better, but the entirety of the company. Many business now employ an API economy. In layman’s terms, this is a set of business models based on a exchange of data and secure access of functionality.
Cloud Computing and APIs
Cloud computing strategies and your API strategy should go hand-in-hand. A properly aligned cloud and API strategy can syndicate assets to new internal and external audiences.
Chris McNabb, GM of Dell Boomi, thinks very highly of this combination. He claims, “When considered this way, it becomes clear that a well-conceived and properly implemented API strategy also has the potential to drive innovation, increase productivity, and create new channels and markets.”
As CFML developers and companies, we have a few distinct advantages when it comes to the building of APIs. And the number one advantage may just be ColdBox.
CF Tech Talk
There are some pretty neat tools out there for CFML and ColdFusion, and ColdBox is no exception. It is a conventions-based HMVC (Hierarchical Model View Controller) framework designed specifically for CFML. Its modular architecture helps you to build hierarchical MVC apps instead of outdated, gargantuan applications. ColdBox also provides you with a developmental standard for use in team environments.
Developed by Ortus Solutions, ColdBox is celebrating its 12 year existence with its newest version, ColdBox 5. Its presence has been felt throughout the CFML community as well. According to our 2018 State of the CF Union, ColdBox is the most popular third party framework. It registered as being used by 1 out of 3 CF’ers polled. Needless to say, ColdBox is here to stay and will only grow stronger with time.
“I’m proud to develop in ColdFusion, because it has the combination. Specifically, being a part of the ColdBox and a lot of the open source community as part of ColdFusion, because we have three things.
One, we have a great tradition. We have been a part of some of the greatest highs and a few of the lows of the web development history.
Second, we’ve got some tenacity in there. A lot of the people who are very strong in the CFML community are people who have been doing this for a while and they’ve been doing it well. That’s tenacity to not go from one thing, to the next thing, to the next thing, but really craft something solidly and well.
Third, we’ve got some of the most forward thinking, and highly developed, and amazing tools that we could imagine. We’re going to be hanging out and Into The Box with the guy that invented CommandBox, as well as the guy that invented ColdBox itself. These are some just amazing tools that the CFML community has been blessed with.
I think we have the key parts that I would want in any community, tradition. We’ve got time honored tenacity and we’ve got some innovation, and forward thinking. That’s exactly what I want to be a part of.”- Nathaniel Francis, Works at Computer Know How
From CF Alive episode, “008 The Best REST You’ve ever Had: ColdBox REST with Nathaniel Francis“
What can ColdBox do for you?
ColdBox is the first framework developed specifically for CFML that embraces a Conventions over Configurations concept. This means that ColdBox attempts to decrease the number of decisions that a developer is required to make without losing flexibility. Alongside its modular architecture, these allow for enhanced user and team productivity.
ColdBox is a member of the “Box” family, so naturally it integrates seamlessly into the CommandBoxCLI. One simple line in the CLI allows you to get started right away with ColdBox. Simply enter:
coldbox create app myApp
Its integration with the CommandBox CLI does more than allow for an easy installation. It allows you access to:
- REPL Interfaces
- Package Management
- Console Development
- Automation Services
- And Much More!
ColdBox also comes with 3 independent modular libraries.
- WireBox: Conventions Based Dependency Injection and (AOP) Framework
- LogBox: Enterprise Caching Engine, Cache Aggregator, and API for CFML Applications
- CacheBox: Enterprise Logging Designed to Give you Flexibility, Simplicity, and Power.
Despite all these neat features, ColdBox has another trick up its sleeve. It can help you to get the best REST you’ve ever had.
REST stands for Representational State Transfer. It is an architectural style for providing standards between computer systems on the web. Thus, making it easier for systems to communicate with each other.
What’s strange is that many CF’ers don’t use REST as of now. Nathaniel Francis believes he knows some of the reasoning behind it.
“I think part of that comes from CFML’s heritage itself, which CFML excelled. It was one of the main languages that excelled at making just full bodied applications dynamically. Since it thrived in that area, when the tech industry moved to some newer ideas, it had a good sweet spot.”
But REST– particularly APIs– can provide something that has continued to elude CFML and ColdFusion. Universality. REST APIs are very versatile. Instead of full-bodied traditional applications, REST allows for something that any platform can interact with. With a REST API backend, you can swap out the front end of your application without fear that it won’t work.
The RESTful ColdBox API makes REST specific aspects such as HTTP verbs, status cards, and routing as straightforward as possible so other systems can translate it well.
ColdBox makes it very simple to convert new apps and even legacy apps to RESTful applications. It is a two step process.
- Import or create your app in ColdBox.
- Take the views from that app and move them out to an application that can speak to REST. Then place the rest of your business logic, event handling, data modeling as a REST API.
This, of course, is an oversimplification, but the process is easy enough.
The second nifty tool Matt Gifford will touch on is cffractal. Github breaks down cffractal into 2 simple sentences.
Views take models and return HTML. CFFractal takes models and returns JSON (or your favorite serialized format).
There are 3 main reasons why you should use cffractal.
- Transforming your business model into JSON in many different places.
- Including and excluding relationships depending on the endpoint.
- Minimize repeating yourself all over the place
Other reasons however may include:
- Conventions around Nested Resources
- Default Includes
- Nested Includes
- Sharing Resource Transformations
- Consistency and Encapsulation
When it comes to the flexibility aspect, here’s what Jon Clausen has to say on the matter:
“Having written API’s against MongoDB, ORM, and even a few that use legacy DAO/Gateway patterns, the benefit for me of the fractal transformation module is that I can use it for any of them, because of the transformer. If the models already know how to accomplish the transformations to a degree, like our mementos in ORM, then that’s great.
You don’t always have that, though, and you don’t always want a fully normalized expansion. Sometimes you need only a small subset when dealing with secondary one-to-one relationships that need some normalization of the top level element.
This eliminates three methods that I always found myself writing (or copy/pasting and adapting) for every API handler:
- The collection marshalling method
- The single entity response marshalling method
- The format entity method, which handles the expansion parameters in the collection
Cffractal also comes equipped with different serializers. Serializers are responsible for the shape of the response of your fractal functions. This includes the data, metadata, and additional information about the item or collection (such as pagination or links).
There are four main serializers with Cffractal.
- Simple Serializer- returns the processed resource data directly and nests the metadata under a meta key.
- Data Serializer- nests the processed resource data inside a data key and nests the metadata under a meta key.
- ResultsMap Serializer- nests the processed resource data inside a resultsMap struct keyed by an identifier column as well as an array of identifiers nested under a results key. The metadata is nested under a meta key.
- XML Serializer- transforms the data into XML. It nests all items under a rootKey which can be specified in the constructor. Data is returned under either a data key or the root transformer’s resourceKey, if defined. Meta is returned under a meta key.
Cffractal along with the use of ColdBox can definitely make your life easier when it comes to the construction of APIs. Don’t miss Matt Gifford’s extremely informative session on using these two tools. Remember, you will only be able to attend this session at the 2018 CF Camp in Munich. Get your tickets and start making plans today!
About the Speaker:
Matt Gifford is owner and primary primate at his own development consultancy company, monkehWorks Ltd. His work primarily focuses on building mobile apps and ColdFusion development, although he’s such a geek he enjoys writing in a variety of languages. He’s a published author and presents at conferences and user groups on a variety of topics.
And to continue learning how to make your ColdFusion apps more modern and alive, I encourage you to download our free ColdFusion Alive Best Practices Checklist.
Because… perhaps you are responsible for a mission-critical or revenue-generating CF application that you don’t trust 100%, where implementing new features is a painful ad-hoc process with slow turnaround even for simple requests.
What if you have no contingency plan for a sudden developer departure or a server outage? Perhaps every time a new freelancer works on your site, something breaks. Or your application availability, security, and reliability are poor.
And if you are depending on ColdFusion for your job, then you can’t afford to let your CF development methods die on the vine.
You’re making a high-stakes bet that everything is going to be OK using the same old app creation ways in that one language — forever.
All it would take is for your fellow CF developer to quit or for your CIO to decide to leave the (falsely) perceived sinking ship of CFML and you could lose everything—your project, your hard-won CF skills, and possibly even your job.
Luckily, there are a number of simple, logical steps you can take now to protect yourself from these obvious risks.
No Brainer ColdFusion Best Practices to Ensure You Thrive No Matter What Happens Next
Modern ColdFusion development best practices that reduce stress, inefficiency, project lifecycle costs while simultaneously increasing project velocity and innovation.
√ Easily create a consistent server architecture across development, testing, and production
√ A modern test environment to prevent bugs from spreading
√ Automated continuous integration tools that work well with CF
√ A portable development environment baked into your codebase… for free!
Learn about these and many more strategies in our free ColdFusion Alive Best Practices Checklist.
Originally published at teratech.com on October 15, 2018.