SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building...

59

Transcript of SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building...

Page 1: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS
Page 2: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

SOA with RESTPrinciples, Patterns & Constraints

for Building Enterprise Solutions with REST

PREnTicE HAll

Upper Saddle river, NJ • BoStoN • iNdiaNapoliS • SaN FraNciSco

New York • toroNto • MoNtreal • loNdoN • MUNich • pariS • Madrid

cape towN • SYdNeY • tokYo • SiNgapore • Mexico citY

thomas erl, Benjamin carlyle, cesare pautasso, and raj Balasubramanian

00_9780137012510_FM .indd 7 7/5/12 5:22 PM

Page 3: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

35_9780137012510_ifc-ibc.indd 2 7/5/12 4:56 PM

Page 4: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

Contents at a GlanceForeword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxix

Chapter 1: introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1

Chapter 2: case Study Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

Part I: FundamentalsChapter 3: introduction to Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23

Chapter 4: Soa terminology and concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31

Chapter 5: reSt constraints and goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51

Part II: restFul servIce-OrIentatIOn Chapter 6: Service contracts with reSt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67

Chapter 7: Service-orientation with reSt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93

Part III: servIce-OrIented analysIs and desIgn wIth rest Chapter 8: Mainstream Soa Methodology and reSt . . . . . . . . . . . . . . . . . . . . . . .127

Chapter 9: analysis and Service Modeling with reSt . . . . . . . . . . . . . . . . . . . . . . .139

Chapter 10: Service-oriented design with reSt . . . . . . . . . . . . . . . . . . . . . . . . . . .173

Part Iv: servIce cOmPOsItIOn wIth restChapter 11: Fundamental Service composition with reSt . . . . . . . . . . . . . . . . . . .231

Chapter 12: advanced Service composition with reSt . . . . . . . . . . . . . . . . . . . . . .261

Chapter 13: Service composition with reSt case Study . . . . . . . . . . . . . . . . . . . 305

Part v: suPPlementalChapter 14: design patterns for Soa with reSt . . . . . . . . . . . . . . . . . . . . . . . . . . .327

Chapter 15: Service versioning with reSt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343

Chapter 16: Uniform contract profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .361

Part vI: aPPendIcesappendix a: case Study conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383

appendix B: industry Standards Supporting the web . . . . . . . . . . . . . . . . . . . . . . . 387

appendix C: reSt constraints reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .391

appendix d: Service-orientation principles reference . . . . . . . . . . . . . . . . . . . . . . 409

appendix e: Soa design patterns reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .425

appendix F: State concepts and types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .521

appendix G: the annotated Soa Manifesto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533

appendix h: additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .547

about the authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553

about the pattern co-contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555

about the Foreword contributor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .557

index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559

00_9780137012510_FM .indd 11 7/5/12 5:22 PM

Page 5: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

Chapter 10

Service-Oriented Design with REST

10.1 Uniform Contract Design Considerations

10.2 REST Service Contract Design

10.3 Complex Method Design

13_9780137012510_ch10.indd 173 7/5/12 4:35 PM

Page 6: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

PrinciPles, Patterns, and constraints referenced in this chaPter:

• AtomicTransaction[432]

• Cache{398}

• CanonicalExpression[434]

• CanonicalSchema[437]

• EntityAbstraction[463]

• Event-DrivenMessaging[465]

• IdempotentCapability[470]

• LayeredSystem{404}

• LegacyWrapper[473]

• LogicCentralization[475]

• ProcessAbstraction[486]

• ServiceAbstraction(414)

• ServiceDiscoverability(420)

• ServiceLooseCoupling(413)

• Stateless{395}

• UniformContract{400}

• UtilityAbstraction[517]

• ValidationAbstraction[518]

13_9780137012510_ch10.indd 174 7/5/12 4:36 PM

Page 7: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 175

Usingtheconceptualservicecandidatesmodeledduringtheprecedingservice-orientedanalysisprocessasastartingpoint,service-orienteddesignisdedicatedtothephysicaldesignofservicecontracts.WhenitcomestocontractdesignwithREST,weneedtobeconcernedwithtwoparticularareas:

1. Thedesignofauniformcontractforaserviceinventory.

2. Thedesignofindividualservicecontractswithintheserviceinventoryandincompliancewiththeuniformcontract.

Theuniformcontractneedstobefirmlyestablishedbeforewebegincreatingservicecontractsthatwillberequiredtoformdependenciesonuniformcontractfeatures.Asaserviceinventorygrowsandevolves,newservicescanstillinfluencethedesignofauniformcontract,butuniformcontractfeaturesaregenerallychangedandaddedataverydeliberatepace.

Followingtheprecedingsequence,thischapterbeginswithcoverageofuniformcon-tract design topics and then moves on to topics that pertain to the design of REST ser-vicecontracts.Thechapterconcludeswithasectiononcomplexmethods, an optional fieldofRESTcontractdesignandonesuitablemainlyforusewithincontrolledenviron-ments,suchasinternalserviceinventories.

10.1 Uniform contract design considerations

Whencreatingauniformcontractforaserviceinventory,wehavearesponsibilitytoequipandlimititsfeaturessothatitisstreamlinedtoeffectivelyaccommodaterequire-mentsandrestrictionsunique to theservice inventory.Thedefault characteristicsofWeb-centrictechnologyarchitecturecanprovideaneffectivebasisforaserviceinven-tory’suniformcontract,althoughadditionalformsofstandardizationandcustomiza-tionarelikelytoberequiredfornon-trivialserviceinventoryarchitectures.

Thefollowingsectionsexplorehowcommonelementsofauniformcontract(methods, mediatypes,andexceptionsinparticular)canbecustomizedtomeettheneedsofindi-vidualserviceinventories.

designing and standardizing Methods

Whenwediscussmethodsinrelationtotheuniformcontract, it is considered short-hand for a request-response communications mechanism that also includes meth-ods, headers, response codes,andexceptions.Methodsarecentralizedaspartof the

13_9780137012510_ch10.indd 175 7/5/12 4:36 PM

Page 8: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

176 Chapter 10: Service-Oriented Design with REST

uniformcontractinordertoensurethattherearealwaysasmallnumberofwaysofmoving information around within a particular service inventory, and that existing serviceconsumerswillworkcorrectlywithnewormodifiedservicesastheyareaddedtotheinventory.Whereasit is importanttominimizethenumberofmethodsintheuniformcontract,methodscanandshouldbeaddedwhenserviceinventoryinterac-tionrequirementsdemandit.Thisisanaturalpartofevolvingaserviceinventoryinresponsetobusinesschange.

HTTP provides a solid foundation by sup-plying the basic set of methods (such asGET,PUT,DELETE,POST)provenbyuseonthe Web and widely supported by off-the-shelf software components and hardware devices.But theneedmayarise toexpressother types of interactions for a serviceinventory.Forexample, youmaydecide toadd a special method that can be used toreliablytriggeraresourcetoexecuteataskat most once,ratherthanusingthelessreli-ableHTTPPOSTmethod.

HTTP is designed to be extended in theseways.TheHTTPspecificationexplicitlysup-ports the notion of extension methods,cus-tomizedheaders,andextensibilityinotherareas.LeveragingthisfeatureofHTTPcanbe effective, as long as new extensions are addedcarefullyandatarateappropriateforthenumberofservicesthatimplementHTTPwithinaninventory.Thisway, the total numberofoptionsformovingdataaround(thatservicesandconsumersarerequiredtounderstand)remainsmanageable.

note

Later in this chapter we explore a set of sample, extended methods (referred to as complex methods), each of which utilizes multiple basic HTTP methods or utilizes a single basic HTTP method multiple times, to perform pre-defined, standardized interactions.

Lesswell-knownHTTPmethodshave come and gone in the past. For example,atvarioustimestheHTTPspecificationhasincludeda PATCHmethodconsistentwithapartialupdateorpartialstorecommunicationsmechanism.PATCHiscurrentlyspecifiedseparatelyfromHTTPmethodsintheIETF’sRFC5789document.OtherIETFspecifications,suchasWebDAV’sRFC4918andtheSessionInitiationProtocol’s RFC 3261,introducednewmethodsaswell as new headers and response codes(orspecialinterpretationsthereof).

13_9780137012510_ch10.indd 176 7/5/12 4:36 PM

Page 9: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 177

Commoncircumstancesthatcanwarrantthecreationofnewmethodsinclude:

• Hyperlinksmaybeusedtofacilitateasequenceofrequest-responsepairs.Whentheystarttoreadlikeverbsinsteadofnounsandtendtosuggestthatonlyasinglemethodwillbevalidonthetargetofahyperlink,wecanconsiderintroduc-ing a new method instead. For example the “customer”hyperlinkforaninvoiceresourcesuggeststhatGETandPUTrequestsmightbeequallyvalidforthecustomerresource.Buta“begintransaction”hyperlinkora“subscribe”hyperlinksuggestonlyPOSTisvalidandmayindicatetheneedforanewmethodinstead.

• Datawithmust-understandsemanticsmaybeneededwithinmessageheaders.Inthis case,aservicethatignoresthismetadatacancauseincorrectruntimebehav-ior.HTTPdoesnotincludeafacilityforidentifyingindividualheadersorinforma-tion within headers as “must-understand.”Anewmethodcanbeusedtoenforcethisrequirementbecausethecustommethodwillbeautomaticallyrejectedbya service that doesn’tunderstandtherequest(whereasfallingbackonadefaultHTTPmethodwillallowtheservicetoignorethenewheaderinformation).

It is important to acknowledge that introducing custom methods can have negativeimpacts when exploring vendor diversity within an implementation environment. Itmay prevent off-the-shelf components (such as caches, load balancers, firewalls, and various HTTP-based software frameworks) from being fully functional within theserviceinventory.SteppingawayfromHTTPanditsdefaultmethodsshouldonlybeattemptedinmatureserviceinventorieswhentheeffectsontheunderlyingtechnologyarchitectureandinfrastructurearefullyunderstood.

Somealternativestocreatingnewmethodscanalsobeexplored.Forexample, service interactions that require a number of steps can use hyperlinks to guide consumersthroughtherequeststheyneedtomake.TheHTTPLinkheader(RFC5988)canbecon-sideredtokeepthesehyperlinksseparatefromtheactualdocumentcontent.

designing and standardizing httP headers

Exchanging messages with metadata is common in service-oriented solutiondesign.Becauseoftheemphasisofcomposingasetofservicestogethertocollectivelyautomateagiventaskatruntime, there is often a need for a message to provide a range of header information that pertains to how the message should be processed by intermediaryservice agents and services along its message path.

13_9780137012510_ch10.indd 177 7/5/12 4:36 PM

Page 10: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

178 Chapter 10: Service-Oriented Design with REST

Built-inHTTPheaderscanbeusedinanumberofways:

• TheycanbeusedtoaddparametersrelatedtoarequestmethodasanalternativetousingquerystringstorepresenttheparameterswithintheURL.Forexample, the AcceptheadercansupplementtheGETmethodbyprovidingcontentnegotia-tion data.

• Theycanbeusedtoaddparametersrelatedtoaresponsecode.ForexampletheLocationheadercanbeusedwiththe201 Created response code to indicate the identifierofanewlycreatedresource.

• Theycanbeusedtocommunicategeneralinformationabouttheserviceorconsumer.ForexampletheUpgradeheadercanindicatethataserviceconsumersupportsandprefersadifferentprotocol, while the Referrer header can indicate whichresourcetheconsumercamefromwhilefollowingaseriesofhyperlinks.

ThistypeofgeneralmetadatamaybeusedinconjunctionwithanyHTTPmethod.

HTTPheaderscanalsobeutilizedtoaddrichmetadata.Forthispurposecustomhead-ersaregenerallyrequired,whichre-introducestheneedtodeterminewhetherornotthemessagecontentmustbeunderstoodbyrecipientsorwhetheritcanoptionallybeignored.Thisassociationofmust-understandsemanticswithnewmethodsandmust-ignoresemanticswithnewmessageheadersisnotaninherentfeatureofREST,butitisafeatureofHTTP.

WhenintroducingcustomHTTPheadersthatcanbeignoredbyservices,regularHTTPmethodscansafelybeused.Thisalsomakes theuseofcustomheadersbackwards-compatiblewhencreatingnewversionsofexistingmessagetypes.

As previously stated in the Designing and Standardizing Methods section, new HTTPmethodscanbeintroducedtoenforcemust-understandcontentbyrequiringservicestoeitherbedesignedtosupportthecustommethodortorejectthemethodinvocationattemptaltogether.Insupportofthisbehavior, a new Must-Understandheadercanbecreated in the same format as the existing Connection header,whichwouldlistalloftheheadersthatneedtobeunderstoodbymessagerecipients.

IfthistypeofmodificationismadetoHTTP,itwouldbetheresponsibilityoftheSOAGovernanceProgramOfficeresponsiblefortheserviceinventorytoensurethatthesesemanticsareimplementedconsistentlyaspartofinventory-widedesignstandards.Ifcustom,must-understandHTTPheadersaresuccessfullyestablishedwithinaserviceinventory, we can explore a range of applications of messaging metadata. For example,

13_9780137012510_ch10.indd 178 7/5/12 4:36 PM

Page 11: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 179

wecandeterminewhetheritispossibleorfeasibletoemulatemessagingmetadatasuchaswhatiscommonlyusedinSOAPmessagingframeworksbasedonWS-*standards.

While custom headers that enforce reliability or routing content (as per the WS-ReliableMessagingandWS-Addressingstandards)canbeaddedtorecreateacknowl-edgementandintelligentloadbalancinginteractions,otherformsofWS-*functionsaresubjecttobuilt-inlimitationsoftheHTTPprotocol.ThemostprominentexampleistheuseofWS-Securitytoenablemessage-levelsecurityfeatures,suchasencryptionanddigitalsignatures.Message-levelsecurityprotectsmessagesbyactuallytransformingthecontentsothatintermediariesalongamessagepathareunabletoreadoraltermes-sagecontent.Onlythosemessagerecipientswithpriorauthorizationareabletoaccessthe content.

ThistypeofmessagetransformationisnotsupportedinHTTP/1.1.HTTPdoeshavesome basic features for transforming the body of the message alone through its Content-Encoding header,butthisisgenerallylimitedtocompressionofthemessagebodyanddoesnotincludethetransformationofheaders.Ifthisfeaturewasusedforencryptionpurposesthemeaningofthemessagecouldstillbemodifiedorinspectedin transit,eventhoughthebodypartofthemessagecouldbeprotected.Messagesig-naturesarealsonotpossibleinHTTP/1.1asthereisnocanonicalformforanHTTPmessage to sign,andnoindustrystandardthatdetermineswhatmodificationsinterme-diarieswouldbeallowedtomaketosuchamessage.

designing and standardizing httP response codes

HTTPwasoriginallydesignedasasynchronous, client-server protocol for the exchange ofHTMLpagesovertheWorldWideWeb.ThesecharacteristicsarecompatiblewithRESTconstraintsandmakeitalsosuitableasaprotocolusedtoinvokeRESTservicecapabilities.

DevelopingaserviceusingHTTPisverysimilartopublishingdynamiccontentonaWebserver.EachHTTPrequestinvokesaRESTservicecapabilityandthatinvocationconcludeswiththesendingofaresponsemessagebacktotheserviceconsumer.

AgivenresponsemessagecancontainanyoneofawidevarietyofHTTPcodes, each ofwhichhasadesignatednumber.Certainrangesofcodenumbersareassociatedwithparticulartypesofconditions,asfollows:

• 100-199areinformationalcodesusedaslowlevelsignalingmechanisms,suchasaconfirmationofarequesttochangeprotocols.

13_9780137012510_ch10.indd 179 7/5/12 4:36 PM

Page 12: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

180 Chapter 10: Service-Oriented Design with REST

• 200-299aregeneralsuccesscodesusedtodescribevariouskindsofsuccessconditions.

• 300-399areredirectioncodesusedtorequestthattheconsumerretryarequesttoadifferentresourceidentifier,orviaadifferentintermediary.

• 400-499representconsumer-sideerrorcodesthatindicatethattheconsumerhasproducedarequestthatisinvalidforsomereason.

• 500-599representservice-sideerrorcodesthatindicatethattheconsumer’s requestmayhavebeenvalidbutthattheservicehasbeenunabletoprocessitforinternal reasons.

The consumer-side and service-side exception categories are helpful for “assigning blame,”butdolittletoactuallyenableserviceconsumerstorecoverfromfailure.Thisisbecause,whilethecodesandreasonsprovidedbyHTTParestandardized, how ser-vice consumers are required to behave upon receiving response codes is not. Whenstandardizingservicedesignforaserviceinventory,itisnecessarytoestablishasetofconventions that assign response codes concrete meaning and treatment.

Table10.1providescommondescriptionsofhowserviceconsumerscanbedesignedtorespond to common response codes.

response code reason Phrase treatment

100 Continue Indeterminate

101 SwitchingProtocols Indeterminate

1xx Anyother1xxcode Failure

200 OK Success

201 Created Success

202 Accepted Success

203 Non-Authoritative Information

Success

204 No Content Success

13_9780137012510_ch10.indd 180 7/5/12 4:36 PM

Page 13: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 181

response code reason Phrase treatment

205 Reset Content Success

206 PartialContent Success

2xx Anyother2xxcode Success

300 MultipleChoices Failure

301 MovedPermanently Indeterminate

(CommonBehavior: Modifyresourceidentifier

andretry.)

302 Found Indeterminate

(CommonBehavior: ChangerequesttoaGETand

retryusingnominatedresourceidentifier.)

303 See Other

304 NotModified Success

(CommonBehavior: Usecachedresponse.)

305 UseProxy Indeterminate

(CommonBehavior: Connecttoidentifiedproxyand

resendoriginalmessage.)

307 TemporaryRedirect Indeterminate

(CommonBehavior: Retryoncetonominatedresource

identifier.)

3xx Anyother3xxcode Failure

400 BadRequest Failure

continues

13_9780137012510_ch10.indd 181 7/5/12 4:36 PM

Page 14: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

182 Chapter 10: Service-Oriented Design with REST

response code reason Phrase treatment

401 Unauthorized Indeterminate

(CommonBehavior: Retrywithcorrectcredentials.)

402 PaymentRequired Failure

403 Forbidden Failure

404 NotFound SuccessifrequestwasDELETE, elseFailure

405 MethodNotAllowed Failure

406 NotAcceptable Failure

407 ProxyAuthenticationRequired Indeterminate

(CommonBehavior: Retrywithcorrectcredentials.)

408 RequestTimeout Failure

409 Conflict Failure

410 Gone SuccessifrequestwasDELETE, elseFailure

411 LengthRequired Failure

412 PreconditionFailed Failure

413 RequestEntityTooLarge Failure

414 Request-URITooLong Failure

415 UnsupportedMediaType Failure

416 RequestedRange NotSatisfiable

Failure

417 Expectation Failed Failure

13_9780137012510_ch10.indd 182 7/5/12 4:36 PM

Page 15: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 183

response code reason Phrase treatment

4xx Anyother4xxcode Failure

500 InternalServerError Failure

501 NotImplemented Failure

502 BadGateway Failure

503 ServiceUnavailable RepeatifRetry-Afterheaderisspecified.Otherwise,Failure.

504 GatewayTimeout Repeatifrequestisidempotent.Otherwise,Failure.

505 HTTPVersion NotSupported

Failure

5xx Anyother5xxcode Failure

Table 10.1HTTP response codes, and typical corresponding consumer behavior.

AsisevidentwhenreviewingTable10.1,HTTPresponsecodesgowellbeyondthesim-pledistinctionbetweensuccessandfailure.Theyprovideanindicationofhowconsum-ers can respond to and recover from exceptions.

Let’stakeacloserlookatsomeofthevaluesfromtheTreatmentcolumninTable10.1:

• Repeatmeansthattheconsumerisencouragedtorepeattherequest, taking into accountanydelayspecifiedinresponsessuchas503 Service Unavailable. This maymeansleepingbeforetryingagain.Iftheconsumerchoosesnottorepeattherequest,itmusttreatthemethodasfailed.

• Successmeanstheconsumershouldtreatthemessagetransmissionasasuccess-fulactionandmustthereforenotrepeatit.(Notethatspecificsuccesscodesmayrequiremoresubtleinterpretation.)

• Failedmeansthattheconsumermustnotrepeattherequestunchanged,althoughitmayissueanewrequestthattakestheresponseintoaccount.Theconsumershouldtreatthisasafailedmethodifanewrequestcannotbegenerated.(Notethatspecificfailurecodesmayrequiremoresubtleinterpretation.)

13_9780137012510_ch10.indd 183 7/5/12 4:36 PM

Page 16: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

184 Chapter 10: Service-Oriented Design with REST

• Indeterminatemeansthattheconsumerneedstomodifyitsrequestinthemannerindicated.Therequestmustnotberepeatedunchangedandanewrequestthattakestheresponseintoaccountshouldbegenerated.Thefinaloutcomeoftheinteractionwilldependonthenewrequest.Iftheconsumerisunabletogenerateanewrequest,thenthiscodemustbetreatedasfailed.

BecauseHTTPisaprotocol, not a set of message processing logic,itisuptotheservicetodecidewhatstatuscode(success,failure,orotherwise)toreturn.Aspreviouslymen-tioned,becauseconsumerbehaviorisnotalwayssufficientlystandardizedbyHTTPformachine-to-machine interactions,itneedstobeexplicitlyandmeaningfullystandard-izedaspartofanSOAproject.

For example,indeterminatecodestendtoindicatethatserviceconsumersmusthandleasituationusingtheirowncustomlogic.Wecanstandardizethesetypesofcodesintwoways:

• Designstandardscandeterminewhichindeterminatecodescanandcannotbeissuedbyservicelogic.

• Designstandardscandeterminehowserviceconsumerlogicmustinterpretthoseindeterminate codes that are allowed.

Customizing Response Codes

TheHTTPspecificationallowsforextensionstoresponsecodes.ThisextensionfeatureisprimarilytheretoallowfutureversionsofHTTPtointroducenewcodes.Itisalsousedbysomeotherspecifications(suchasWebDAV)todefinecustomcodes.This istypicallydonewithnumbersthatarenotlikelytocollidewithnewHTTPcodes, which canbeachievedbyputtingthemneartheendoftheparticularrange(forexample,299isunlikelytoeverbeusedbythemainHTTPstandard).

Specificserviceinventoriescanfollowthisapproachbyintroducingcustomresponsecodesaspartoftheserviceinventorydesignstandards.InsupportoftheUniform Con-tract {400} constraint, customresponse codes shouldonlybedefinedat theuniformcontract level, not at the REST service contract level.

Whencreatingcustomresponsecodes,itisimportantthattheybenumberedbasedontherangetheyfallin.Forexample,2xxcodesshouldbecommunicatingsuccess, while 4xxcodesshouldonlyrepresentfailureconditions.

13_9780137012510_ch10.indd 184 7/5/12 4:36 PM

Page 17: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 185

Additionally,itisgoodpracticetostandardizetheinsertionofhuman-readablecontentintotheHTTPresponsemessageviatheReasonPhrase.Forexample,thecode400hasadefaultreasonphraseof“BadRequest.”Thisisenoughforaserviceconsumertohandletheresponseasageneralfailure,butitdoesn’ttellahumananythingusefulabouttheactualproblem.Settingthereasonphraseto“TheserviceconsumerrequestismissingtheCustomeraddressfield.” or perhaps even “Requestbodyfailedvalidationagainstschema http://example.com/customer” is more helpful, especially when reviewinglogsofexceptionconditionsthatmaynothavethefulldocumentattached.

Consumerscanassociategenericlogictohandleresponsecodesineachoftheseranges, butmayalsoneedtoassociatespecificlogictospecificcodes.Somecodescanbelim-itedsothattheyareonlygeneratediftheconsumerrequestsaspecialfeatureofHTTP, whichmeans that somecodes canbe leftunimplementedbyconsumers thatdonotrequestthesefeatures.

Uniformcontractexceptionsaregenerallystandardizedwithinthecontextofaparticu-larnewtypeofinteractionthatisrequiredbetweenservicesandconsumers.Theywilltypicallybeintroducedalongwithoneormorenewmethodsand/orheaders.Thiscon-textwillguidethekindofexceptionsthatarecreated.Forexample,itmaybenecessarytointroduceanewresponsecodetoindicatethatarequestcannotbefulfilledduetoalockonaresource.(WebDAVprovidesthe423 Lockedcodeforthispurpose.)

When introducingandstandardizingcustomresponsecodes fora service inventoryuniformcontractweneedtoensurethat:

• eachcustomcodeisappropriateandabsolutelynecessary

• thecustomcodeisgenericandhighlyreusablebyservices

• theextenttowhichserviceconsumerbehaviorisregulatedisnottoorestrictivesothatthecodecanapplytoalargerangeofpotentialsituations

• codevaluesaresettoavoidpotentialcollisionwithresponsecodesfromrelevantexternalprotocolspecifications

• codevaluesaresettoavoidcollisionwithcustomcodesfromotherserviceinven-tories(insupportofpotentialcross-serviceinventorymessageexchangesthatmayberequired)

Responsecodenumericrangescanbeconsideredaformofexceptioninheritance.Anycodewithinaparticularrangeisexpectedtobehandledbyadefaultsetoflogic,justasiftherangeweretheparenttypeforeachexceptionwithinthatrange.

13_9780137012510_ch10.indd 185 7/5/12 4:36 PM

Page 18: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

186 Chapter 10: Service-Oriented Design with REST

In thissection,wehavebrieflyexploredresponsecodeswithin thecontextofHTTP.However,itisworthnotingthatRESTcanbeappliedwithotherprotocols(andotherexceptionmodels).Itisultimatelythebaseprotocolofaserviceinventoryarchitecturethat will determine how normal and exceptional conditions are reported.

For example,youcouldconsiderhavingaREST-basedserviceinventorystandardizedontheuseofSOAPmessagesthatresult inSOAP-basedexceptions insteadofHTTPexceptioncodes.Thisallowstheresponsecoderangestobesubstitutedforinheritanceof exceptions.

designing Media types

During the lifetime of a service inventory architecture we can expect more changeswillberequiredtothesetofauniformcontract’smediatypesthantoitsmethods.Forexample,anewmediatypewillberequiredwheneveraserviceorconsumerneedstocommunicatemachine-readableinformationthatdoesnotmatchtheformatorschemarequirementsofanyexistingmediatype.

SomecommonmediatypesfromtheWebtoconsiderforserviceinventoriesandser-vicecontractsinclude:

• text/plain; charset=utf-8 for simple representations,suchasintegerandstringdata.Primitivedatacanbeencodedasstrings,asperbuilt-inXMLSchemadatatypes.

• application/xhtml+xml for more complex lists,tables,human-readabletext, hypermedialinkswithexplicitrelationshiptypes,andadditionaldatabasedonmicroformats.organdotherspecifications.

• text/uri-listforplainlistsofURIs.

• application/atom+xmlforfeedsofhuman-readableeventinformationorotherdatacollectionsthataretime-related(ortimeordered).

MorestandardmediatypescanbefoundintheIANAmediatyperegistry, as explained inAppendixB.Beforeinventingnewmediatypesforusewithinaserviceinventory, it isadvisabletofirstcarryoutasearchofestablishedindustrymediatypesthatmaybesuitable.

Whetherchoosingexistingmediatypesorcreatingcustomones, it ishelpfultocon-siderthefollowingbestpractices:

13_9780137012510_ch10.indd 186 7/5/12 4:36 PM

Page 19: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 187

• Eachspecificmediatypeshouldideallybespecifictoaschema.Forexam-ple, application/xml or application/jsonarenotschema-specific, while application/atom+xmlusedasasyndicationformatisspecificenoughtobe usefulforcontentnegotiationandtoidentifyhowtoprocessdocuments.

• Mediatypesshouldbeabstractinthattheyspecifyonlyasmuchinformationastheirrecipientsneedtoextractviatheirschemas.Keepingmediatypesabstractallowsthemtobereusedwithinmoreservicecontracts.

• Newmediatypesshouldreusematurevocabulariesandconceptsfromindustryspecificationswheneverappropriate.Thisreducestheriskthatkeyconceptshavebeenmissedorpoorlyconstructed,andfurtherimprovescompatibilitywithotherapplicationsofthesamevocabularies.

• Amediatypeshouldincludeahyperlinkwheneveritneedstorefertoarelatedresourcewhoserepresentationislocatedoutsidetheimmediatedocument.Linkrelationtypesmaybedefinedbythemediatype’s schema or, in some cases, sepa-rately,aspartofalinkrelationprofile.

• Custommediatypesshouldbedefinedwithmust-ignoresemanticsorotherextensionpointsthatallownewdatatobeaddedtofutureversionsofthemediatypewithoutoldservicesandconsumersrejectingthenewversion.

• Mediatypesshouldbedefinedwithstandardprocessinginstructionsthatdescribehowanewprocessorshouldhandleolddocumentsthatmaybemiss-ingsomeinformation.Usuallytheseprocessinginstructionsensurethatearlierversionsofadocumenthavecompatiblesemantics.Thisway, new services and consumersdonothavetorejecttheoldversions.

Allmedia types thatareeither invented foraparticularservice inventoryorreusedfromanothersourceshouldbedocumentedintheuniformcontractprofile, alongside thedefinitionofuniformmethods.

HTTPusesInternetmediatypeidentifiersthatconformtoaspecificsyntax.Custommediatypesareusuallyidentifiedwiththenotation:

application/vnd.organization.type+supertype

…where application is a common prefix that indicates that the type is used formachine consumption and standards. Theorganization field identifies the vendornamespace,whichcanoptionallyberegisteredwithIANA.

13_9780137012510_ch10.indd 187 7/5/12 4:36 PM

Page 20: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

188 Chapter 10: Service-Oriented Design with REST

The typepartisauniquenameforthemediatypewithintheorganization, while the supertypeindicatesthatthistypeisarefinementofanothermediatype.Forexample, application/vnd.com.examplebooks.purchase-order+xmlmayindicatethat:

• thetypeismeantformachineconsumption

• thetypeisvendor-specific,andtheorganizationthathasdefinedthetypeis“examplebooks.com”

• thetypeisforpurchaseorders(andmaybeassociatedwithacanonicalPurchaseOrderXMLschema)

• thetypeisderivedfromXML,meaningthatrecipientscanunambiguouslyhandlethecontentwithXMLparsers

Typesmeantformoregeneralinter-organizationalusecanbedefinedwiththemediatype namespace of the organization ultimately responsible for defining the type.Alternatively, they can be defined without the vendor identification information inplacebyregisteringeachtypedirectly,followingtheprocessdefinedintheRFC4288specification.

designing schemas for Media types

Withinaserviceinventory,mostcustommediatypescreatedtorepresentbusinessdataanddocumentswillbedefinedtogetherwithXMLschemas.Thisessentiallyappliesthe CanonicalSchema[437]patterninthatitestablishesasetofstandardizeddatamod-elsthatarereusedbyRESTserviceswithintheinventorytowhateverextentfeasible.

For this tobesuccessful,especiallywith largercollectionsofservices, schemas need tobedesignedtobeflexible.Thismeansthatitisgenerallypreferableforschemastoenforceacoarselevelofvalidationconstraintgranularitythatallowseachschematobeapplicableforusewithabroaderrangeofdatainteractionrequirements.

RESTrequiresmediatypesandtheirschemastobedefinedonlyattheuniformcontractlevel.Ifaservicecapabilityrequiresauniquedatastructureforaresponsemessage, itmuststilluseoneof thecanonicalmedia typesprovidedby theuniformcontract.Designing schemas to be flexible and weakly typed can accommodate a variety ofservice-specificmessageexchangerequirements.

13_9780137012510_ch10.indd 188 7/5/12 4:36 PM

Page 21: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.1 Uniform Contract Design Considerations 189

note

To explore techniques for weakly typing XML Schema definitions, see Chapters 6, 12, and 13 in the book Web Service Contract Design & Ver-sioning for SOA, as well as the description for the Validation Abstraction [518] pattern.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/schema/po" xmlns="http://example.com/schema/po"> <xsd:element name="LineItemList" type="LineItemListType"/> <xsd:complexType name="LineItemListType"> <xsd:element name="LineItem" type="LineItemType" minOccurs="0"/> </xsd:complexType> <xsd:complexType name="LineItemType"> <xsd:sequence> <xsd:element name="productID" type="xsd:anyURI"/> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="available" type="xsd:boolean" minOccurs="0"/> </xsd:sequence> </xsd:complexType></xsd:schema>

Example 10.1

One of the most straightforward ways of making a media type more reusable is todesigntheschematosupportalistofzeroormoreitems.Thisenablesthemediatypetopermitoneinstanceoftheunderlyingtype,butalsoallowsqueriesthatreturnzeroormoreinstances.Makingindividualelementswithinthedocumentoptionalcanalsoincreasereusepotential.

Service-Specific XML Schemas

It is technically possible for individual REST service contracts to introduce contract-specificXMLschemas,but indoingsoweneed toaccept that theUniformContract{400}constraintwillbeviolated.

13_9780137012510_ch10.indd 189 7/5/12 4:36 PM

Page 22: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

190 Chapter 10: Service-Oriented Design with REST

Thismaybewarrantedwhenaservicecapabilityneedstogeneratearesponsemessagecontaininguniquedata(orauniquecombinationofdata)forwhich:

• nosuitablecanonicalschemasexist

• nonewcanonicalschemashouldbecreatedduetothefactthatitwouldnotbereusablebyotherservices.

Aconsequenceofnon-compliancetoUniformContract {400} ispotentially increasedlevelsofnegativecouplingbetweenserviceconsumersandtheserviceofferingservicecapabilitiesbasedonservice-specificmediatypes.Service-specificmediatypesshouldbeclearlyidentifiedandeffortshouldbemadetominimizethequantityoflogicthatisdirectlyexposedtoandmadedependentuponthesetypes.

sUMMarY of KeY Points

• We can design and standardize custom HTTP methods and response codes. We can also standardize how built-in HTTP methods and response codes are used (or whether they are used).

• There are numerous existing media types we can choose to use (and reuse) within a service inventory, many of which are registered with the IANA (and other industry bodies). We can also design and standardize cus-tom media types to represent common types of data and documents that are exchanged within the service inventory.

• Schemas encompassed by media types are naturally standardized when made part of a uniform contract. For schemas to be reusable, they gener-ally need to be designed with flexibility in mind, ensuring reduced levels of validation constraint granularity.

13_9780137012510_ch10.indd 190 7/5/12 4:36 PM

Page 23: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 191

10.2 rest service contract design

This next section exploresdesigntechniquesandconsiderationsspecifictoindividualRESTservicecontractsandhowtheyrelatetotheiroverarchinguniformcontract.

designing services Based on service Models

InChapters4and9wedescribedthethreecommonservicemodelsusedtoestablishbasefunctionalcontextsthatcategorizeandgroupserviceswithinaserviceinventoryintothreecommonlogicallayers.ThechoiceofservicemodelforagivenRESTservicecanaffectourapproachtoservicecontractdesign.ThefollowingsectionsbrieflyraisesomekeyconsiderationsandprovideonesampleRESTservicecontractdesignforeachservice model.

Task Services

Task services willtypicallyhavefewservicecapabilities,sometimeslimitedtoonlyasingleone(Figure10.1).Thisisduetothefactthatataskservicecontract’sprimaryuseisfortheexecutionofautomatedbusinessprocess(ortask)logic.Theservicecapabil-itycanbebasedonasimpleverb,suchasStartorProcess.Thatverb, together with the nameof the taskservice (thatwill indicate thenatureof the task) isoftenall that isrequiredforsynchronoustasks.

Figure 10.1A sample task service, recognizable by the verb in its name. The contract only provides a single service capability that will be used by the composition initiator to trigger the execution of the Validate Timesheet business process that the task service logic encapsulates. In this case, the service capability receives a timesheet resource identifier that will be used as the basis of the validation logic, plus a unique consumer-generated request identifier that supports reliable triggering of the process. (Note that the composition initiator is explained in Chapter 11.)

AdditionalservicecapabilitiescanbeaddedtosupportasynchronousinteractionsasshowninFigure10.2.Forexample,tasksthatinvolvehumaninteractionorbatchpro-cessingwillretainthestateoftheon-goingbusinessprocessbetweenrequestsandwilltypicallyallowaccesstothisstatebyexposingservicecapabilitiesforthispurpose.

13_9780137012510_ch10.indd 191 7/5/12 4:36 PM

Page 24: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

192 Chapter 10: Service-Oriented Design with REST

REST-based task services will often have service capabilities triggered by a POSTrequest.However,thismethodisnotinherentlyreliable.AnumberoftechniquesexisttoachieveareliablePOST,includingtheinclusionofadditionalheadersandhandlingof response messages,ortheinclusionofauniqueconsumer-generatedrequestidenti-fierintheresourceidentifier.

Toprovideinputtoaparameterizedtaskserviceitwillmakesenseforthetaskservicecontracttoincludevariousidentifiersintothecapability’sresourceidentifiertemplate(that might have been parameters in a SOAP message). This frees up the service toexposeadditionalresourcesratherthandefiningacustommediatypeasinputtoitsprocessing.

Ifthetaskserviceautomatesalong-runningbusinessprocessitwillreturnaninterimresponsetoitsconsumerwhilefurtherprocessingstepsmaystillneedtotakeplace.Ifthetaskserviceincludesadditionalcapabilitiestocheckonorinteractwiththestateofthebusinessprocess(orcompositioninstance),itwilltypicallyincludeahyperlinktooneormoreresourcesrelatedtothisstateintheinitialresponsemessage.

Entity Services

Each entity service establishes a functional boundary associated with one or morerelatedbusinessentities(suchasinvoice, claim,customer,etc.).EntityservicesaretheprimemeansbywhichLogicCentralization[475]isappliedtobusinesslogicwithinaserviceinventory.Thetypesofservicecapabilitiesexposedbyatypicalentityservicearefocusedonfunctionsthatprocesstheunderlyingdataassociatedwiththeentity(orentities).Figure10.3providessomeexamples.

Entity service contracts are typically dominated by service capabilities that includeinherently idempotent and reliable GET, PUT, or DELETE methods. However, more complexmethodsmaybeneeded.Manyentityserviceswillneedtosupportupdating

Figure 10.2Two additional service capabilities are added to allow consumers to asynchronously check on the progress of the timesheet validation task, and to cancel the task while it is in progress.

13_9780137012510_ch10.indd 192 7/5/12 4:36 PM

Page 25: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 193

theirstateconsistentlywithchangestootherentityservices.Entityserviceswillalsooftenincludequerycapabilitiesforfindingentitiesorpartsofentitiesthatmatchcertaincriteria,andthereforereturnhyperlinkstorelatedandrelevantentities.

Utility Services

Utilityservicesare,likeentityservices,expectedtobeagnosticandreusable.However, unlikeentityservices,theydonotusuallyhavepre-definedfunctionalscopes.Whileindividual utility services group related service capabilities, the services’ functionalboundariescanvarydramatically.TheexampleillustratedinFigure10.4isautilityser-viceactingasawrapperforalegacysystem(aspertheLegacyWrapper[473]pattern).

note

To learn more about service models and service layers, see the Process Abstraction [486], Entity Abstraction [463], and Utility Abstraction [517] patterns.

Figure 10.3An entity service based on the invoice business entity that defines a functional scope that limits the service capabilities to performing invoice-related processing only. This agnostic Invoice service will be reused and composed by any automated business process that needs to work with or process invoice records. For example, the Invoice service may be invoked by the Validate Timesheet task service to retrieve invoice data linked to client information collected from a timesheet record. The Validate Timesheet service may then use this data to verify that what the client was billed matches what the employee logged in the timesheet.

Figure 10.4This utility service is based on the application of the Legacy Wrapper [473] pattern in that it provides a service contract that encapsulates a legacy HR system (and is accordingly named the HR System service). The service capabilities it exposes provide generic, read-only data access functions against the data stored in the underlying legacy repository. For example, the Employee entity service (composed by the Verify Timesheet task service) may invoke an employee data-related service capability to retrieve data. This type of utility service may provide access to one of several available sources of employee and HR-related data.

13_9780137012510_ch10.indd 193 7/5/12 4:36 PM

Page 26: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

194 Chapter 10: Service-Oriented Design with REST

designing and standardizing resource identifiers

ThefundamentalrequirementofaneffectiveRESTservicecontractdesignisitsabilitytoexpress the identityof resources thatconsumerscan interactwithaspartof theirservicecapabilityinvocations.

Atatechnicallevelthestructureofaresourceidentifierisoftenirrelevanttoaserviceconsumer.Anyserviceconsumerthat followsasimplehyperlinkonlycares that thedestinationofthehyperlinkisthecorrectresource.Itdoesn’ttrytointerpretthemean-ingoftheresourceidentifieritself,pasttheinformationrequiredtoactuallymaketheconnectiontotheresponsibleservice.

Withthatsaidthereareanumberofreasonsweproceedpastthepointofstandardizingthesyntaxofresourceidentifierstothepointofstandardizingstructureandvocabularywithinresourceidentifiers:

1. Themoredescriptiveandconsistentthestructureofresourceidentifiersisforsimilarservicecapabilities,theeasieritisforhumanstointerpretandunderstandservicesandtheircapabilities.ThisdirectlysupportstheapplicationofService Discoverability(420).

2. Someresourceidentifierstructureslendthemselvesbettertothefutureneedsoftheirservicecontractthanothers.Theydosobyprovidingobviousplaceswhereadditionalresourcesandrelatedcapabilitiescanbeinsertedintheresourceidenti-fiernamespace.

3. Designingflexibleresourceidentifierscanreducenegativecoupling, while increasingbackwardscompatibilityand,potentially,forwardscompatibility(asexplainedinChapter15).

4. Insomecases,serviceconsumersneedtoinsertinformationintoresourceidenti-fiers,eitherbyaddingdatavaluesintothequerycomponentofaURLusingastandardsyntax,orbyfollowingaURLtemplatetoinsertdatathroughouttheURL.Ifthevocabularyisnotreusablebetweenmultipleservicesthenthesevari-ableportionsofURLsbecomeabackdoorfornegativeformsofcouplingbetweentheconsumerstotheservicecontract.

ThelattertwoitemsdirectlysupporttheapplicationoftheServiceLooseCoupling(413)principle.

13_9780137012510_ch10.indd 194 7/5/12 4:36 PM

Page 27: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 195

Service Names in Resource Identifiers

The first area of standardization we’ll explore is the use of service names withinresourceidentifierstatements.ThisbringsusbacktothestudyofURIsyntax, which we beganintheURIs (and URLs and URNs)sectioninChapter6.Brieflyrevisitthissectiontore-familiarizeyourselfwiththeexamples.

Inthelastexampleprovidedinthissection:

invoices.example.com

…identifiestheservicewithintheURL:

http://invoices.example.com/

Anotherservice:

customers.example.com

…mayinitiallysharethesameIPaddressas:

invoices.example.com

…asaresultofbeingdeployedinasharedhostingenvironment.

Whencustomers.example.comismovedtoitsownseparatephysicalhardware,theIPaddressescanbeeasilyupdatedviatheDomainNameSystem(DNS)withoutmodify-ingthelogicalnameoftheservice.Consumersthatrefertocustomers.example.com willautomaticallybegincommunicatingwiththenewIPaddress, and therefore will placenofurtherburdenontheoldhostingenvironment.

If, instead, the service names were part of the pathoftheURL,theauthoritywouldhaveto refer to the hosting environment itself.

AURLfortheInvoiceservicethatstartswith:

http://services.example.com/invoice

…wouldalwaysresolvetotheIPaddressof:

services.example.com

…ratherthanaspecificIPaddressfortheservice.

13_9780137012510_ch10.indd 195 7/5/12 4:36 PM

Page 28: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

196 Chapter 10: Service-Oriented Design with REST

If the Customer service were then moved to a new hosting environment, all of the hyperlinksheldbyserviceconsumerswouldhavetochangeortherequestssenttotheservicewouldstillhavetocontinuepassingthroughtheservices.example.com host.

WhencombiningRESTwithservice-orientation,theauthorityneedstobesynonymouswith the service name in order to maximize the application potential of the ServiceAutonomy(SDP)principle.Theauthority isalwayswhat is lookedupbytheserviceconsumersothatitcanmakethenecessaryTCP/IPconnections.Itisalsousedtoiden-tifyproxiesbetweentheserviceanditsconsumers.Sometimes,multipleserviceswillbehostedwithinthesamevirtualserverorcluster, and these service names will resolve tothesameIPaddress.But,byensuringthateachservicehasauniqueauthority, the servicecanbeeasilyshiftedtootherIPaddressesasservicedeploymentarrangementschange.

Other URI Components

The path and query components of the URI provide context for service capabilitieswithin a given service. This context is combined with the service identifier in theauthorityandwiththemethodofeachrequesttodeterminewhichservicecapabilityagivenconsumerseekstoinvoke.

The {fragment}componentoftheURIreferenceisneversenttotheservice,andisonlyusedasaplaceholder tostore instructions for theserviceconsumertoknowhowtoprocesstheresponsewhenitarrives.Ifaserviceconsumerneedstousetheaforemen-tionedURIreferencetoinvokeaGETrequest,itwouldsendthepartoftheURIrefer-enceuptoandincludingthequery.The{fragment}componentwouldbeintentionallyomitted. For example, a page2 fragmentmayindicatetotheserviceconsumerthat itshouldstartprocessingatpage2inthereturneddocument.Whereexactlytofindsuchapointinthedocumentdependsonthemediatypeofthedocument.

IfsomeofthecomponentsofaURIaremissing,theURIreferencemaybecomearela-tiveURI. In that case, the contextof theURI isused todeterminewhatexactly it ispointing to.

For example,arelativeURIof:

/invoices/INV042

…wouldbeexpandedas:

http://invoice.example.com/invoices/INV042

13_9780137012510_ch10.indd 196 7/5/12 4:36 PM

Page 29: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 197

RelativeURIsareoftenausefulwaytorefertorelatedresourceswithoutreferringtoadditional context,suchasthenameoftheservice.ThebaseURItoresolvearelativeURIagainstcancomefromXMLdirectives,HTTPheaders, thelocationthatadocu-ment was retrieved from,orfromarangeofothersources, depending on the conven-tionsassociatedwiththemediatypeinuse.

Resource Identifier Overlap

Resources can be any specific utility, entity, task, queue, report, statistic, or in fact anythingrelatedtotheservicethatcanbereferredtoinacontext.Theidentifierforaresourcecancontainasmuchoraslittlecontextasisneededtospecifytheconcepttheresource embodies. A resource could be “today’s weather in Vancouver, Canada.” Aseparateresourcecouldcapture“yesterday’sweatherinVancouver, Canada”whileyetanotherfamilyofresourcescouldcapturetheweatherinVancouverforspecifichistori-caldates.Theconceptsthatresourcesembodywillsometimesoverlap, so that some or allofthesamedataisretrievedviadifferentresourceidentifiers.Otherresourceswillencapsulateconceptsthataredistinctintheirownrightanddonotoverlap.

WecanimaginethataURIsuchas:

http://weather/canada/vancouver/date/today

…willreturnthesamevaluewhenretrievedastheURI:

http://weather/canada/vancouver/date/{date}

…withadatesettotoday’s date. However,thesearedifferentresourcesandperhapseven different service capabilities. When the date switches over to the next day, the today resource will point to the new day’s weather. The resource based on the old{date}willstillrefertothehistoricalweatheratthatparticulardate.

Similarly,aninvoicemightappearasitsownURIbutmayalsohaveitsdatasumma-rizedaspartofaninvoicelistorreportresource.TheinvoiceURImayfurtherhavesub-ordinateresources,suchasaspecialresourceindicatingitspaidstatus.Inallofthesecases,theURIsaredifferent,butthedataandtheservicelogicthatimplementrequeststo each one overlap.

ThecontextoftheresourceasidentifiedinitsURImaybedynamicorsession-specific.For example,thefollowingURI:

http://mybank/accounts/myaccount?after=XACT102

13_9780137012510_ch10.indd 197 7/5/12 4:36 PM

Page 30: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

198 Chapter 10: Service-Oriented Design with REST

…mayrefertothetransactionsinabankaccountthatoccurredaftertransactionnum-ber102.Thismayhavebeenreturnedfromtheservicetoaparticularconsumerasaplaceholderbetweentransactionstheconsumerhasreconciledandthosethathavenotyetbeenreconciled.Thiskindofresourcecapturessessioninformationandactsasacontainer for session state, allowing the service to avoid having to retain these details.

Queriescanalsobeencapsulatedinresourceidentifiers.Queryterms,suchasarequiredtemperaturerangeorthemaximumtemperaturevaluepastaparticulardate,canbeincluded in a resource identifier. When the first request is sent to this identifier theresourceautomatically springs intoexistence, performs its processing, and returnsaresult.Theconsumerandanymiddlewarearenotawareofwhetheraresourceisstaticordynamic.Theinterfacetotheresourcedoesnotchange,andfeaturessuchascach-ing,workjustaswellwithstaticanddynamicresources.Theimplementationofeachresourceishiddenfromconsumers.

InChapter6wecovered theuseof formsandresource identifier templates toallowservice consumers to input parameters into resource identifiers without introducingservice-specificcoupling.IfURIsarebeingconstructedbyhumanusers,formscanbeprovidedforthemtofilloutaspartofproducingtheURI.Thisdoesnotintroducetightcouplingbetween the serviceandservice consumer, as the consumerdoesnotneedtounderstand thedata thatpasses through it.Only thehumanuserneeds todeter-minewhatdatatoplaceinwhichformfields.However,aserviceconsumerthatisnotbeingdrivenbyahumanuserwillneedtoknowwhichspecificvariablestoinsertintoagivenresourceidentifier.IfautomatedserviceconsumersaresupplyingparametersdirectlyaspartofURIs,itisadvisabletoclearlydifferentiatebetweenelementsoftheURIthatconsumersareconsideredlikelytohave,inordertopopulatethemselvesandtoidentifythesefieldsinawaythatisdocumentedintheuniformcontractprofilefortheserviceinventory.

For example,theaforementionedbankaccountURI:

http://mybank/accounts/myaccount?after=XACT102

…suggeststoreadersoftheservicecontractthatitislikelytobetheserviceconsumerthatfillsouttheafterfieldwithintheURI.Inorderforanautomatedserviceconsumertoavoidtightcouplingwiththeservicecontract, the afterfieldshouldbecomepartoftheuniformcontract.Whenafterisused,itshouldhavethesamemeaning, regardless ofwhichservicetheconsumeristalkingto.

13_9780137012510_ch10.indd 198 7/5/12 4:36 PM

Page 31: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 199

note

Resource identifiers contain data for their corresponding services to inter-pret. In order to invoke the correct service capability, the business context of a request must be specified by the consumer and understood by the service. As explained in previous chapters, resource identifiers can be discovered by a service consumer through hyperlinking, or by direct entry of resource identifiers into configuration data. In these cases the resource identifier can usually be treated as opaque by the service consumer. The consumer does not attempt to parse information out of the identifier, nor does it need to insert additional information. Resource identifier templates allow consumers to insert data into resource identifiers in predefined ways, while treating the overall structure of the resource identifiers as being opaque.

Resource identifiers that are handled in this manner by the service con-sumer act as a message from the service that is held onto by the con-sumer and passed back to the service with subsequent requests. These messages can contain identifiers for entities, session state data, or any other data the service will need the next time a request comes in for pro-cessing. Treating resource identifiers as opaque within service consumers means that we can reduce (or loosen) the coupling between a service and its consumers. The service can change the content or structure of its resource identifiers without needing corresponding changes to service consumer logic.

Resource Identifier Design Guidelines

HereareafewtipsforoptimizingresourceidentifiersinsupportofSOA.EachofthesecanformthebasisofadesignstandardinsupportoftheCanonicalExpression[434]pattern:

• TrytoavoidincludingavariablepartoftheURLasthefirstpathsegment,orany-wherenotprecededbyastaticpathsegmentdescribingthecontext.Forexample, avoid http://invoice.example.com/{invoice}.Althoughwemayusethistypeofnotationforsimplicity’ssakeearlyintheservicecapabilitymodelinglifecycle, onceweentertheservice-orienteddesignstageitcanmakeitdifficulttoextendthenamespace.Thisisbecauseanynewpathcouldbeinterpretedasincludinganinvoiceidentifier.Considerintroducingaprefixtoqualifythevariablepart, for exampleusinghttp://invoice.example.com/invoice/{invoice}, instead.

13_9780137012510_ch10.indd 199 7/5/12 4:36 PM

Page 32: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

200 Chapter 10: Service-Oriented Design with REST

• Trailingslashesusuallyindicateacollectionofresources.Onecommonconven-tionisthataGETrequesttoaURLwithatrailingslashwillretrievealistoftheseresources,whileaPOSTtotheURLwillcreateanewresource.Forexample, http://invoice.example.com/unpaid/maysupportaGETrequesttoobtainallunpaidinvoices,whileaPOSTtohttp://invoice.example.com/invoice/maycreateaninvoicewitharesourceidentifierofhttp://invoice.example.com/invoice/INV042.Thisagainisadeparturefromthenotationusedduringtheservice-orientedanalysisprojectstage,whereweusethetrailingslash, together with the initial slash,asdelimiterstorepresentaresource.

• Singleoutthoseresourceidentifiersthatarecanonicalnames(URNs), and make theseURLsassimpleaspossible.Avoidincludingaquerycomponentintheresourceidentifierandavoidspecialcharacterssuchas‘;’, ‘=’, and ‘&’. For exam-ple, http://invoice.example.com/?invoice=INV042isnotagoodidentifierforinvoicenumber42, while http://invoice.example.com/invoice/INV042 is abetterchoice.Simpleridentifiersareeasiertoembedintootherresourceidenti-fiers,andeasierforahumantoreadandunderstand;aprimerequirementoftheServiceDiscoverability(420)principle.

• Alwaysrefertocanonicalnames(URNs)bytheirfullresourceidentifier.Forexample, the http://invoice.example.com/query{?customer}URLshould beexpandedtohttp://invoice.example.com/query?customer=http:// customer.example.com/customer/C1234.ThisallowstheInvoiceservicetodirectlyinteractwiththecustomerresourceforadditionalinformation(ifrequired),withoutneedingtoconstructitsownresourceidentifierforthecustomer.

• ExplicitlyseparatequeryparametersexpectedtobeinsertedbyhumanusersorserviceconsumersintoresourceidentifiersinthequerycomponentoftheURL.For example, http://invoice.example.com/search{?paid,due-date, min-amount,max-amount,customer}canbeinterpretedasindicatingthatpaid, due-date, min-amount, max-amount, and customerarealllikelytobeinsertedintotheresourceidentifierviahumaninputorbyaserviceconsumer.Thevocabu-laryusedinthequerycomponentoftheresourceidentifierislikelytocomeunderincreasedgovernancescrutinycomparedtoothercomponentsoftheresource.

• VariablesthataserviceconsumerneedstoinsertintoURLtemplatescanpro-duceundesirableformsofcouplingtobeintroducedbetweentheconsumerandthe service contract. This is in direct opposition to the design goals of the Ser-viceLooseCoupling(413)principle.Eachvariabletobeinsertedneedstohave

13_9780137012510_ch10.indd 200 7/5/12 4:36 PM

Page 33: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 201

anagreeduponmeaningamongaserviceanditsconsumers.Thesimplestwaytotacklethisistostandardizethenames,syntax,datatypes, and meaning of variablesacrossmultipleservicesaspartoftheuniformcontractdefinition.Itisstraightforwardtoconsiderstandardizingvariablenamessuchasdtstart and dtendtoidentifythestartandenddatesandtimesofagivenquery.Forexample, thistypeofvocabularycanbereusedtoqueryaninvoiceserviceashttp://invoice.example.com/query?dtstart=2015-03-06T10:00:00&dtend=

2015-04-06T10:00:00, a calendar of events,oracorrespondencelogforparticu-lar time periods.

note

Business entities are prime targets for inclusion in a controlled resource identifier vocabulary. We have already seen examples in this chapter where a consumer queries the Invoice entity service for a list of invoices related to a particular customer. In this case, the expansion of this parameter would be the full resource identifier for that entity. As new service capabilities are defined, new vocabulary will be discovered. It will be important to keep the vocabulary up-to-date and to be able to identify which elements of the vocabulary are genuinely reused in practice across different service contracts, versus those that are service-specific.

designing with and standardizing rest constraints

Although the set of REST constraints are, individually, separate and distinct design rules with corresponding design goals, there is room for interpretation concerning whethereachconstraintshouldbestrictlyapplied.Duetotheimportanceofstandard-izinghowservicesarebuiltaspartofaserviceinventory, it is recommended that how RESTconstraintsthemselvesareappliedalsobeclearlystandardized.

Stateless {395}

ThetwobasicinterpretationsofrulesestablishedbytheStateless{395}constraintare:

• Thelooserinterpretationisthatsessionstateisanydatathatarequestmessagemightrefertothatdoesnothaveanexplicitresourceidentifier.Underthisdefini-tion,sessionstatecanbegivenaresourceidentifierwithintheservicetotransformitintoservicestate.Itcanthenbedeferredbytheserviceintoadatabaseorotherdedicatedrepository.Furtherrequests(bythesameconsumerorbyothercon-sumers)refertothestatebyitsresourceidentifierandsotheycanbeunderstoodindependentlyofpreviousrequests.

13_9780137012510_ch10.indd 201 7/5/12 4:36 PM

Page 34: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

202 Chapter 10: Service-Oriented Design with REST

• Astricterinterpretationisthatsessionstateisanydataboundtoaspecificserviceconsumerthatwouldnormallyneedtobedestroyedwhenthatconsumerexitsanon-goingserviceactivity,orwhenthatconsumerstopsinteractingwiththeser-vice. Under this interpretation,associatingaresourceidentifierwiththedatadoesnottransformitintoservicestateanditmuststillnotberetainedbytheservicebetweenrequests.

The usage of the Stateless {395} constraint requires a clear design standard, both inregards to the interpretation of the constraint as well as the extent to which it is applied totheserviceinventory.

Additionally, if any exceptions to or violations of Stateless {395} are allowed, these needtobewell-definedsothatthereisanopportunitytoadjusttheserviceinventory’s underlyinginfrastructureaccordingly.

Cache {398}

Asexplained inChapter5, thisconstraint requires thatanyrequestwhoseresponsecouldpotentiallybereusedforsubsequentrequestsneedstoincorporatethefacilitytoincludecachecontrolmetadata.Thisconstraintmostlyappliestodataretrievalmeth-ods,suchasGETandHEAD.However,itcanalsoapplytosomeusesofPOSTandotherformsofrequeststhatcanbeclassifiedasprimarilyretrievingdatafromaservice.

Twobasicformsofcachingexist:

• Aresponsemessageisconsideredreusableforaparticularperiodoftime.Forexample, a message containing report data can state that its content will remain validfor24hours.Thisallowsthecachinginfrastructuretocontinuereturningthesameresponsewithouthavingtore-invoketheserviceforthedurationofthatperiod.TheHTTPheaderusedforthiskindofcachingisCache-Control with a maxagefield.

• Aresponsemessageisconsideredreusableonlyifitsvalidityischeckedeachtimeitisused.Forexample,alogofrecenttransactionsmaybereuseduntilanewtransactionisadded.Inthiscase,eachtimeacachehandlesarequestitexplic-itlycheckswiththeservicetoensurethatnofurthertransactionshaveoccurredbeforereturningthecachedresponse.TheHTTPheadersusedforthiskindofcaching are ETag in responses and If-None-Matchinrequests.

Inordertodecidewhethertoevenattempttoreuseacachedresponsethecacheneedsamechanismfordeterminingwhethertworequestsareequivalentforcachingpurposes.Requests are often equivalent if their method and resource identifier are the same;

13_9780137012510_ch10.indd 202 7/5/12 4:36 PM

Page 35: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 203

however,requestheaderscanplayaroleinwhetherrequestsareequivalentornot.Insupportofthis,itcanbehelpfultointroduceadesignstandardregardingtheusageoftheHTTPVaryheaderthatcanbeappliedtoidentifywhichrequestheaderswereusedas part of generating a response and,byaprocessofelimination, which headers were ignored.Thisfeatureallowsrequeststhatareslightlydifferenttostillreusethesamecached response.

Inaddition toa responsebeingable to identifywhichrequestheaderswereused ingenerating the response,itishelpfultohaveafurtherdesignstandardthatestablishesacanonicalformforrequestmessagessothattheycanbecomparedforequivalence.HTTPhasabasiccanonicalizationmechanismthatcanbeusedtoremoveredundantwhitespaceandtomergeduplicateheaders.

Uniform Contract {400}

HTTPrequiresthatmethodsandmediatypesbe“standard.”InthecontextofRESTthisdoesnotsimplymeanstandardization,butinsteadrefersto“reuseinpractice”bymulti-ple services. Methods,mediatypes, headers,exceptiontypes,resourceidentifiersyntax, andanyotherelementofmessages(otherthanthespecificresourceidentifierschosenaspartofservicecontractstoexposeservicecapabilities)areallrequiredtobereusedbymultipleservicesinordertocomplywithUniformContract{400}.Insomecases(asdescribedearlier),evenpartsoftheresourceidentifiersmaybestandardizedaswell.

Although themereusageofauniformcontract introducesanatural levelof serviceinventory standardization, there are aspects that need further attention and customstandardization.

Designstandardsneedtobeinplacetoaddressthefollowing:

• Newmethodsandmediatypesaddedtotheuniformcontractneedtobeclearlyidentifiedandcloselymonitoredastheyprogresstowardamaturestate.Ifactualreusebymultipleservicecontractsdoesnothappen,itmaybenecessarytostarttreatingthesenewextensionsasbeingservice-specific.

• Anymethodsormediatypesthatareintendedtobeservice-specificneedtobegovernedassuchtoensurethatthequantityoflogicthatisdirectlyexposedtotheseextensionsisminimizedinfavorofcouplinglogictomorereusablemethodsandmediatypes.

• Someservicecontractsmayalsonotlendthemselvestocompliancewiththeinven-tory’soverarchinguniformcontract.Itcanthereforebeusefultohaveadesignstandardthatdeterminesunderwhatcircumstancesexceptionsmaybepermitted.

13_9780137012510_ch10.indd 203 7/5/12 4:36 PM

Page 36: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

204 Chapter 10: Service-Oriented Design with REST

Withregardstothelastitemontheprecedinglist,thereshouldbestronggovernanceinplacetoensurethatbeforeallowingservice-specificmethodsandmediatypes,uniformmethodsandmediatypesarealwayscarefullyandthoroughlyconsideredfirst.

Layered System {404}

LayeredSystem{404}requiresthatconsumersandservicesnotbeabletotellwhethertheyarecommunicatingwitheachotherdirectly, or via a series of intermediaries that understandtheuniformcontract.Tocomplywiththisconstraint, new methods need to be analyzed to ensure intermediaries are able to pass requests and responses ontowards their intended recipients,andtoadequatelyhidetheexistenceofintermediar-ieswhentheyarepresent.

OnekeyrequirementofLayeredSystem{404}isthatenoughinformationbepresentineach message for it to reach its intended recipient. This means we cannot,uponmakinga connection to the service,stripoutthedatathatallowedthatconnection.Forexam-ple, it isnotvalidtoremovetheservicenameembeddedwithinaresourceidentifieraftermakingaconnectiontotheservice.Iftheconnectionturnedouttoreallyonlybetoanintermediarythentheintermediarywouldnotbeabletodeterminewhichser-viceshouldreceivethemessage.Instead,allrequestsshouldincludetheirfullresourceidentifier.

Anotherrequirementisthatconsumersshouldnotneedtospeakadifferentprotocol, usedifferentmethods,orusedifferentheaderstocommunicatewithanintermediaryascomparedtocommunicatingwithanactualservice.Ifremovingtheintermediarystopsthecommunicationfromworking,thearchitectureisinbreachofLayeredSystem{404}.

sUMMarY of KeY Points

• Defining the reuse of uniform contract methods and media types is a service inventory responsibility, as is enforcing the compliance of these uniform contract elements to REST constraints as part of design standards.

• Services based on different service models will tend to introduce different service contract design considerations and characteristics.

• The use of resource identifiers can be standardized for a given service inventory at both the syntax and vocabulary levels.

13_9780137012510_ch10.indd 204 7/5/12 4:36 PM

Page 37: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 205

case stUdY exaMPle

By following proven REST service contract design techniques, together with cus-tomdesignstandardsestablishedspecificallyfortheMUAenterprise,MUAarchi-tectsusetheservicecandidatesmodeledinChapter9asinputforaservice-orienteddesign process.

Theresultsofthiseffortaredocumentedinthefollowingsections.

Confer Student Award Service Contract (Task)

Astudentwhosubmitsanawardconferral applicationwilldo so throughaWebbrowser.Aseparateuserinterfaceisthereforedesignedtoallowuserstoentertheapplicationdetails.Itisthesubmissionofthisbrowser-basedformthatinitiatesthetask service.

Uponreceivingthesubmission,aserver-sidescriptorganizestheformdataintoanXMLdocumentbasedonthefollowingmediatype:

application/vnd.edu.mua.student-award-conferral-application+xhtml+xml

Example10.2providesasubmittedapplicationformcompletedwithsampledatacol-lectedfromthehumanuser.Thisrepresentsthedatasetthatkick-startsanddrivestheexecutionofanentireinstanceoftheConferStudentAwardbusinessprocess.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" > <head> <title>Student Award Conferral Application</title> </head> <body> <p>Student: <a rel="student" href="http://student.mua.edu/student/555333"> John Smith (Student Number 555333) </a> </p> <p>Award: <a rel="award" href="http://award.mua.edu/award/BS/CompSci"> Bachelor of Science with Computer Science Major

13_9780137012510_ch10.indd 205 7/5/12 4:36 PM

Page 38: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

206 Chapter 10: Service-Oriented Design with REST

</a> </p> <p>Event: <a rel="event" href="http://event.mua.edu/fall-graduation"> fall graduation event </a> </p> </body></html>

Example 10.2Sample application data, as submitted to the Web server. This document structure contains both human-readable and machine-processable information.

Figure 10.5 displays the Confer Student Award ser-vicecontract.Theprecedingmediatypeisdeliberatelydesigned to include human-readable and machine-readabledatainaformsuitableforlong-termarchival.Thedocumentissubmittedtoaservicecapabilitycor-respondingdirectlytotheStartcapabilitydefinedintheConferStudentAwardservicecandidate(Figure9.13).

AsalsoshowninFigure10.5,duringthedesignprocessfor this service contract it was decided to add new ser-vicecapabilitiestoprovidethefollowingfunctions:

• DELETE /task/{id}–ThiscapabilitywasaddedtoallowanexecutinginstanceoftheConferStudentAwardbusinessprocesstobeterminated.

• GET /task/{id}–ThiscapabilityallowsthestateofanexecutinginstanceoftheConferStudentAwardbusinessprocesstobequeried.

NotethatthesensitivenatureofthiskindofapplicationmeansthattheGET /task/{id} capability can be accessed only by authorized staff and by the student. TheDELETE /task/{id}capabilityisonlyaccessiblebythestudenttocanceltheapplica-tion process.

Figure 10.5The Confer Student Award service contract.

13_9780137012510_ch10.indd 206 7/5/12 4:36 PM

Page 39: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 207

Event Service Contract (Entity)

TheEvententityserviceisequippedwithaGET /event/{id}servicecapabilityusedtoqueryeventinformationand which corresponds to the Get Details capabilitycandidatefromtheEventservicecandidate(Figure9.14).

During the service-oriented design pro-cess, architects decided to add further GET

/event/{id}/calendar and GET /event/{id}/

description capabilities (Figure 10.6) that allow fortheretrievalofmorespecificevent information.ThesecapabilitieswerenotaddedspecificallyinsupportoftheConferStudentAwardbusinessprocess,butmoresotoprovideabroaderrangeofanticipatedreusablefunctionality.

Award Service Contract (Entity)

InadditiontoimplementingthethreeservicecapabilitiesfromtheoriginalAwardservice candidate (Figure 9.15), SOA architects within MUA decide to make somefurtherchanges.

Back in Step 4 of the REST service modeling process (Chapter 9) MUA analystsdeterminedthatthefollowingactionwastobeencompassedbytheConferStudentAwardtaskservicelogic:

• VerifyStudentTranscriptQualifiesforAwardBasedonAwardConferralRules

However, with the rules being specific to each award type they determine that itshouldbetheAwardentityservicethatappliesthebulkoftheserules.Nevertheless, somegenericchecksdoneedtobeappliedsothelogicisdividedbetweentheConferStudentAwardtaskserviceandtheAwardentityservice.

ToavoidthetaskservicefromneedingtopassfulltranscriptdetailsintotheAwardentityserviceforverification,itisdecidedtouseacode-on-demandapproach.TheAward entity service provides the logic, but the logic is executed by the task ser-vice. The decision to define the logic centrally within the Award entity service isjustifiedbasedontheneedtoproducehuman-readableoutput(forstudents), along-sidemachine-readableoutput (for theConferStudentAwardservice).Asaresult,

Figure 10.6The Event service contract.

13_9780137012510_ch10.indd 207 7/5/12 4:36 PM

Page 40: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

208 Chapter 10: Service-Oriented Design with REST

the entity service provides a new GET /award/{id}/

conferral-rules service capability (Figure 10.7) thatsupports theoutputof two formats for the rules logic:the first in human-readable form and the second in aformthatcanbereadilyembeddedintothetaskservice’s logic.

MUA architects choose JavaScript for this purposebecause they find that JavaScript runtimes are read-ilyavailableformanyofthetechnologyplatformsthathave been used to develop services within the inven-tory. Choosing JavaScript over other technologies alsoaccountsforitbeingthelanguageofchoicefortheuser-interfacetieroftheserviceinventory.

The same service capability is able to return the conferral rules in JavaScript oras human-readable HTML. The decision as to which transformation to carry outdepends on which Acceptheaderwasprovidedbytheserviceconsumer.Forexam-ple,theConferStudentAwardtaskservicerequeststheapplication/javascript mediatype,whileserviceconsumersrequiringhuman-readableoutputwillrequestthe text/htmlmediatype.

Student Transcript Service Contract (Entity)

The Student service was originally intended as a centralized entity service thatwouldencompassallstudent-relatedfunctionalityanddataaccess.However, itera-tionsoftheRESTservicemodelingprocessthatoccurredsubsequenttotheexamplescoveredinChapter9resultedinaserviceinventoryblueprintthatrevealedtheStu-dentservicecandidateasbeingfarmorecoarsegrainedthananyother.ThiswasprimarilyduetothecomplexityoftheStudententityanditsrelationshipstootherrelated entities.

Uponreviewof theStudentservicecandidate itwasdeterminedtocreateasetofstudent-relatedentityservices.OneofthesemorespecializedvariationsbecametheStudentTranscriptservicecandidate(Figure10.8).

BecausetheConferStudentAwardbusinessprocessonlyrequiresaccesstostudenttranscript information,itonlyneedstocomposetheStudentTranscriptservice, not

Figure 10.7The Award service contract.

13_9780137012510_ch10.indd 208 7/5/12 4:36 PM

Page 41: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.2 REST Service Contract Design 209

theactualStudentservice.AsshowninFigure10.9, theStudentTranscriptservicecontainsservicecapabilitiesthatcorrespondtotheservicecapabilitycandidatespro-videdbytheStudentTranscriptservicecandidate.

Figure 10.8The Student Transcript service candidate that was defined subsequent to the Student service candidate from Chapter 9. This service effectively replaces the Student service in the Confer Student Award service composition.

Figure 10.9The Student Transcript service contract.

notification and document service contracts (Utility)

TheNotificationserviceandDocumentserviceprocesssimilarhuman-readabledata.Notificationssentviae-mailorhardcopycanbothbeencodedasahuman-readabledocumentformat,suchasHTMLorPDF.

TheNotificationserviceisretainedfore-mailnotificationswhiletheDocumentser-vicehasbeenevolved intoaprinter-centricandpostal-delivery-centricutilityser-vice.TheConferStudentAward task service cansendadocument to the studentinthepreferredformatbylookingupthepreferreddeliverymethodintheoriginalapplication form.

As shown in Figure 10.10, the Notification and Document services can each beinvokedwiththePOSTmethod.

13_9780137012510_ch10.indd 209 7/5/12 4:36 PM

Page 42: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

210 Chapter 10: Service-Oriented Design with REST

The sample student (John Smith) from the application form used as input for theConfer Student Award task service has nominated his contact preference with ahyperlink tomailto:[email protected]. The service inventory standardforhandlingsuchanaddressistotransformtheURLintohttp://notification.mua.edu/[email protected] and use a POST method for itsdelivery.JohnSmith’snotificationwillbedeliveredviae-mailtothisaddress.

Figure 10.10The Notification and Document service contracts.

13_9780137012510_ch10.indd 210 7/5/12 4:36 PM

Page 43: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 211

10.3 complex Method design

Theuniformcontractestablishesasetofbasemethodsusedtoperformbasicdatacom-municationfunctions.Aswe’ve explained,thishigh-leveloffunctionalabstractioniswhatmakestheuniformcontractreusabletotheextentthatwecanpositionitasthesole,over-archingdataexchangemechanismforanentireinventoryofservices.Besidesitsinherentsimplicity,thispartofaserviceinventoryarchitectureautomaticallyresultsinthebaselinestandardizationofservicecontractelementsandmessageexchange.

ThestandardizationofHTTPontheWorldWideWebresultsinaprotocolspecificationthatdescribes the things thatservicesandconsumers“may,” “should,” or “must” do tobecompliantwiththeprotocol.Theresultinglevelofstandardizationisintention-allyonlyashighasitneedstobetoensurethebasicfunctioningoftheWeb.Itleavesanumberofdecisionsastohowtorespondtodifferentconditionsuptothelogicwithinindividualservicesandconsumers.This“primitive”levelofstandardizationisimpor-tant to theWebwherewecanhavenumerous foreignserviceconsumers interactingwiththird-partyservicesatanygiventime.

A service inventory, however, often represents an environment that is private and controlled within an IT enterprise. This gives us the opportunity to customize thisstandardizationbeyondtheuseofcommonandprimitivemethods.Thisformofcus-tomizationcanbejustifiedwhenwehaverequirementsforincreasingthelevelsofpre-dictabilityandquality-of-servicebeyondwhattheWorldWideWebcanprovide.

For example, let’ssaythatwewouldliketointroduceadesignstandardwherebyallaccounting-related documents (invoices, purchase orders, credit notes, etc.) must beretrieved with logic that,uponencounteringaretrievalfailure,automaticallyretriestheretrievalanumberoftimes.Thelogicwouldfurtherrequirethatsubsequentretrievalattempts do not alter the state of the resource representing the business documents(regardlessofwhetheragivenattemptissuccessful).

With this type of design standard, we are essentially introducing a set of rules andrequirementsastohowtheretrievalofaspecifictypeofdocumentneedstobecarriedout. These are rules and requirements that cannot be expressed or enforced via thebase,primitivemethodsprovidedbyHTTP.Instead,wecanapplytheminadditiontothelevelofstandardizationenforcedbyHTTPbyassemblingthem(togetherwithotherpossibletypesofruntimefunctions)intoaggregateinteractions.Thisisthebasisofthecomplex method.

13_9780137012510_ch10.indd 211 7/5/12 4:36 PM

Page 44: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

212 Chapter 10: Service-Oriented Design with REST

Acomplexmethodencapsulatesapre-definedsetofinteractionsbetweenaserviceandaserviceconsumer.These interactionscan include the invocationofstandardHTTPmethods. To better distinguish these base methods from the complex methods thatencapsulatethem, we’llrefertobaseHTTPmethodsasprimitive methods(atermonlyusedwhendiscussingcomplexmethoddesign.)

Complexmethodsarequalifiedas“complex”becausethey:

• caninvolvethecompositionofmultipleprimitivemethods

• caninvolvethecompositionofaprimitivemethodmultipletimes

• canintroduceadditionalfunctionalitybeyondmethodinvocation

• canrequireoptionalheadersorpropertiestobesupportedbyorincludedinmessages

Aspreviouslystated,complexmethodsaregenerallycustomizedforandstandardizedwithinagivenserviceinventory.Foracomplexmethodtobestandardized, it needs to bedocumentedaspartoftheserviceinventoryarchitecturespecification.Wecandefineanumberofcommoncomplexmethodsaspartofauniformcontractthatthenbecomeavailableforimplementationbyallserviceswithintheserviceinventory.

Complex methods have distinct names. The complex method examples that we cover shortlyarecalled:

• Fetch–AseriesofGETrequeststhatcanrecoverfromvariousexceptions.

• Store–AseriesofPUTorDELETErequeststhatcanrecoverfromvariousexceptions.

• Delta–AseriesofGETrequeststhatkeepaconsumerinsyncwithchangingresourcestate.

• Async–Aninitialmodifiedrequestandsubsequentinteractionsthatsupportasynchronousrequestmessageprocessing.

Services that support a complex method communicate this by showing the methodname as part of a separate service capability (Figure 10.11), alongside the primitive methodsthatthecomplexmethodisbuiltupon.Whenprojectteamscreateconsumerprograms for certain services,theycandeterminetherequiredconsumer-sidelogicforacomplexmethodbyidentifyingwhatcomplexmethodstheservicesupports, as indi-catedbyitspublishedservicecontract.

13_9780137012510_ch10.indd 212 7/5/12 4:36 PM

Page 45: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 213

note

When applying the Service Abstraction (414) principle to REST service composition design, we may exclude entirely describing some of the primitive methods from the service contract. This can be the result of design standards that only allow the use of a complex method in certain situations. Going back to the previous example about the use of a com-plex method for retrieving accounting-related documents, we may have a design standard that prohibits these documents from being retrieved via the regular GET method (because the GET method does not enforce the additional reliability requirements).

Itisimportanttonotethattheuseofcomplexmethodsisbynomeansrequired.Out-sideofcontrolledenvironmentsinwhichcomplexmethodscanbesafelydefined, stan-dardized,andappliedinsupportoftheIncreasedIntrinsicInteroperabilitygoal, their useisuncommonandgenerallynotrecommended.Whenbuildingaserviceinventoryarchitecturewecanopttostandardizeoncertaininteractionsthroughtheuseofcom-plexmethodsorwecanchoosetolimitRESTserviceinteractiontotheuseofprimitivemethodsonly.Thisdecisionwillbebasedheavilyonthedistinctnatureofthebusinessrequirementsaddressedandautomatedbytheservicesintheserviceinventory.

Despite their name,complexmethodsareintendedtoaddsimplicitytoserviceinven-toryarchitecture.Forexample, let’simaginewechoosenottousepre-definedcomplexmethods and then realize that there are common rules or policies that should havebeenappliedtonumerousservicesandtheirconsumers.Inthiscase,wewillhavebuiltmultiple services and consumers that behave unpredictably. When a service returns

Figure 10.11An Invoice service contract displaying two service capabilities based on primitive methods and two service capabilities based on complex methods. We can assume that the two complex methods incorporate the use of the two primitive methods, but we can confirm this by studying the design specification that documents the complex methods.

13_9780137012510_ch10.indd 213 7/5/12 4:36 PM

Page 46: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

214 Chapter 10: Service-Oriented Design with REST

a redirection code,wecan’tbesurethatallconsumerswillactuponit, and a tempo-rarycommunicationfailurecanhaveunexpectedramifications.Lackofpolicycanalsoresult inunnecessarilyredundantmessageprocessing logic.The fact that the imple-mentationswillcontinuetoremainoutofsynchmakethisaconvolutedarchitecturethatisunnecessarilycomplex.Thisisexactlytheproblemthattheuseofcomplexmeth-ods is intended to avoid.

Theupcomingsectionsintroduceasetofsamplecomplexmethodsorganizedintotwosections:

• StatelessComplexMethods

• StatefulComplexMethods

Notethatthesemethodsarebynomeansindustrystandard.Theirnamesandthetypeofmessageinteractionsandprimitivemethodinvocationstheyencompasshavebeencustomizedtoaddresscommontypesoffunctionality.

note

The Case Study Example section at the end of this chapter further explores this subject matter. In this example, in response to specific busi-ness requirements, two new complex methods (one stateless, the other stateful) are defined.

stateless complex Methods

Thisfirstcollectionofcomplexmethodsencapsulatemessageinteractionsthatarecom-pliantwiththeStateless{395}constraint.

Fetch Method

InsteadofrelyingonlyonasingleinvocationoftheHTTPGETmethod(anditsassoci-atedheadersandbehavior)toretrievecontent,wecanbuildamoresophisticateddataretrievalmethodwithfeaturessuchas:

• automaticretryontimeoutorconnectionfailure

• requiredsupportforruntimecontentnegotiationtoensuretheserviceconsumerreceivesdatainaformitunderstands

13_9780137012510_ch10.indd 214 7/5/12 4:36 PM

Page 47: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 215

• requiredredirectionsupporttoensurethatchangestotheservicecontractcanbegracefullyaccommodatedbyserviceconsumers

• requiredcachecontroldirectivesupportbyservicestoensureminimumlatency, minimumbandwidthusage,andminimumprocessingforredundantrequests

We’llrefertothistypeofenhancedread-onlycomplexmethodasaFetch.Figure10.12showsanexampleofapre-definedmessageinteractionofaFetchmethoddesignedtoperformcontentnegotiationandautomaticretries.

Figure 10.12An example of a Fetch complex method comprised of consecutive GET method calls.

Store Method

WhenusingthestandardPUTorDELETEmethodstoaddnewresources, set the state of existing resources, or remove old resources, service consumers can suffer requesttimeoutsorexceptionresponses.AlthoughtheHTTPspecificationexplainswhateachexception means,itdoesnotimposerestrictionsastohowtheyshouldbehandled.Forthispurpose,wecancreateacustomStoremethodtostandardizenecessarybehavior.

TheStoremethodcanhaveanumberofthesamefeaturesasaFetch,suchasrequiringautomatic retryof requests, contentnegotiation support, andsupport for redirection

13_9780137012510_ch10.indd 215 7/5/12 4:36 PM

Page 48: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

216 Chapter 10: Service-Oriented Design with REST

exceptions.UsingPUTandDELETE,itcanalsodefeatlowbandwidthconnectionsbyalwayssendingthemostrecentstaterequestedbytheconsumer, rather than needing to completeearlierrequestsfirst.

ThesamewaythatindividualprimitiveHTTPmethodscanbeidempotent, the Store method can be designed to behave idempotently. By building upon primitive idem-potent methods,anyrepeated,successfulrequestmessageswillhavenofurthereffectafterthefirstrequestmessageissuccessfullyexecuted.

For example, when setting an invoice state from “Unpaid” to “Paid”:

• a“toggle”requestwouldnotbeidempotentbecauserepeatingtherequesttogglesthestatebackto“Unpaid.”

• the“PUT”requestisidempotentwhensettingtheinvoiceto“Paid”becauseithasthe same effect,nomatterhowmanytimestherequestisrepeated

ItisimportanttounderstandthattheStoreanditsunderlyingPUTandDELETErequestsarerequeststo service logic,notanactioncarriedoutontheservice’sunderlyingdata-base. As shown in Figure 10.13, these types of requests are stated in an idempotent

Figure 10.13An example of the interaction carried out by a Store complex method.

13_9780137012510_ch10.indd 216 7/5/12 4:36 PM

Page 49: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 217

mannerinordertoefficientlyallowfortheretryingofrequestswithouttheneedforsequencenumberstoaddreliablemessagingsupport.

note

Service capabilities that incorporate this type of method are an example of the application of the Idempotent Capability [470] pattern.

Delta Method

Itisoftennecessaryforaserviceconsumertoremainsynchronizedwiththestateofachangingresource.TheDeltamethodisasynchronizationmechanismthatfacilitatesstatelesssynchronizationofthestateofachangingresourcebetweentheservicethatownsthisstateandconsumersthatneedtostayinalignmentwiththestate.

TheDeltamethodfollowsprocessinglogicbasedonthefollowingthreebasicfunctions:

1. Theservicekeepsahistoryofchangestoaresource.

2. TheconsumergetsaURLreferringtothelocationinthehistorythatrepresentsthelasttimetheconsumerqueriedthestateoftheresource.

3. Thenexttimetheconsumerqueriestheresourcestate,theservice(usingtheURLprovidedbytheconsumer)returnsalistofchangesthathaveoccurredsincethelasttimetheconsumerqueriedtheresourcestate.

Figure10.14illustratesthisusingaseriesofGETinvocations.

The service provides a “main”resourcethatrespondstoGETrequestsbyreturningthecurrentstateoftheresource.Nexttothemainresourceitprovidesacollectionof“delta” resources thateachreturn the listofchanges fromanominatedpoint in thehistorybuffer.

TheconsumeroftheDeltamethodactivatesperiodicallyorwhenrequestedbythecoreconsumerlogic.Ifithasadeltaresourceidentifieritsendsitsrequesttothatlocation.Ifitdoesnothaveadeltaresourceidentifier,itretrievesthemainresourcetobecomesynchronized.Inthecorrespondingresponsetheconsumerreceivesalinktothedeltaforthecurrentpointinthehistorybuffer.ThislinkwillbefoundintheLink header (RFC5988)withrelationtypeDelta.

13_9780137012510_ch10.indd 217 7/5/12 4:36 PM

Page 50: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

218 Chapter 10: Service-Oriented Design with REST

Therequesteddeltaresourcecanbeinanyoneofthefollowingstates:

1. Itcanrepresentasetofoneormorechangesthathaveoccurredtothemainresourcesincethepointinhistorythatthedeltaresourceidentifierrefersto.Inthis case,allchangesinthehistoryfromthenominatedpointarereturnedalongwithalinktothenewdeltaforthecurrentpointinthehistorybuffer.ThislinkwillbefoundintheLinkheaderwithrelationtypeNext.

Figure 10.14An example of the message interaction encompassed by the Delta complex method.

13_9780137012510_ch10.indd 218 7/5/12 4:36 PM

Page 51: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 219

2. Itmaynothaveasetofchangesbecausenochangeshaveoccurredsinceitsnomi-natedpointinthehistorybuffer,inwhichcaseitcanreturnthe204 No Content responsecodetoindicatethattheserviceconsumerisalreadyup-to-dateandcancontinueusingthedeltaresourceforitsnextretrieval.

3. Changesmayhaveoccurred,butthedeltaisnowexpiredbecausethenominatedpointinhistoryisnowsooldthattheservicehaselectednottopreservethechanges.Inthissituation,theresourcecanreturna410 Gone code to indicate that theconsumerhaslostsynchronizationandshouldre-retrievethemainresource.

Deltaresourcesusethesamecachingstrategyasthemainresource.

Theservicecontrolshowmanyhistoricaldeltasitispreparedtoaccumulatebasedonhowmuchtimeitexpectsconsumerswilltake(onaverage)togetup-to-date, or in some caseswhereafullaudittrailismaintainedforotherpurposesthenumberofdeltascanbeindefinite.Theamountofspacerequiredtokeepthisrecordisconstantandpredict-ableregardlessof thenumberofconsumers, leaving itup toeach individualserviceconsumertokeeptrackofwhereitisinthehistorybuffer.

Async Method

This complex method providespre-definedinteractionsforthesuccessfulandcanceledexchangeofasynchronousmessages.ItisusefulforwhenagivenrequestrequiresmoretimetoexecutethanwhatthestandardHTTPrequesttimeoutsallow.

Normally,ifarequesttakestoolong,theconsumermessageprocessinglogicwilltimeoutoranintermediarywillreturna504 Gateway Timeout response code to the service consumer. The Async method provides a fallback mechanism for handling requestsand returning responses that does not require the service consumer to maintain itsHTTPconnectionopenforthetotaldurationoftherequestinteraction.

AsshowninFigure10.15,theserviceconsumerissuesarequest,butdoessospecifyingacall-backresourceidentifier.Iftheservicechoosestousethisidentifier, it responds with the 202 Accepted response code,andmayoptionallyreturnaresourceidentifierin the Locationheadertohelpittracktheplaceoftheasynchronousrequestinitspro-cessingqueue.Whentherequesthasbeenfullyprocessed,itsresultisdeliveredbytheservice,whichthenissuesaPUTorPOSTrequesttothecall-backaddressoftheserviceconsumer.

IftheserviceconsumerissuesaDELETErequest(asshowninFigure10.16)whiletheAsync request is still in theprocessingqueue (andbeforea response is returned), a

13_9780137012510_ch10.indd 219 7/5/12 4:36 PM

Page 52: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

220 Chapter 10: Service-Oriented Design with REST

Figure 10.15An asynchronous request interaction encompassed by the Async complex method.

Figure 10.16An asynchronous cancel interaction encompassed by the Async complex method.

separatepre-definedinteractioniscarriedouttocanceltheasynchronousrequest.Inthis case,noresponseisreturnedandtheservicecancelstheprocessingoftherequest.

Iftheconsumercannotlistenforcall-backrequests,itcanusetheasynchronousrequestidentifiertoperiodicallypolltheservice.Oncetherequesthasbeensuccessfullyhan-dled, it ispossible toretrieve its resultusing thepreviouslydescribedFetchmethodbeforedeletingtheasynchronousrequeststate.Servicesthatexecuteeitherinteractionencompassedbythismethodmusthaveameansofpurgingoldasynchronousrequestsifserviceconsumersareunavailabletopickupresponsesorotherwise“forget” to delete requestresources.

13_9780137012510_ch10.indd 220 7/5/12 4:36 PM

Page 53: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 221

stateful complex Methods

These next complexmethodsuseRESTasthebasisofservicedesignbutincorporateinteractionsthat intentionallybreachtheStateless{395}constraint.Althoughthesce-nariosrepresentedby thesemethodsarerelativelycommon in traditionalenterpriseapplication designs,thiskindofcommunicationisnotconsiderednativetotheWorldWideWeb.Theuseofstatefulcomplexmethodscanbewarrantedwhenweacceptthereductioninscalabilitythatcomeswiththisdesigndecision.

Trans Method

The Trans methodessentiallyprovidestheinteractionsnecessarytocarryoutatwo-phase commit between one service consumer and one or more services (as per theapplication of the AtomicTransaction[432]pattern).Changesmadewithinthetransac-tionareguaranteedtoeithersuccessfullypropagateacrossallparticipatingservices, or allservicesarerolledbacktotheiroriginalstates.

Thistypeofcomplexmethodrequiresa“prepare”functionforeachparticipantbeforeafinalcommitorrollbackiscarriedout.Functionalityofthissortisnotnativelysup-portedbyHTTP.Therefore,weneedtointroduceacustomPREP-PUTmethod(avari-antofthePUTmethod),asshowninFigure10.17.

InthisexamplethePREP-PUTmethodistheequivalentofPUT,butitdoesnotcommitthePUTaction.Adifferentmethodnameisusedtoensurethatiftheservicedoesnot

Figure 10.17An example of a Trans complex method, using a custom primitive method called PREP-PUT.

13_9780137012510_ch10.indd 221 7/5/12 4:36 PM

Page 54: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

222 Chapter 10: Service-Oriented Design with REST

understandhowtoparticipateintheTranscomplexmethod,itthenrejectsthePREP-PUTmethodandallowstheconsumertoabortthetransaction.

TocarryoutthelogicbehindatypicalTranscomplexmethodwillusuallyrequiretheinvolvementofa transactioncontroller toensure that thecommitandrollbackfunc-tionsaretrulyandreliablycarriedoutwithatomicity.

AlternativetransactionmodelsthathavevaryingdegreesofcompliancewithStateless{395}arefurtherexploredinChapter12.

PubSub Method

A variety of publish-subscribe options are available once it is decided to intention-allybreachtheStateless{395}constraint.AsexplainedintheEvent-Driven Messaging [465]pattern,thesetypesofmechanismsaredesignedtosupportreal-timeinteractionswhereaserviceconsumermustactimmediatelywhensomepre-determinedeventatagivenresourceoccurs.TheEvent-DrivenMessaging[465]patternisappliedasanalter-nativetotherepeatedpollingoftheresource,whichcannegativelyimpactperformanceifthepollingfrequencyisincreasedtodetectchangeswithminimaldelay.

Therearevariouswaysthatthiscomplexmethodcanbedesigned.Figure10.18illus-trates an approach that treats publish-subscribe messaging as a “cache-invalidation” mechanism.

Thisformofpublish-subscribeinteractionisconsidered“lightweight”becauseitdoesnotrequireservicestosendouttheactualchangestothesubscribers.Instead, it informs themthataresourcehaschangedbypushingouttheresourceidentifier,andthenreusesan existing,cacheableFetchmethodastheserviceconsumerspullthenewrepresenta-tionsofthechangedresource.

Theamountofstaterequiredtomanagethesesubscriptionsisboundtoonefixed-sizedrecordforeachserviceconsumer. Ifmultiple invalidationsqueueupforaparticularsubscribedevent,theycanbefoldedtogetherintoasinglenotification.Regardlessofwhethertheconsumerreceivesoneormultipleinvalidationmessages,itwillstillonlyneedtoinvokeoneFetchmethodtobringitselfup-to-datewiththestateofitsresourceseach time it sees one or more new invalidation messages.

ThePubSubmethodcanbefurtheradjustedtodistributesubscriptionloadandsessionstatestoragetodifferentplacesaroundthenetwork.Thistechniquecanbeparticularlyeffectivewithincloud-basedenvironmentsthatnaturallyprovidemultiple,distributedstorageresources.

13_9780137012510_ch10.indd 222 7/5/12 4:36 PM

Page 55: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 223

sUMMarY of KeY Points

• When designing both the uniform contract and individual service contracts, we can consider creating complex methods as part of the functions offered by the contracts.

• Complex methods encompass the aggregation of multiple primitive HTTP methods or the repeated execution of a single primitive HTTP method, along with other functional features that are part of predefined message interactions.

• Complex methods are ideally standardized so that the interaction behavior is consistent across all services and consumers that use them.

• Both stateless and stateful complex methods can be designed, although the latter variation is not REST-compliant.

Figure 10.18An example of a PubSub complex method based on cache invalidation. When the service determines that something has changed on one or more resources, it issues cache expiry notifications to its subscribers. Each subscriber can then use a Fetch complex method (or something equivalent) to bring the subscriber up-to-date with respect to the changes.

4: Resource changed()

: Consumer : Service

2: SUBSCRIBE(resource, callback resource)

3: Created(subscription resource)

1: Start Request()

6: OK

7: Begin fetch()

5: EXPIRE(callback resource)

9: OK(cache metadata, representation)

8: GET(resource, content negotiation metadata)

10: Unsubscribe()

12: OK

11: DELETE(subscription resource)

13_9780137012510_ch10.indd 223 7/5/12 4:36 PM

Page 56: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

224 Chapter 10: Service-Oriented Design with REST

case stUdY exaMPle

TheMUAteamresponsibleforservicedesignencountersanumberofrequirementsforaccessingandupdatingresourcestate.

Forexample:

• Oneserviceconsumerneedstoatomicallyreadthestateoftheresource, perform processing,andstoretheupdatedstatebacktotheresource.

• Anotherserviceconsumerneedstosupportconcurrentuseractionsthatmodifythesameresource.Theseactionsupdatecertainresourcepropertieswhileothersneed to remain the same.

Allowingindividualserviceconsumerstocontaindifferentcustomlogic thatper-forms these types of functions will inadvertently lead to problems and runtimeexceptionswhenanytwoserviceconsumersattemptupdatestothesameresourceat the same time.

MUAarchitectsconcludethatthesimplestwaytoavoidthisistointroduceanewcomplex method that ensures that a resource is locked while being updated by agivenconsumer.Usingtherulesofoptimisticlocking,anapproachcommonlytradi-tionallyusedwithdatabaseupdates,theyareabletocreateacomplexmethodthatisstatelessandtakesadvantageofexistingstandardfeaturesoftheHTTPprotocol.Theynamethemethod“OptLock”andwriteupanofficialdescriptionthatismadepartoftheuniformcontractprofile:

optlock complex Method

If twoseparateserviceconsumersattempt toupdate thestateofa resourceat thesame time,theiractionswillclearlyconflictwitheachotherastheoutcomedependsontheorderinwhichtheirrequestsreachtheservice.TheOptLockmethod(Figure10.19)addressesthisproblembyprovidingameansbywhichaserviceconsumercandeterminewhetherthestateofaresourcehaschangedsinceitwaslastreadbytheconsumerbeforeattemptinganupdate.

Specifically,aconsumerwillfirstretrievethecurrentstateassociatedwitharesourceidentifier using the Fetch method. Along with the data the consumer receives an“ETag.”ETagisaconceptfromHTTPthatuniquelyidentifiestheversionofaresource

13_9780137012510_ch10.indd 224 7/5/12 4:36 PM

Page 57: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 225

inanopaqueway.WhenevertheresourcechangesstateitsETagisguaranteedtobedifferent.When the service consumer initiatesaStore, itdoes soconditionallybyrequestingtheservicetoonlyhonortheStoreinteractioniftheresource’s ETag still matches the one that it had when fetched. This is done with the If-Match header. TheservicecanusetheETagvalueintheconditiontodetectwhethertheresourcestatehasbeenchangedinthemeantime.

TheOptLockcomplexmethoddoesnot introduceanynew features toHTTP, butinsteadintroducesnewrequirementsforhandlingGETandPUTrequests.Specifi-cally,theGETrequestmustreturnanETagvalueandthePUTrequestmustprocessthe If-Match header. And, if the resource has changed, the service must furtherguaranteenottocarryoutthePUTrequest.

ThereareseveraltechniquesforcomputingETags.Somecomputeahashvalueoutofthestateinformationassociatedwiththeresource,somesimplykeepa“last modi-fied”timestampforeachresource,andotherstracktheversionoftheresourcestateexplicitly.

Figure 10.19An example of an OptLock complex method.

13_9780137012510_ch10.indd 225 7/5/12 4:36 PM

Page 58: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

226 Chapter 10: Service-Oriented Design with REST

The OptLock method may not scale effectively for high concurrent access to a particular resource. If consumer update requests are denied with an HTTP 409 Conflict response code, the OptLock method prescribes how the consumer canrecoverbyfetchinganewerversionoftheresourceoverwhichtheyhavetore-com-putethechangeandretrytheStoremethod.However,thismayfailagainduetoaconflictingupdaterequest.Serviceconsumersthat interactwitharesource inthiswayrelyonthatparticularresourcehavingrelativelylowratesofwriteaccess.

TheOptLockcomplexmethodbecomesavailableaspartoftheuniformcontractandisimplementedbyseveralservices.However,scenariosemergewhereamultiplecon-sumersattempttomodifytheresourceatthesametime,causingregularexceptionsand failed updates. These situations occur during peak usage times and becauseconcurrentusagevolumeisexpectedtoincreasefurther, it is determined that a more efficientmeansofserializingupdatestotheresourceneedstobeestablished.

ItisproposedthattheOptLockcomplexmethodbechangedtoperformpessimisticlocking instead,asperthefollowingPesLockcomplexmethoddescription:

Peslock complex Method

Pessimisticlockingprovidesgreaterflexibilityandcertaintythanoptimisticlocking.From a REST perspective,thiscomesatthecostofintroducingstatefulinteractionsandlimitingconcurrentaccesswhilethepessimisticlockisheld.

AsshowninFigure10.20,theWebDAVextensionstoHTTPprovidelockingprimi-tivesthatcanbeusedwithinacompositionarchitecturethatintentionallybreachestheStateless{395}constraint.Oneconsumermaylockoutothersfromaccessingaresource,socaremustbetakenthatappropriateaccesscontrolpoliciesareinplace.Consumerscanalsofailwhilethelockisheld,whichmeansthatlocksmustbeabletotimeoutindependentlyoftheconsumersthatregisterthem.

Thisway,theserviceconsumerwouldbeabletolocktheresourceforaslongasittakes to read the state,modify it, andwrite itbackagain.Althoughother serviceconsumerswouldstillencounterexceptionswhileattemptingtoupdatetheresourceatthesametimeastheconsumerthathaslockedit, it isdeemedpreferabletotheunpredictabilityofmanagingtheresourceaspartofanoptimisticlockingmodel.

13_9780137012510_ch10.indd 226 7/5/12 4:36 PM

Page 59: SOA with REST - Arcitura · SOA with REST Principles, Patterns & Constraints for Building Enterprise Solutions with REST PEcR nTi E HAll Upper Saddle river, NJ • BoStoN • iNdiaNapoliS

10.3 Complex Method Design 227

ThissolutionisnotembracedbyalloftheMUAarchitectsbecauseretainingthelockontheresourcerequiresthattheStateless{395}constraintbebreached.Itcouldfur-therleadtothedangerofstalelocksstartingtoimpactperformanceandscalability.Inparticular,unlesspropermeasuresaretakentoensurethatonlyauthorizedcon-sumersmaylockaresource,thisexposestheresourcestodenialofserviceattacksbymaliciousconsumersthatcouldlockoutallotherconsumers.

After further discussion, a compromise is reached. The OptLock method will beattempted first. As a fallback, if the consumer tries three times and fails, it will attemptthestatefulPesLockmethodtoensureitisabletocompletetheaction.

Figure 10.20An example of a PesLock complex method.

13_9780137012510_ch10.indd 227 7/5/12 4:36 PM