38
RESTFul Tools for Lazy Experts Luis Majano @lmajano

RESTFul Tools For Lazy Experts - CFSummit 2016

Embed Size (px)

Citation preview

RESTFul Tools for Lazy ExpertsLuis 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

PrinciplesGood Design

ToolsInfrastructure

Development Stacks

REST = Representational State Transfer

• 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

AbstractedCanbeNestedCanpointtoanyinternalRPCcallCanbelayeredFlexible

getUser(‘lmajano’)RemoteProcedureCall

CouplingStaticRefactoringProblemsInflexible

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 HTTP Verbs + HTTP Headers

Representations Models in different formats: json, xml, rss, pdf, etc

200 OKContent-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", "rel": "self",

RESTFUL PRINCIPLES

RESTFUL PRINCIPLES

Stateless Performance, reliability, and ability to scale

LET’S APPLY THESE PRINCIPLES

A Good RESTFul Design Offers

1. Resource Naming2. HTTP Verb Usage3. Meaningful Status Codes4. Modeling + Documentation 5. Uniformity 6. Security7. Versioning (Modularity)8. Performance9. Testability10.Tools

1. Resource Naming

1. URI Centric2. Use nouns, avoid verbs (HTTP Verbs)3. Deeper you go in the resource the more detail4. 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 CodesCode 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 Request Timeout

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)• RelaxURL Tester• Swagger Import/Export -> API Manager

boxinstallrelax—saveDev

RELAX MODELfunctionconfigure(){ //ThisiswherewedefineourRESTfulservice,thisisusually //ourfirstplacebeforeevenbuildingit,wespecitout. this.relax={ //ServiceTitle title="ForgeBoxIO", //ServiceDescription description="ThisAPIpowersForgeBox", //Serviceentrypoint,canbeasinglestringornamevaluepairstodenotetiers //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" }, //DoesithaveextensiondetectionviaColdBox extensionDetection=true, //Validformatextensions validExtensions="json", //Doesitthrowexceptionswheninvalidextensionsaredetected throwOnInvalidExtension=false }; //GlobalAPIHeaders //globalHeader(name="x-app-token",description="Thesecretapplicationtoken",required=true,type="string");

//ECHO

5.Uniformity

• Common Response object• Common Controller (MVC)• HTTP Verb Security• Access Security• Error Handling Uniformity• Response Uniformity

Error!

Security

WhereFrameworksWillHelp!

RESPONSE OBJECT/***HTTPResponsemodelfortheAPI*/componentaccessors="true"{

propertyname="format" type="string" default="json"; propertyname="data" type="any" default=""; propertyname="error" type="boolean" default="false"; propertyname="binary" type="boolean" default="false"; propertyname="messages" type="array"; propertyname="location" type="string" default=""; propertyname="jsonCallback" type="string" default=""; propertyname="jsonQueryFormat"type="string" default="query";

propertyname="contentType" type="string" default=""; propertyname="statusCode" type="numeric" default="200"; propertyname="statusText" type="string" default="OK"; propertyname="errorCode" type="numeric" default="0"; propertyname="responsetime" type="numeric" default="0"; propertyname="cachedResponse" type="boolean" default="false"; propertyname="headers" type="array";

/** *Constructor */ Responsefunctioninit(){

BASE CONTROLLER/***Aroundhandlerforallfunctions*/functionaroundHandler(event,rc,prc,targetAction,eventArguments){ try{ varstime=getTickCount(); //prepareourresponseobject prc.response=getModel("Response@core"); //Scopetheincominguserrequest prc.oCurrentUser=securityService.getUserSession();

//prepareargumentexecution varargs={event=arguments.event,rc=arguments.rc,prc=arguments.prc}; structAppend(args,arguments.eventArguments); //Securethecall if(isAuthorized(event,rc,prc,targetAction)){ //Executeaction varsimpleResults=arguments.targetAction(argumentCollection=args); } }catch(Anye){ //LogLocally log.error("Errorcalling#event.getCurrentEvent()#:#e.message##e.detail#",e); //LogtoBugLogHQ sendToBugLog(e);

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 MethodologyNew 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/Testing1. Relax*, Postman, Swagger, Gelato

2. API Management1. Adobe*, Mulesoft, IBM, Kong

3. Load Testing1. JMeter, Paessler

4. ColdBox MVC1. cbSwagger Module

10. Adobe API Manager

1. Scale your API’s2. Tons of Features:

1. Rate Limiting2. SLAs3. Swagger Support4. Caching5. Versioning6. Security7. Analytics8. SOAP Tools9. Notifications

Technology Stack

REST

Stack ColdBox MVC

Relax

cbSwagger

RollbarCouchbase

Nginx

AdobeAPI

A Good RESTFul Design Offers

1. Resource Naming2. HTTP Verb Usage3. Meaningful Status Codes4. Modeling + Documentation 5. Uniformity 6. Security7. Versioning (Modularity)8. Performance9. Testability10.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!