RESTFul Tools for Lazy Experts
Luis Majano @lmajano
Who am I
• Luis Majano
• Computer Engineer
• Imported from El Salvador
• CEO of Ortus Solutions
• Creator of all things Box
What is REST?
Benefits
Principles
Good Design
Tools
Infrastructure
Development Stacks
REST = Representational StateTransfer
• An architectural style (2000)
• Adhere to best practices
• Low ceremony web services
• Leverage the HTTP/S Protocol
• Resource Oriented not RPC Oriented
Resource vs RPC
/user/:usernameResource
Abstracted	
Can	be	Nested	
Can	point	to	any	internal	RPC	call	
Can	be	layered	
Flexible
getUser(	‘lmajano’	)Remote	Procedure	Call
Coupling	
Static	
Refactoring	Problems	
Inflexible
BENEFITS
• Abstractions
• Easier to scale
• Easy to refactor
• Easier to layer
• Less bandwidth
• Many tools
RESTFUL PRINCIPLES
Addressability - Resources
Objects/Resources can be addressable via a URI
/api/user/luis
/api/user/tweets
RESTFUL PRINCIPLES
Uniformity
Leveraging HTTPVerbs + HTTP Headers
Representations
Models in different formats: json, xml, rss, pdf, etc
200 OK
Content-Type: application/json+userdb
{
"users": [
{
"id": 1,
"name": "Emil",
"country: "Sweden",
"links": [
{
"href": "/user/1",
"rel": "self",
"method": "GET"
},
{
"href": "/user/1",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/1",
"rel": "delete",
"method": "DELETE"
}
]
},
{
"id": 2,
"name": "Adam",
"country: "Scotland",
"links": [
{
"href": "/user/2", RESTFUL PRINCIPLES
RESTFUL PRINCIPLES
Stateless
Performance, reliability, and ability to scale
LET’S APPLY THESE PRINCIPLES
A Good RESTFul Design Offers
1. Resource Naming
2. HTTPVerb Usage
3. Meaningful Status Codes
4. Modeling + Documentation
5. Uniformity
6. Security
7. Versioning (Modularity)
8. Performance
9. Testability
10.Tools
1. Resource Naming
1. URI Centric
2. Use nouns, avoid verbs (HTTPVerbs)
3. Deeper you go in the resource the more detail
4. URL Params (Options)
5. Headers (Auth+Options)
6. This is where a modeling tool can help
/customers

Get - List customers

Post - Create new customer
/customer/:id

Get - Show customer

Put - Update customer

Delete - Delete customer
/customer/:id/invoices

Get - All invoices

Post - Create invoice
/customer/:id/invoice/:invoiceID

Get - Show invoice

Put - Update invoice

Delete -Delete invoice
2. HTTP Verb Usage
Operation Verb
Create POST
Read GET
Update PUT
Single item update PATCH
Delete DELETE
Info/Metadata HEAD
Resource Doc OPTIONS
3. Meaningful Status Codes
Code Description
200 OK, usually a representation
201 New resource, check headers for URI
202 Accepted (ASYNC), check headers or response for tokens
203 Non-authoritative (Usually a cached response)
204 No Content, but processed
205 Reset Content
206 Partial Results (Usually pagination)
Code Description
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method not allowed
406 Not acceptable (Validation, invalid data)
408 RequestTimeout
410 Resource Gone
429 Too Many Requests
500 Server Error
4. MODELING + DOCUMENTATION
5.Relax Modeling, Tester, Docs
• ColdBox Module
• Model RESTFul Services
• Scaffold ColdBox Routes
• Documentation Exporter (HTML,PDF,etc)
• RelaxURLTester
• Swagger Import/Export -> API Manager
box	install	relax	—saveDev
RELAX MODEL
function	configure(){	
	 	 	
	 //	This	is	where	we	define	our	RESTful	service,	this	is	usually	
	 //	our	first	place	before	even	building	it,	we	spec	it	out.	
	 this.relax	=	{	
	 	 //	Service	Title	
	 	 title	=	"ForgeBox	IO",	
	 	 //	Service	Description	
	 	 description	=	"This	API	powers	ForgeBox",	
	 	 //	Service	entry	point,	can	be	a	single	string	or	name	value	pairs	to	denote	tiers	
	 	 //entryPoint	=	"http://www.myapi.com",	
	 	 entryPoint	=	{	
	 	 	 dev			 =	"http://localhost:9095/api/v1",	
	 	 	 stg		 =	"http://forgebox.stg.ortussolutions.com/api/v1",	
	 	 	 prd		 =	"http://forgebox.io/api/v1"	
	 	 },	
	 	 //	Does	it	have	extension	detection	via	ColdBox	
	 	 extensionDetection	=	true,	
	 	 //	Valid	format	extensions	
	 	 validExtensions	=	"json",	
	 	 //	Does	it	throw	exceptions	when	invalid	extensions	are	detected	
	 	 throwOnInvalidExtension	=	false	 	 	
	 };	
	 	
	 //	Global	API	Headers	
	 //	globalHeader(	name="x-app-token",	description="The	secret	application	token",	required=true,	type="string"	);
5.Uniformity
• Common Response object
• Common Controller (MVC)
• HTTPVerb Security
• Access Security
• Error Handling Uniformity
• Response Uniformity
Error!
Security
Where	Frameworks	Will	Help!
RESPONSE OBJECT/**	
*	HTTP	Response	model	for	the	API	
*/	
component	accessors="true"	{	
	 property	name="format"		 	 type="string"		 	 default="json";	
	 property	name="data"		 	 type="any"	 	 default="";	
	 property	name="error"		 	 type="boolean"	 	 default="false";	
	 property	name="binary"		 	 type="boolean"	 	 default="false";	
	 property	name="messages"		 	 type="array";	
	 property	name="location"		 	 type="string"	 	 default="";	
	 property	name="jsonCallback"		 type="string"	 	 default="";	
	 property	name="jsonQueryFormat"						type="string"	 	 default="query";	
	 property	name="contentType"		 type="string"	 	 default="";	
	 property	name="statusCode"		 type="numeric"	 	 default="200";	
	 property	name="statusText"			 type="string"	 	 default="OK";	
	 property	name="errorCode"	 	 type="numeric"	 	 default="0";	
	 property	name="responsetime"	 type="numeric"	 	 default="0";	
	 property	name="cachedResponse"		 type="boolean"	 	 default="false";	
	 property	name="headers"		 	 type="array";	
	 /**	
	 *	Constructor	
	 */
BASE CONTROLLER/**	
*	Around	handler	for	all	functions	
*/	
function	aroundHandler(	event,	rc,	prc,	targetAction,	eventArguments	){	
	 try{	
	 	 var	stime	=	getTickCount();	
	 	 //	prepare	our	response	object	
	 	 prc.response	=	getModel(	"Response@core"	);	
	 	 //	Scope	the	incoming	user	request	
	 	 prc.oCurrentUser	=	securityService.getUserSession();	
	 	 //	prepare	argument	execution	
	 	 var	args	=	{	event	=	arguments.event,	rc	=	arguments.rc,	prc	=	arguments.prc	};	
	 	 structAppend(	args,	arguments.eventArguments	);	
	 	 	
	 	 //	Secure	the	call	
	 	 if(	isAuthorized(	event,	rc,	prc,	targetAction	)	){	
	 	 	 //	Execute	action	
	 	 	 var	simpleResults	=	arguments.targetAction(	argumentCollection=args	);	
	 	 }	
	 }	catch(	Any	e	){	
	 	 //	Log	Locally	
	 	 log.error(	"Error	calling	#event.getCurrentEvent()#:	#e.message#	#e.detail#",	e	);	
	 	 //	Log	to	BugLogHQ
6. SECURITY
SSL
HTTP Verb Security
Request Throttling
Client API Keys or Tokens (Headers/Params)
API Key + Secret Encryption Keys (Like Amazon)
Basic Authentication (At least its something!)
IP Based Filtering/Tagging (Programmatic/Firewall/Etc)
oAuth
Adobe API Manager
• Upgrade/Downgrade Paths
• Scale
• No more monoliths
• Implementations:
• Frameworks
• Adobe API Manager
• Both
7. VERSIONING (MODULARITY)
7. Versioning (Modularity)
• ColdBox Modules - HMVC
• Root api module
• Contain commonalities (Uniformity)
• Sub-modules as versions
• v1 - /api/v1
• v2 - /api/v2
• Reusability + Scalability
• Adobe API Manager
8. PERFORMANCE
• Web Server (Nginx)
• Gzip Compression
• Resource Caching
• HTTP2
• SSL Keep-Alive Connections
• Throttling
• Distributed Caching
• Couchbase
• Redis
• Terracota
• Frameworks: CacheBox + ColdBox
• Adobe API Manager
• Take time in a cache strategy
• Cache Invalidation
8. PERFORMANCE
• ColdBox Event Caching
• Leverages CacheBox
• Any Cache Backend
• Caching Resources
• Rich Invalidation API
Looks familiar?
9. TESTABILITY
WHY PEOPLE DON’T TEST
COMFORT
WHY PEOPLE DON’T TEST
New Methodology
New Learned Behavior
It is a leap….
BIGGEST LIE IN SOFTWARE DEV


Don’t worry, we will create the
tests and refactor it later!
• Just do it!
• You will get dirty
• It can hurt (a little)
• Learned behavior
NO MORE EXCUSES
IT WILL ACCELERATE YOUR
DEVELOPMENT
BDD TESTING
10. Tools
1. Modeling/Documentation/Testing
1. Relax*, Postman, Swagger, Gelato
2. API Management
1. Adobe*, Mulesoft, IBM, Kong
3. LoadTesting
1. JMeter, Paessler
4. ColdBox MVC
1. cbSwagger Module
10. Adobe API Manager
1. Scale your API’s
2. Tons of Features:
1. Rate Limiting
2. SLAs
3. Swagger Support
4. Caching
5. Versioning
6. Security
7. Analytics
8. SOAPTools
9. Notifications
Technology Stack
RESTStack
ColdBox MVC
Relax
cbSwagger
RollbarCouchbase
Nginx
Adobe	API
A Good RESTFul Design Offers
1. Resource Naming
2. HTTPVerb Usage
3. Meaningful Status Codes
4. Modeling + Documentation
5. Uniformity
6. Security
7. Versioning (Modularity)
8. Performance
9. Testability
10.Tools
Resources
• Relax: github.com/coldbox-modules/coldbox-relax
• Swagger SDK: github.com/coldbox-modules/swagger-sdk
• cbSwagger Module: github.com/coldbox-modules/cbSwagger
• TestBox : ortussolutions.com/products/testbox
• CommandBox: ortussolutions.com/products/commandbox
• Slack: boxteam.herokuapp.com
• CFML Slack: #box-products
Thank
you!

RESTFul Tools For Lazy Experts - CFSummit 2016

  • 1.
    RESTFul Tools forLazy Experts Luis Majano @lmajano
  • 2.
    Who am I •Luis Majano • Computer Engineer • Imported from El Salvador • CEO of Ortus Solutions • Creator of all things Box
  • 3.
    What is REST? Benefits Principles GoodDesign Tools Infrastructure Development Stacks
  • 4.
    REST = RepresentationalStateTransfer • An architectural style (2000) • Adhere to best practices • Low ceremony web services • Leverage the HTTP/S Protocol • Resource Oriented not RPC Oriented
  • 5.
  • 6.
    BENEFITS • Abstractions • Easierto scale • Easy to refactor • Easier to layer • Less bandwidth • Many tools
  • 7.
    RESTFUL PRINCIPLES Addressability -Resources Objects/Resources can be addressable via a URI /api/user/luis /api/user/tweets
  • 8.
  • 9.
    Representations Models in differentformats: json, xml, rss, pdf, etc 200 OK Content-Type: application/json+userdb { "users": [ { "id": 1, "name": "Emil", "country: "Sweden", "links": [ { "href": "/user/1", "rel": "self", "method": "GET" }, { "href": "/user/1", "rel": "edit", "method": "PUT" }, { "href": "/user/1", "rel": "delete", "method": "DELETE" } ] }, { "id": 2, "name": "Adam", "country: "Scotland", "links": [ { "href": "/user/2", RESTFUL PRINCIPLES
  • 10.
  • 11.
  • 12.
    A Good RESTFulDesign Offers 1. Resource Naming 2. HTTPVerb Usage 3. Meaningful Status Codes 4. Modeling + Documentation 5. Uniformity 6. Security 7. Versioning (Modularity) 8. Performance 9. Testability 10.Tools
  • 13.
    1. Resource Naming 1.URI Centric 2. Use nouns, avoid verbs (HTTPVerbs) 3. Deeper you go in the resource the more detail 4. URL Params (Options) 5. Headers (Auth+Options) 6. This is where a modeling tool can help /customers
 Get - List customers
 Post - Create new customer /customer/:id
 Get - Show customer
 Put - Update customer
 Delete - Delete customer /customer/:id/invoices
 Get - All invoices
 Post - Create invoice /customer/:id/invoice/:invoiceID
 Get - Show invoice
 Put - Update invoice
 Delete -Delete invoice
  • 14.
    2. HTTP VerbUsage Operation Verb Create POST Read GET Update PUT Single item update PATCH Delete DELETE Info/Metadata HEAD Resource Doc OPTIONS
  • 15.
    3. Meaningful StatusCodes Code Description 200 OK, usually a representation 201 New resource, check headers for URI 202 Accepted (ASYNC), check headers or response for tokens 203 Non-authoritative (Usually a cached response) 204 No Content, but processed 205 Reset Content 206 Partial Results (Usually pagination) Code Description 400 Bad Request 401 Unauthorized 402 Payment Required 403 Forbidden 404 Not Found 405 Method not allowed 406 Not acceptable (Validation, invalid data) 408 RequestTimeout 410 Resource Gone 429 Too Many Requests 500 Server Error
  • 16.
    4. MODELING +DOCUMENTATION
  • 17.
    5.Relax Modeling, Tester,Docs • ColdBox Module • Model RESTFul Services • Scaffold ColdBox Routes • Documentation Exporter (HTML,PDF,etc) • RelaxURLTester • Swagger Import/Export -> API Manager box install relax —saveDev
  • 18.
    RELAX MODEL function configure(){ // This is where we define our RESTful service, this is usually // our first place before even building it, we spec it out. this.relax = { // Service Title title = "ForgeBox IO", // Service Description description = "This API powers ForgeBox", // Service entry point, can be a single string or name value pairs to denote tiers //entryPoint = "http://www.myapi.com", entryPoint = { dev = "http://localhost:9095/api/v1", stg = "http://forgebox.stg.ortussolutions.com/api/v1", prd = "http://forgebox.io/api/v1" }, // Does it have extension detection via ColdBox extensionDetection = true, // Valid format extensions validExtensions = "json", // Does it throw exceptions when invalid extensions are detected throwOnInvalidExtension = false }; // Global API Headers // globalHeader( name="x-app-token", description="The secret application token", required=true, type="string" );
  • 19.
    5.Uniformity • Common Responseobject • Common Controller (MVC) • HTTPVerb Security • Access Security • Error Handling Uniformity • Response Uniformity Error! Security Where Frameworks Will Help!
  • 20.
    RESPONSE OBJECT/** * HTTP Response model for the API */ component accessors="true" { property name="format" type="string" default="json"; property name="data" type="any" default=""; property name="error" type="boolean" default="false"; property name="binary" type="boolean" default="false"; property name="messages" type="array"; property name="location" type="string" default=""; property name="jsonCallback" type="string" default=""; property name="jsonQueryFormat" type="string" default="query"; property name="contentType" type="string" default=""; property name="statusCode" type="numeric" default="200"; property name="statusText" type="string" default="OK"; property name="errorCode" type="numeric" default="0"; property name="responsetime" type="numeric" default="0"; property name="cachedResponse" type="boolean" default="false"; property name="headers" type="array"; /** * Constructor */
  • 21.
    BASE CONTROLLER/** * Around handler for all functions */ function aroundHandler( event, rc, prc, targetAction, eventArguments ){ try{ var stime = getTickCount(); // prepare our response object prc.response = getModel( "Response@core" ); // Scope the incoming user request prc.oCurrentUser = securityService.getUserSession(); // prepare argument execution var args = { event = arguments.event, rc = arguments.rc, prc = arguments.prc }; structAppend( args, arguments.eventArguments ); // Secure the call if( isAuthorized( event, rc, prc, targetAction ) ){ // Execute action var simpleResults = arguments.targetAction( argumentCollection=args ); } } catch( Any e ){ // Log Locally log.error( "Error calling #event.getCurrentEvent()#: #e.message# #e.detail#", e ); // Log to BugLogHQ
  • 22.
    6. SECURITY SSL HTTP VerbSecurity Request Throttling Client API Keys or Tokens (Headers/Params) API Key + Secret Encryption Keys (Like Amazon) Basic Authentication (At least its something!) IP Based Filtering/Tagging (Programmatic/Firewall/Etc) oAuth Adobe API Manager
  • 23.
    • Upgrade/Downgrade Paths •Scale • No more monoliths • Implementations: • Frameworks • Adobe API Manager • Both 7. VERSIONING (MODULARITY)
  • 24.
    7. Versioning (Modularity) •ColdBox Modules - HMVC • Root api module • Contain commonalities (Uniformity) • Sub-modules as versions • v1 - /api/v1 • v2 - /api/v2 • Reusability + Scalability • Adobe API Manager
  • 25.
    8. PERFORMANCE • WebServer (Nginx) • Gzip Compression • Resource Caching • HTTP2 • SSL Keep-Alive Connections • Throttling • Distributed Caching • Couchbase • Redis • Terracota • Frameworks: CacheBox + ColdBox • Adobe API Manager • Take time in a cache strategy • Cache Invalidation
  • 26.
    8. PERFORMANCE • ColdBoxEvent Caching • Leverages CacheBox • Any Cache Backend • Caching Resources • Rich Invalidation API
  • 27.
  • 28.
    WHY PEOPLE DON’TTEST COMFORT
  • 29.
    WHY PEOPLE DON’TTEST New Methodology New Learned Behavior It is a leap….
  • 30.
    BIGGEST LIE INSOFTWARE DEV 
 Don’t worry, we will create the tests and refactor it later!
  • 31.
    • Just doit! • You will get dirty • It can hurt (a little) • Learned behavior NO MORE EXCUSES IT WILL ACCELERATE YOUR DEVELOPMENT
  • 32.
  • 33.
    10. Tools 1. Modeling/Documentation/Testing 1.Relax*, Postman, Swagger, Gelato 2. API Management 1. Adobe*, Mulesoft, IBM, Kong 3. LoadTesting 1. JMeter, Paessler 4. ColdBox MVC 1. cbSwagger Module
  • 34.
    10. Adobe APIManager 1. Scale your API’s 2. Tons of Features: 1. Rate Limiting 2. SLAs 3. Swagger Support 4. Caching 5. Versioning 6. Security 7. Analytics 8. SOAPTools 9. Notifications
  • 35.
  • 36.
    A Good RESTFulDesign Offers 1. Resource Naming 2. HTTPVerb Usage 3. Meaningful Status Codes 4. Modeling + Documentation 5. Uniformity 6. Security 7. Versioning (Modularity) 8. Performance 9. Testability 10.Tools
  • 37.
    Resources • Relax: github.com/coldbox-modules/coldbox-relax •Swagger SDK: github.com/coldbox-modules/swagger-sdk • cbSwagger Module: github.com/coldbox-modules/cbSwagger • TestBox : ortussolutions.com/products/testbox • CommandBox: ortussolutions.com/products/commandbox • Slack: boxteam.herokuapp.com • CFML Slack: #box-products
  • 38.