SlideShare a Scribd company logo
Building Scalable RESTFul Services
Luis Majano
@lmajano
@ortussolutions
WHO AM I?
• Luis Majano - Computer Engineer
• Imported from El Salvador ————>
• Computer Engineer
• Adobe Community Professional
• CEO of Ortus Solutions
www.ortussolutions.com
@ortussolutions
@lmajano
PROFESSIONAL OPEN SOURCE
• ContentBox Modular CMS, ColdBox MVC, CommandBox Package Manager
• Ortus University
• Support & Mentoring Plans
• Architecture & Design
• Infrastructure Design & Setup
• Code Reviews & Sanity Checks
• Application Development
info@ortussolutions.com
@ortussolutions
What are APIs
What is REST
Benefits
Principles
Good Design
Tooling
Building sustainable RESTFul services
Building sustainable RESTFul services
Building sustainable RESTFul services
• We live in a mobile world
• APIs are what powers our mobile world
• Growth is exponential
• Provides new ways to do business
• Evolve or you will be left behind
WHY APIS ARE IMPORTANT
API GROWTH
MOTIVATIONAL QUOTES
“APIs are how we are going to build software in the
future, we are just going to glue it together.”
- John Musser, founder of ProgrammableWeb
“The secret of change is to focus all of your energy,
not on fighting the old, but on building the new”
- Socrates
REST = Representational StateTransfer
• An architectural style (2000)
• Standard for web + mobile apps
• Adhere to best practices
• Low ceremony web services
• Leverage the HTTP/S Protocol
• Resource Oriented not RPC Oriented
LOW CEREMONY
SOAP - XML
VS
REST - JSON
(HTTP/S)
Headers
Params
Body
Method+URI
SOAP vs REST
/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
RESOURCE VS RPC
RESTFUL BENEFITS
• Abstractions
• Easier to scale
• Easy to refactor
• Easier to layer
• Much Less bandwidth
RESTFUL PRINCIPLES
• Protocol -> HTTP/S
• Addressability
• Protocol Uniformity
• Model Representations
• Stateless
Addressability - Resources
Objects/Resources can be addressable via a URI
/api/user/luis
/api/user/tweets
RESTFUL PRINCIPLES
RESTFUL PRINCIPLES
Protocol Uniformity
Leveraging HTTPVerbs + HTTP Headers
Model 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
10 STEPSTO GREATNESS
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. HTTPVERB 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
4. MODELING + DOCUMENTATION
• Swagger Standard (swagger.io)
• YML or JSON
• Swagger based tool: ColdBox Relax
• Model RESTFul Services
• Scaffold MVC Routes
• Documentation Exporter (HTML,PDF,etc)
• Tester
• Swagger Import/Export
box	install	relax	—saveDev
SWAGGER JSON
{	
				swagger:	"2.0",	
				info:	{	
								description:	"This	is	a	sample	server	Petstore	server.	You	can	find	out	more	about	Swagger	at	[http://swagger.io](http://swagger.io)	or	on	[irc.freenode.net,	
#swagger](http://swagger.io/irc/).	For	this	sample,	you	can	use	the	api	key	`special-key`	to	test	the	authorization	filters.",	
								version:	"1.0.0",	
								title:	"Swagger	Petstore",	
								termsOfService:	"http://swagger.io/terms/",	
								contact:	{	
												email:	"apiteam@swagger.io"	
								},	
								license:	{	
												name:	"Apache	2.0",	
												url:	"http://www.apache.org/licenses/LICENSE-2.0.html"	
								}	
				},	
				host:	"petstore.swagger.io",	
				basePath:	"/v2",	
				tags:	[{	
												name:	"pet",	
												description:	"Everything	about	your	Pets",	
												externalDocs:	{	
																description:	"Find	out	more",	
																url:	"http://swagger.io"	
												}	
								},	
								{	
												name:	"store",	
												description:	"Access	to	Petstore	orders"	
								},
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 is a MUST!
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
Third Party API Managers (Adobe API Manager, Kong)
• Upgrade/Downgrade Paths
• Scale with Ease
• No more monoliths
• Implementations:
• Frameworks
• API Manager
• Both
7. VERSIONING (MODULARITY)
8. PERFORMANCE
• Web Server (Nginx)
• Gzip Compression
• Resource Caching
• HTTP2
• SSL Keep-Alive Connections
• Throttling
• Distributed Caching
• Couchbase
• Redis
• Adobe API Manager
• Create a Caching Strategy
• Cache Invalidation
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, SwaggerHub
2. API Management
1. Adobe, Mulesoft, Kong
3. LoadTesting
1. JMeter, Paessler
4. Modular Frameworks
1. ColdBox for ColdFusion/CFML
2. Laravel, Kohana for PHP
10.ADOBE API MANAGER
1. Tons of Features:
1. Rate Limiting
2. SLAs
3. Swagger Support
4. Caching
5. Versioning
6. Security
7. Analytics
8. SOAPTools
9. Notifications
http://www.adobe.com/products/coldfusion-enterprise/api-management-platform.html
TECHNOLOGY STACK
RESTStack
ColdBox MVC
Relax
cbSwagger
RollbarCouchbase
Nginx
Adobe	API
10 STEPSTO GREATNESS
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
• Adobe API Manager: www.adobe.com/products/coldfusion-enterprise/api-
management-platform.html
• Swagger SDK: github.com/coldbox-modules/swagger-sdk
• cbSwagger Module: github.com/coldbox-modules/cbSwagger
• ColdBox : ortussolutions.com/products/coldbox
• TestBox : ortussolutions.com/products/testbox
• CommandBox: ortussolutions.com/products/commandbox
• Slack: boxteam.herokuapp.com
RESOURCES
• Docker - https://www.docker.com/
• Portainer - portainer.io
• Kong - https://getkong.org/
• Postman - https://www.getpostman.com/
• Gelato - https://gelato.io/
• Swagger - https://swagger.io/tools/
• Paessler - http://www.paessler.com/webstress
• JMeter - http://jmeter.apache.org/

More Related Content

Building sustainable RESTFul services