Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 40

RESTful Service Best Practices

RESTful Service Best Practices


Recommendations for Creating Web Services

Todd Fredrich Pearson eCollege @tfredrich www.RestApiTutorial.com

03/26/14

www.RestApiTutorial.com

Page 1 of 40

RESTful Service Best Practices

03/26/14

www.RestApiTutorial.com

Page 2 of 40

RESTful Service Best Practices

Table of Contents
Document Histor ......................................................................................................................................! "#o $#oul% Rea% T#is Document.............................................................................................................! &ntro%uction................................................................................................................................................6 "#at is R'$T(...........................................................................................................................................6 )niform &nterface..................................................................................................................................* Resource+,ase%................................................................................................................................* -anipulation of Resources T#roug# Representations......................................................................* $elf+%escripti.e -essages................................................................................................................* H perme%ia as t#e 'ngine of Application $tate /HAT'0A$1.........................................................* $tateless.................................................................................................................................................* 2ac#ea3le..............................................................................................................................................4 2lient5ser.er.........................................................................................................................................4 6a ere% s stem......................................................................................................................................4 2o%e on %eman% /optional1...................................................................................................................4 R'$T 7uic8 Tips.......................................................................................................................................9 )se HTTP :er3s to -ean $omet#ing...................................................................................................9 $ensi3le Resource ;ames.....................................................................................................................9 <-6 an% =$0;.....................................................................................................................................9 2reate >ine+?raine% Resources...........................................................................................................10 2onsi%er 2onnecte%ness......................................................................................................................10 Definitions................................................................................................................................................10 &%empotence........................................................................................................................................10 $afet ...................................................................................................................................................11 HTTP :er3s..............................................................................................................................................11 ?'T.....................................................................................................................................................11 P)T.....................................................................................................................................................12 P0$T...................................................................................................................................................12 P)T .s P0$T for 2reation..................................................................................................................13 D'6'T'..............................................................................................................................................13 Resource ;aming.....................................................................................................................................14 Resource )R& '@amples.....................................................................................................................1! Resource ;aming Anti+Patterns..........................................................................................................16 PluraliAation.........................................................................................................................................16 Returning Representations.......................................................................................................................1* Resource Disco.era3ilit T#roug# 6in8s /HAT'0A$ contB%1...........................................................14 -inimal 6in8ing Recommen%ations..............................................................................................19 6in8 >ormat....................................................................................................................................19 "rappe% Responses.............................................................................................................................21 Han%ling 2ross+Domain &ssues...........................................................................................................22 $upporting 20R$...........................................................................................................................22 $upporting =$0;P..........................................................................................................................22 7uer ingC >iltering an% Pagination..........................................................................................................23 6imiting Results..................................................................................................................................24 03/26/14 www.RestApiTutorial.com Page 3 of 40

RESTful Service Best Practices 6imiting .ia t#e Range Hea%er.......................................................................................................2! 6imiting .ia 7uer +$tring Parameters............................................................................................2! Range+,ase% Responses.................................................................................................................2! Pagination............................................................................................................................................26 >iltering an% $orting Results...............................................................................................................2* >iltering..........................................................................................................................................2* $orting............................................................................................................................................24 $er.ice :ersioning...................................................................................................................................24 $upport :ersioning .ia 2ontent ;egotiation.......................................................................................29 "#at .ersion is returne% w#en no .ersion is specifie%(.................................................................31 )nsupporte% :ersions ReDueste%...................................................................................................31 "#en $#oul% & 2reate a ;ew :ersion(...............................................................................................32 2#anges t#at will 3rea8 contracts...................................................................................................32 2#anges consi%ere% non+3rea8ing..................................................................................................33 At "#at 6e.el $#oul% :ersioning 0ccur(..........................................................................................33 )se 2ontent+6ocation to 'n#ance Responses.....................................................................................33 6in8s wit# 2ontent+T pe.....................................................................................................................33 >in%ing 0ut "#at :ersions are $upporte%..........................................................................................33 How man .ersions s#oul% & support at once(...............................................................................33 Deprecate%......................................................................................................................................33 How %o & inform clients a3out %eprecate% resources(....................................................................34 Date/Time Han%ling.................................................................................................................................34 Date/Time $erialiAation &n ,o% 2ontent...........................................................................................34 Date/Time $erialiAation &n HTTP Hea%ers..........................................................................................3! $ecuring $er.ices.....................................................................................................................................3! Aut#entication.....................................................................................................................................3! Transport $ecurit ...............................................................................................................................36 Aut#oriAation.......................................................................................................................................36 Application $ecurit ............................................................................................................................36 2ac#ing an% $cala3ilit ...........................................................................................................................3* T#e 'Tag Hea%er............................................................................................................................3* HTTP $tatus 2o%es /Top 101...................................................................................................................39 A%%itional Resources...............................................................................................................................40 ,oo8s...................................................................................................................................................40 "e3sites...............................................................................................................................................40

03/26/14

www.RestApiTutorial.com

Page 4 of 40

RESTful Service Best Practices

Document History
Date >e3 10C 2012 Apr 24C 2012 -a 29C 2012 Aug 2C 2013 Version Draft .1.0 .1.1 .1.2 Description &nitial %raft .ersion. &nitial pu3lic /non+%raft1 .ersion. -inor up%ates to correct misspellings an% clarif wor%ing after fee%3ac8 from AP& ,est Practices Tas8 force. )p%ate% .ersioning section. A%%itional minor corrections of misspellingsC wor%ingC etc.

Who Should Read This Document


T#is 3est+practices %ocument is inten%e% for %e.elopers w#o are intereste% in creating R'$Tful "e3 ser.ices t#at pro.i%e #ig# relia3ilit an% consistenc across multiple ser.ice suites. , following t#ese gui%elinesC ser.ices are well positione% for rapi%C wi%esprea%C pu3lic a%option 3 3ot# internal an% e@ternal clients. T#e gui%elines in t#is %ocument are also appropriate for support engineers w#ere t#e %esire to ser.ices %e.elope% using t#ese 3est practices. "#ile t#eir concerns ma 3e focuse% on cac#ing practicesC pro@ rulesC monitoringC securit an% suc#C t#is %ocument ma 3e useful as an o.erarc#ing ser.ice %ocumentation gui%e of sorts. A%%itionall C management personnel ma 3enefit from t#ese gui%elines 3 en%ea.oring to un%erstan% t#e effort reDuire% to create ser.ices t#at are pu3licl consuma3le an% offer #ig# le.els of consistenc across t#eir ser.ice suites.

03/26/14

www.RestApiTutorial.com

Page ! of 40

RESTful Service Best Practices

Introduction
T#ere are numerous resources on 3est practices for creating R'$Tful we3 ser.ices /see t#e Resources section at t#e en% of t#is %ocument1. -an of t#e a.aila3le resources are conflictingC %epen%ing on w#en t#e were written. PlusC rea%ing an% compre#en%ing se.eral 3oo8s on t#e su3Eect in or%er to implement ser.ices FtomorrowG is not %oa3le. &n or%er to facilitate t#e Duic8 upta8e an% un%erstan%ing of R'$Tful conceptsC wit#out reDuiring t#e rea%ing of at least t#ree to fi.e 3oo8s on t#e su3EectC t#is gui%e is meant to spee% up t#e processHcon%ensing R'$T 3est practices an% con.entions into Eust t#e #ig# points wit# not a lot of %iscussion. R'$T is more a collection of principles t#an it is a set of stan%ar%s. 0t#er t#an its o.er+arc#ing si@ constraints not#ing is %ictate%. T#ere are I3est practicesI an% %e+facto stan%ar%s 3ut t#ose are constantl e.ol.ingHwit# religious 3attles waging continuousl . Designe% to 3e 3riefC t#is %ocument pro.i%es recommen%ations an% some coo83oo8+st le %iscussion on man of t#e common Duestions aroun% R'$T an% pro.i%es some s#ort 3ac8groun% information to offer support for effecti.e creation of real+worl%C pro%uction+rea% C consistent R'$Tful ser.ices. T#is %ocument aggregates information a.aila3le in ot#er sourcesC a%apting it wit# e@perience gaine% t#roug# #ar% 8noc8s. T#ere is still consi%era3le %e3ate as to w#et#er R'$T is 3etter t#an $0AP /an% .ice .ersa1C an% per#aps t#ere are still reasons to create $0AP ser.ices. "#ile touc#ing on $0APC t#is %ocument wonBt spen% a lot of time %iscussing t#e relati.e merits. &nstea%C 3ecause tec#nolog an% t#e in%ustr marc#es onC we will procee% wit# t#e assumption t#at le.eraging R'$T is t#e current 3est practice for "e3 ser.ice creation. T#e first section offers an o.er.iew of w#at R'$T isC its constraintsC an% w#at ma8es it uniDue. T#e secon% section supplies some Duic8 tips as little remin%ers of R'$T ser.ice concepts. 6ater sections go more in %ept# to pro.i%e t#e "e3 ser.ice creator more support an% %iscussion aroun% t#e nitt +gritt %etails of creating #ig#+Dualit R'$T ser.ices capa3le of 3eing pu3licl e@pose% in a pro%uction en.ironment.

What is REST?
T#e R'$T arc#itectural st le %escri3es si@ constraints. T#ese constraintsC applie% to t#e arc#itectureC were originall communicate% 3 Ro >iel%ing in #is %octoral %issertation /see #ttpJ//www.ics.uci.e%u/Kfiel%ing/pu3s/%issertation/restLarc#Lst le.#tm1 an% %efines t#e 3asis of R'$Tful+st le. T#e si@ constraints areJ )niform &nterface $tateless 2ac#ea3le 2lient+$er.er 6a ere% $ stem 2o%e on Deman% www.RestApiTutorial.com Page 6 of 40

03/26/14

RESTful Service Best Practices A more %etaile% %iscussion of t#e constraints followsJ

Uniform Interface
T#e uniform interface constraint %efines t#e interface 3etween clients an% ser.ers. &t simplifies an% %ecouples t#e arc#itectureC w#ic# ena3les eac# part to e.ol.e in%epen%entl . T#e four gui%ing principles of t#e uniform interface areJ

Resource-Based
&n%i.i%ual resources are i%entifie% in reDuests using )R&s as resource i%entifiers. T#e resources t#emsel.es are conceptuall separate from t#e representations t#at are returne% to t#e client. >or e@ampleC t#e ser.er %oes not sen% its %ata3aseC 3ut rat#erC some HT-6C <-6 or =$0; t#at represents some %ata3ase recor%s e@presse%C for instanceC in >innis# an% enco%e% in )T>+4C %epen%ing on t#e %etails of t#e reDuest an% t#e ser.er implementation.

Mani ulation of Resources Throu!h Re resentations


"#en a client #ol%s a representation of a resourceC inclu%ing an meta%ata attac#e%C it #as enoug# information to mo%if or %elete t#e resource on t#e ser.erC pro.i%e% it #as permission to %o so.

Self-descri ti"e Messa!es


'ac# message inclu%es enoug# information to %escri3e #ow to process t#e message. >or e@ampleC w#ic# parser to in.o8e ma 3e specifie% 3 an &nternet me%ia t pe /pre.iousl 8nown as a -&-' t pe1. Responses also e@plicitl in%icate t#eir cac#e+a3ilit .

Hy ermedia as the En!ine of #

lication State $H#TE%#S&

2lients %eli.er state .ia 3o% contentsC Duer +string parametersC reDuest #ea%ers an% t#e reDueste% )R& /t#e resource name1. $er.ices %eli.er state to clients .ia 3o% contentC response co%esC an% response #ea%ers. T#is is tec#nicall referre%+to as # perme%ia /or # perlin8s wit#in # perte@t1. Asi%e from t#e %escription a3o.eC HAT'0$ also means t#atC w#ere necessar C lin8s are containe% in t#e returne% 3o% /or #ea%ers1 to suppl t#e )R& for retrie.al of t#e o3Eect itself or relate% o3Eects. "eBll tal8 a3out t#is in more %etail later. T#e uniform interface t#at an R'$T ser.ices must pro.i%e is fun%amental to its %esign.

Stateless
As R'$T is an acron m for REpresentational State TransferC statelessness is 8e . 'ssentiall C w#at t#is means is t#at t#e necessar state to #an%le t#e reDuest is containe% wit#in t#e reDuest itselfC w#et#er as part of t#e )R&C Duer +string parametersC 3o% C or #ea%ers. T#e )R& uniDuel i%entifies t#e resource an% t#e 3o% contains t#e state /or state c#ange1 of t#at resource. T#en after t#e ser.er %oes itBs processingC t#e appropriate stateC or t#e piece/s1 of state t#at matterC are communicate% 3ac8 to t#e client .ia #ea%ersC status an% response 3o% . 03/26/14 www.RestApiTutorial.com Page * of 40

RESTful Service Best Practices -ost of us w#o #a.e 3een in t#e in%ustr for a w#ile are accustome% to programming wit#in a container w#ic# pro.i%es us wit# t#e concept of FsessionG w#ic# maintains state across multiple HTTP reDuests. &n R'$TC t#e client must inclu%e all information for t#e ser.er to fulfill t#e reDuestC resen%ing state as necessar if t#at state must span multiple reDuests. $tatelessness ena3les greater scala3ilit since t#e ser.er %oes not #a.e to maintainC up%ate or communicate t#at session state. A%%itionall C loa% 3alancers %onBt #a.e to worr a3out session affinit for stateless s stems. $o w#atBs t#e %ifference 3etween state an% a resource( $tateC or application stateC is t#at w#ic# t#e ser.er cares a3out to fulfill a reDuestH%ata necessar for t#e current session or reDuest. A resourceC or resource stateC is t#e %ata t#at %efines t#e resource representationHt#e %ata store% in t#e %ata3aseC for instance. 2onsi%er application state to 3e %ata t#at coul% .ar 3 clientC an% per reDuest. Resource state, on t#e ot#er #an%C is constant across e.er client w#o reDuests it. '.er #a% 3ac8+3utton issues wit# a we3 application w#ere it went A"06 at a certain point 3ecause it e@pecte% ou to %o t#ings in a certain or%er( T#atBs 3ecause it .iolate% t#e statelessness principle. T#ere are cases t#at %onBt #onor t#e statelessness principleC suc# as t#ree+legge% 0Aut#C AP& call rate limitingC etc. Howe.erC ma8e e.er effort to ensure t#at application state %oesnBt span multiple reDuests of our ser.ice/s1.

Cacheable
As on t#e "orl% "i%e "e3C clients can cac#e responses. Responses must t#ereforeC implicitl or e@plicitl C %efine t#emsel.es as cac#ea3leC or notC to pre.ent clients reusing stale or inappropriate %ata in response to furt#er reDuests. "ell+manage% cac#ing partiall or completel eliminates some client5 ser.er interactionsC furt#er impro.ing scala3ilit an% performance.

Clientserver
T#e uniform interface separates clients from ser.ers. T#is separation of concerns means t#atC for e@ampleC clients are not concerne% wit# %ata storageC w#ic# remains internal to eac# ser.erC so t#at t#e porta3ilit of client co%e is impro.e%. $er.ers are not concerne% wit# t#e user interface or user stateC so t#at ser.ers can 3e simpler an% more scala3le. $er.ers an% clients ma also 3e replace% an% %e.elope% in%epen%entl C as long as t#e interface is not altere%.

Layered system
A client cannot or%inaril tell w#et#er it is connecte% %irectl to t#e en% ser.erC or to an interme%iar along t#e wa . &nterme%iar ser.ers ma impro.e s stem scala3ilit 3 ena3ling loa%+3alancing an% 3 pro.i%ing s#are% cac#es. 6a ers ma also enforce securit policies.

Code on demand (optional)


$er.ers are a3le to temporaril e@ten% or customiAe t#e functionalit of a client 3 transferring logic to it t#at it can e@ecute. '@amples of t#is ma inclu%e compile% components suc# as =a.a applets an% client+si%e scripts suc# as =a.a$cript. 2ompl ing wit# t#ese constraintsC an% t#us conforming to t#e R'$T arc#itectural st leC will ena3le an 03/26/14 www.RestApiTutorial.com Page 4 of 40

RESTful Service Best Practices 8in% of %istri3ute% # perme%ia s stem to #a.e %esira3le emergent propertiesC suc# as performanceC scala3ilit C simplicit C mo%ifia3ilit C .isi3ilit C porta3ilit an% relia3ilit . ;0T'J T#e onl optional constraint of R'$T arc#itecture is code on demand. &f a ser.ice .iolates an ot#er constraintC it cannot strictl 3e referre% to as R'$Tful.

REST 'uic( Ti s
"#et#er itBs tec#nicall R'$Tful or not /accor%ing to t#e si@ constraints mentione% a3o.e1C #ere are a few recommen%e% R'$T+li8e concepts t#at will result in 3etterC more usa3le ser.icesJ

Use HTTP Verbs to

ean Somethin!

An AP& consumer is capa3le of sen%ing ?'TC P0$TC P)TC an% D'6'T' .er3sC an% t#e greatl en#ance t#e clarit of w#at a gi.en reDuest %oes. AlsoC ?'T reDuests must not c#ange an un%erl ing resource %ata. -easurements an% trac8ing ma still occurC w#ic# up%ates %ataC 3ut not resource %ata i%entifie% 3 t#e )R&.

Sensible "eso#rce $ames


Ha.ing sensi3le resource names or pat#s /e.g.C /posts/23 instea% of /api(t peMpostsNi%M231 impro.es t#e clarit of w#at a gi.en reDuest %oes. )sing )R6 Duer +string parameters is fantastic for filteringC 3ut not for resource names. Appropriate resource names pro.i%e conte@t for a ser.ice reDuestC increasing un%erstan%a3ilit of t#e ser.ice AP&. Resources are .iewe% #ierarc#icall .ia t#eir )R& namesC offering consumers a frien%l C easil +un%erstoo% #ierarc# of resources to le.erage in t#eir applications. Resource names s#oul% 3e nounsHa.oi% .er3s as resource names. &t ma8es t#ings more clear. )se t#e HTTP met#o%s to specif t#e .er3 portion of t#e reDuest.

% L and &S'$
>a.or =$0; support as t#e %efaultC 3ut unless t#e costs of offering 3ot# =$0; an% <-6 are staggeringC offer t#em 3ot#. &%eall C let consumers switc# 3etween t#em 3 Eust c#anging an e@tension from .@ml to .Eson. &n a%%itionC for supporting A=A<+st le user interfacesC a wrappe% response is .er #elpful. Pro.i%e a wrappe% responseC eit#er 3 %efault or for separate e@tensionsC suc# as .wEson an% .w@ml to in%icate t#e client is reDuesting a wrappe% =$0; or <-6 response /see "rappe% Responses 3elow1. =$0; in regar%s to a Istan%ar%I #as .er few reDuirements. An% t#ose reDuirements are onl s ntactical in natureC not a3out content format or la out. &n ot#er wor%sC t#e =$0; response to a R'$T ser.ice call is .er muc# part of t#e contractHnot %escri3e% in a stan%ar%. -ore a3out t#e =$0; %ata format can 3e foun% at #ttpJ//www.Eson.org/. Regar%ing <-6 use in R'$T ser.icesC <-6 stan%ar%s an% con.entions are reall not in pla ot#er t#an to utiliAe s ntacticall correct tags an% te@t. &n particularC namespaces are notC nor s#oul% t#e 3e use in a R'$Tful ser.ice conte@t. <-6 t#at is returne% is more =$0; li8eHsimple an% eas to rea%C wit#out t#e sc#ema an% namespace %etails presentHEust %ata an% lin8s. &f it en%s up 3eing more 03/26/14 www.RestApiTutorial.com Page 9 of 40

RESTful Service Best Practices comple@ t#an t#isC see t#e first paragrap# of t#is tipHt#e cost of <-6 will 3e staggering. &n our e@perience few consumers uses t#e <-6 responses an wa . T#is is t#e last Bno%B 3efore it gets p#ase% out entirel .

Create (ine)*rained "eso#rces


"#en starting outC itBs muc# easier to create AP&s t#at mimic t#e un%erl ing application %omain or %ata3ase arc#itecture of our s stem. '.entuall C ouBll want aggregate ser.icesHser.ices t#at utiliAe multiple un%erl ing resources to re%uce c#attiness. ,ut itBs muc# easier to create larger resources later from in%i.i%ual resources t#an it is to create fine+graine% or in%i.i%ual resources from larger aggregates. -a8e it eas on ourself an% start wit# smallC easil %efine% resourcesC pro.i%ing 2R)D functionalit on t#ose. Oou can create t#ose use+case+oriente%C c#attiness+re%ucing resources later.

Consider Connectedness
0ne of t#e principles of R'$T is connecte%nessH.ia # perme%ia lin8s. "#ile ser.ices are still useful wit#out t#emC AP&s 3ecome more self+%escripti.e w#en lin8s are returne% in t#e response. At t#e .er leastC a BselfB reference informs clients #ow t#e %ata was or can 3e retrie.e%. A%%itionall C utiliAe t#e Location #ea%er to contain a lin8 on resource creation .ia P0$T. >or collections returne% in a response t#at support paginationC BfirstBC BlastBC Bne@tB an% Bpre.B lin8s at a minimum are .er #elpful.

Definitions
Idempotence
2ontrar to #ow it soun%sC ma8e no mista8eC t#is #as no relation to certain areas of %isfunction. >rom "i8ipe%iaJ In computer science, the term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times. This may have a different meaning depending on the context in which it is applied. In the case of methods or subroutine calls with side effects, for instance, it means that the modified state remains the same after the first call. >rom a R'$Tful ser.ice stan%pointC for an operation /or ser.ice call1 to 3e i%empotentC clients can ma8e t#at same call repeate%l w#ile pro%ucing t#e same resultHoperating muc# li8e a FsetterG met#o% in a programming language. &n ot#er wor%sC ma8ing multiple i%entical reDuests #as t#e same effect as ma8ing a single reDuest. ;ote t#at w#ile i%empotent operations pro%uce t#e same result on t#e ser.er /si%e effects1C t#e response itself ma not 3e t#e same /e.g. a resourceBs state ma c#ange 3etween reDuests1. T#e P)T an% D'6'T' met#o%s are %efine% to 3e i%empotent. Howe.erC rea% t#e ca.eat on D'6'T' in t#e HTTP erbs, !"L"T" section 3elow. ?'TC H'ADC 0PT&0;$ an% TRA2' met#o%s are %efine% as i%empotent alsoC since t#e are %efine% as safe. Rea% t#e section on safet 3elow. 03/26/14 www.RestApiTutorial.com Page 10 of 40

RESTful Service Best Practices

Safety
>rom "i8ipe%iaJ #ome methods $for example, H"%!, &"T, 'PTI'(# and TR%)"* are defined as safe, which means they are intended only for information retrieval and should not change the state of the server. In other words, they should not have side effects, beyond relatively harmless effects such as logging, caching, the serving of banner advertisements or incrementing a web counter. +a,ing arbitrary &"T re-uests without regard to the context of the application.s state should therefore be considered safe. &n s#ortC safet means t#at calling t#e met#o% %oes not cause si%e effects. 2onseDuentl C clients can ma8e safe reDuests repeate%l wit#out worr of si%e effects on t#e ser.er. T#is means t#at ser.ices must a%#ere to t#e safet %efinitions of ?'TC H'ADC 0PT&0;$ an% TRA2' operations. 0t#erwiseC 3esi%es 3eing confusing to ser.ice consumersC it can cause pro3lems for "e3 cac#ingC searc# engines an% ot#er automate% agentsHma8ing uninten%e% c#anges on t#e ser.er. , %efinitionC safe operations are i%empotentC since t#e pro%uce t#e same result on t#e ser.er. $afe met#o%s are implemente% as rea%+onl operations. Howe.erC safet %oes not mean t#at t#e ser.er must return t#e same response e.er time.

HTT) *erbs
T#e HTTP .er3s comprise a maEor portion of our Funiform interfaceG constraint an% pro.i%e us t#e action counterpart to t#e noun+3ase% resource. T#e primar or most+commonl +use% HTTP .er3s /or met#o%sC as t#e are properl calle%1 are P0$TC ?'TC P)TC an% D'6'T'. T#ese correspon% to createC rea%C up%ateC an% %elete /or 2R)D1 operationsC respecti.el . T#ere are a num3er of ot#er .er3sC tooC 3ut are utiliAe% less freDuentl . 0f t#ose less+freDuent met#o%sC 0PT&0;$ an% H'AD are use% more often t#an ot#ers.

*+T
T#e HTTP ?'T met#o% is use% to retrie.e /or rea%1 a representation of a resource. &n t#e F#app G /or non+error1 pat#C ?'T returns a representation in <-6 or =$0; an% an HTTP response co%e of 200 /0P1. &n an error caseC it most often returns a 404 /;0T >0);D1 or 400 /,AD R'7)'$T1. '@amplesJ &"T http/00www.example.com0customers012345 &"T http/00www.example.com0customers0123450orders &"T http/00www.example.com0buc,ets0sample Accor%ing to t#e %esign of t#e HTTP specificationC ?'T /along wit# H'AD1 reDuests are use% onl to rea% %ata an% not c#ange it. T#ereforeC w#en use% t#is wa C t#e are consi%ere% safe. T#at isC t#e can 3e calle% wit#out ris8 of %ata mo%ification or corruptionHcalling it once #as t#e same effect as calling it 10 timesC or none at all. A%%itionall C ?'T /an% H'AD1 is i%empotentC w#ic# means t#at ma8ing multiple i%entical reDuests en%s up #a.ing t#e same result as a single reDuest.

03/26/14

www.RestApiTutorial.com

Page 11 of 40

RESTful Service Best Practices Do not e@pose unsafe operations .ia ?'THit s#oul% ne.er mo%if an resources on t#e ser.er.

PUT
P)T is most+often utiliAe% for up%ate capa3ilitiesC P)T+ing to a 8nown resource )R& wit# t#e reDuest reDuest 3o% containing t#e newl +up%ate% representation of t#e original resource. Howe.erC P)T can also 3e use% to create a resource in t#e case w#ere t#e resource &D is c#osen 3 t#e client instea% of 3 t#e ser.er. &n ot#er wor%sC if t#e P)T is to a )R& t#at contains t#e .alue of a non+ e@istent resource &D. AgainC t#e reDuest 3o% contains a resource representation. -an feel t#is is con.olute% an% confusing. 2onseDuentl C t#is met#o% of creation s#oul% 3e use% sparingl C if at all. Alternati.el C use P0$T to create new resources an% pro.i%e t#e client+%efine% &D in t#e 3o% representationHpresuma3l to a )R& t#at %oesnBt inclu%e t#e &D of t#e resource /see P'#T 3elow1. '@amplesJ P6T http/00www.example.com0customers012345 P6T http/00www.example.com0customers0123450orders0789:5 P6T http/00www.example.com0buc,ets0secret;stuff 0n successful up%ateC return 200 /or 204 if not returning an content in t#e 3o% 1 from a P)T. &f using P)T for createC return HTTP status 201 on successful creation. A 3o% in t#e response is optionalH pro.i%ing one consumes more 3an%wi%t#. &t is not necessar to return a lin8 .ia a 6ocation #ea%er in t#e creation case since t#e client alrea% set t#e resource &D. $ee t#e Return alues section 3elow. P)T is not a safe operationC in t#at it mo%ifies /or creates1 state on t#e ser.erC 3ut it is idempotent. &n ot#er wor%sC if ou create or up%ate a resource using P)T an% t#en ma8e t#at same call againC t#e resource is still t#ere an% still #as t#e same state as it %i% wit# t#e first call. &fC for instanceC calling P)T on a resource increments a counter wit#in t#e resourceC t#e call is no longer idempotent. $ometimes t#at #appens an% it ma 3e enoug# to %ocument t#at t#e call is not idempotent. Howe.erC itBs recommen%e% to 8eep P)T reDuests idempotent. &t is strongl recommen%e% to use P0$T for non+i%empotent reDuests.

P'ST
T#e P0$T .er3 is most+often utiliAe% for creation of new resources. &n particularC itBs use% to create subordinate resources. T#at isC su3or%inate to some ot#er /e.g. parent1 resource. &n ot#er wor%sC w#en creating a new resourceC P0$T to t#e parent an% t#e ser.ice ta8es care of associating t#e new resource wit# t#e parentC assigning an &D /new resource )R&1C etc. '@amplesJ P'#T http/00www.example.com0customers P'#T http/00www.example.com0customers0123450orders 0n successful creationC return HTTP status 201C returning a Location #ea%er wit# a lin8 to t#e newl + create% resource wit# t#e 201 HTTP status. P0$T is neit#er safe or idempotent. &t is t#erefore recommen%e% for non+i%empotent resource reDuests. -a8ing two i%entical P0$T reDuests will most+li8el result in two resources containing t#e same 03/26/14 www.RestApiTutorial.com Page 12 of 40

RESTful Service Best Practices information.

PUT vs P'ST for Creation


&n s#ortC fa.or using P0$T for resource creation. 0t#erwiseC use P)T w#en t#e client is in c#arge of %eci%ing w#ic# )R& /.ia itBs resource name or &D1 t#e new resource will #a.eJ if t#e client 8nows w#at t#e resulting )R& /or resource &D1 will 3eC use P)T at t#at )R&. 0t#erwiseC use P0$T w#en t#e ser.er or ser.ice is in c#arge of %eci%ing t#e )R& for t#e newl +create% resource. &n ot#er wor%sC w#en t#e client %oesnBt /or s#oul%nBt1 8now w#at t#e resulting )R& will 3e 3efore creationC use P0$T to create t#e new resource.

,+L+T+
D'6'T' is prett eas to un%erstan%. &t is use% to %elete a resource i%entifie% 3 a )R&. '@amplesJ !"L"T" http/00www.example.com0customers012345 !"L"T" http/00www.example.com0customers0123450orders !"L"T" http/00www.example.com0buc,ets0sample 0n successful %eletionC return HTTP status 200 /0P1 along wit# a response 3o% C per#aps t#e representation of t#e %elete% item /often %eman%s too muc# 3an%wi%t#1C or a wrappe% response /see Return alues 3elow1. 'it#er t#at or return HTTP status 204 /;0 20;T';T1 wit# no response 3o% . &n ot#er wor%sC a 204 status wit# no 3o% C or t#e =$';D+st le response an% HTTP status 200 are t#e recommen%e% responses. HTTP+spec+wiseC D'6'T' operations are idempotent. &f ou D'6'T' a resourceC itBs remo.e%. Repeate%l calling D'6'T' on t#at resource en%s up t#e sameJ t#e resource is gone. &f calling D'6'T' sa C %ecrements a counter /wit#in t#e resource1C t#e D'6'T' call is no longer idempotent. As mentione% pre.iousl C usage statistics an% measurements ma 3e up%ate% w#ile still consi%ering t#e ser.ice i%empotent as long as no resource %ata is c#ange%. )sing P0$T for non+i%empotent resource reDuests is recommen%e%. T#ere is a ca.eat a3out D'6'T' i%empotenceC #owe.er. 2alling D'6'T' on a resource a secon% time will often return a 404 /;0T >0);D1 since it was alrea% remo.e% an% t#erefore is no longer fin%a3le. T#is ma8es D'6'T' operations no longer i%empotentC 3ut is an appropriate compromise if resources are remo.e% from t#e %ata3ase instea% of 3eing simpl mar8e% as %elete%. ,elow is a ta3le summariAing recommen%e% return .alues of t#e primar HTTP met#o%s in com3ination wit# t#e resource )R&sJ HTTP Verb ?'T P)T /customers 200 /0P1C list of customers. )se paginationC sorting an% filtering to na.igate 3ig lists. 404 /;ot >oun%1C unless ou want to up%ate/replace e.er resource in t#e entire collection. www.RestApiTutorial.com /customers/{id} 200 /0P1C single customer. 404 /;ot >oun%1C if &D not foun% or in.ali%. 200 /0P1 or 204 /;o 2ontent1. 404 /;ot >oun%1C if &D not foun% or in.ali%. Page 13 of 40

03/26/14

RESTful Service Best Practices P0$T D'6'T' 201 /2reate%1C B6ocationB #ea%er wit# lin8 to /customers/Qi%R containing new &D. 404 /;ot >oun%1C unless ou want to %elete t#e w#ole collectionHnot often %esira3le. 404 /;ot >oun%1. 200 /0P1. 404 /;ot >oun%1C if &D not foun% or in.ali%.

Resource +amin!
&n a%%ition to utiliAing t#e HTTP .er3s appropriatel C resource naming is argua3l t#e most %e3ate% an% most important concept to grasp w#en creating an un%erstan%a3leC easil le.erage% "e3 ser.ice AP&. "#en resources are name% wellC an AP& is intuiti.e an% eas to use. Done poorl C t#at same AP& can feel 8lutA an% 3e %ifficult to use an% un%erstan%. ,elow are a few tips to get ou going w#en creating t#e resource )R&s for our new AP&. 'ssentiall C a R'$T>ul AP& en%s up 3eing simpl a collection of )R&sC HTTP calls to t#ose )R&s an% some =$0; an%/or <-6 representations of resourcesC man of w#ic# will contain relational lin8s. T#e R'$Tful principal of addressability is co.ere% 3 t#e )R&s. 'ac# resource #as its own a%%ress or )R&He.er interesting piece of information t#e ser.er can pro.i%e is e@pose% as a resource. T#e constraint of uniform interface is partiall a%%resse% 3 t#e com3ination of )R&s an% HTTP .er3sC an% using t#em in line wit# t#e stan%ar%s an% con.entions. &n %eci%ing w#at resources are wit#in our s stemC name t#em as nouns as oppose% to .er3s or actions. &n ot#er wor%sC a R'$Tful )R& s#oul% refer to a resource t#at is a thing instea% of referring to an action. ;ouns #a.e properties as .er3s %o notC Eust anot#er %istinguis#ing factor. $ome e@ample resources areJ )sers of t#e s stem. 2ourses in w#ic# a stu%ent is enrolle%. A userBs timeline of posts. T#e users t#at follow anot#er user. An article a3out #orse3ac8 ri%ing.

'ac# resource in a ser.ice suite will #a.e at least one )R& i%entif ing it. An% itBs 3est w#en t#at )R& ma8es sense an% a%eDuatel %escri3es t#e resource. )R&s s#oul% follow a pre%icta3leC #ierarc#ical structure to en#ance un%erstan%a3ilit an%C t#ereforeC usa3ilit J pre%icta3le in t#e sense t#at t#e Bre consistentC #ierarc#ical in t#e sense t#at %ata #as structureHrelations#ips. T#is is not a R'$T rule or constraintC 3ut it en#ances t#e AP&. R'$Tful AP&s are written for consumers. T#e name an% structure of )R&s s#oul% con.e meaning to t#ose consumers. &tBs often %ifficult to 8now w#at t#e %ata 3oun%aries s#oul% 3eC 3ut wit# un%erstan%ing of our %ataC ou most+li8el are eDuippe% to ta8e a sta3 an% w#at ma8es sense to return as a representation to our clients. Design for our clientsC not for our %ata. 6etBs sa weBre %escri3ing an or%er s stem wit# customersC or%ersC line itemsC pro%uctsC etc. 2onsi%er t#e )R&s in.ol.e% in %escri3ing t#e resources in t#is ser.ice suiteJ

03/26/14

www.RestApiTutorial.com

Page 14 of 40

RESTful Service Best Practices

"eso#rce U"I +-amples


To insert /create1 a new customer in t#e s stemC we mig#t useJ P'#T http/00www.example.com0customers To rea% a customer wit# 2ustomer &DS 3324!J &"T http/00www.example.com0customers033245 T#e same )R& woul% 3e use% for P)T an% D'6'T'C to up%ate an% %eleteC respecti.el . Here are propose% )R&s for pro%uctsJ P'#T http/00www.example.com0products for creating a new pro%uct. &"T<P6T<!"L"T" http/00www.example.com0products0::432 for rea%ingC up%atingC %eleting pro%uct 66432C respecti.el . ;owC #ere is w#ere it gets fun... "#at a3out creating a new or%er for a customer( 0ne option mig#t 3eJ P'#T http/00www.example.com0orders An% t#at coul% wor8 to create an or%erC 3ut itBs argua3l outsi%e t#e conte@t of a customer. ,ecause we want to create an or%er for a customer /note t#e relations#ip1C t#is )R& per#aps is not as intuiti.e as it coul% 3e. &t coul% 3e argue% t#at t#e following )R& woul% offer 3etter clarit J P'#T http/00www.example.com0customers0332450orders ;ow we 8now weBre creating an or%er for customer &DS 3324!. ;ow w#at woul% t#e following return( &"T http/00www.example.com0customers0332450orders Pro3a3l a list of or%ers t#at customer S3324! #as create% or owns. ;oteJ we ma c#oose to not support D'6'T' or P)T for t#at url since itBs operating on a collection. ;owC to continue t#e #ierarc#ical conceptC w#at a3out t#e following )R&( P'#T http/00www.example.com0customers0332450orders089:70lineitems T#at mig#t a%% a line item to or%er S4*69 /w#ic# is for customer S3324!1. Rig#tT ?'T for t#at )R& mig#t return all t#e line items for t#at or%er. Howe.erC if line items %onBt ma8e sense onl in customer conte@t or also ma8e sense outsi%e t#e conte@t of a customerC we woul% offer a P'#T www.example.com0orders089:70lineitems )R&. Along t#ose linesC 3ecause t#ere ma 3e multiple )R&s for a gi.en resourceC we mig#t also offer a &"T http/00www.example.com0orders089:7 )R& t#at supports retrie.ing an or%er 3 num3er wit#out #a.ing to 8now t#e customer num3er. To go one la er %eeper in t#e #ierarc# J &"T http/00www.example.com0customers0332450orders089:70lineitems01 -ig#t return onl t#e first line item in t#at same or%er. , now ou can see #ow t#e #ierarc# concept wor8s. T#ere arenBt an #ar% an% fast rulesC onl ma8e sure t#e impose% structure ma8es sense to consumers of our ser.ices. As wit# e.er t#ing in t#e craft of $oftware De.elopmentC naming is critical to success. 6oo8 at some wi%el use% AP&s to get t#e #ang of t#is an% le.erage t#e intuition of our teammates to 03/26/14 www.RestApiTutorial.com Page 1! of 40

RESTful Service Best Practices refine our AP& resource )R&s. $ome e@ample AP&s areJ TwitterJ #ttpsJ//%e..twitter.com/%ocs/api >ace3oo8J #ttpJ//%e.elopers.face3oo8.com/%ocs/reference/api/ 6in8e%&nJ #ttpsJ//%e.eloper.lin8e%in.com/apis

"eso#rce $amin! .nti)Patterns


"#ile weB.e %iscusse% some e@amples of appropriate resource namesC sometimes itBs informati.e to see some anti+patterns. ,elow are some e@amples of poor R'$Tful resource )R&s seen in t#e Fwil%.G T#ese are e@amples of w#at not to %oT >irst upC often ser.ices use a single )R& to specif t#e ser.ice interfaceC using Duer +string parameters to specif t#e reDueste% operation an%/or HTTP .er3. >or e@ample to up%ate customer wit# &D 1234!C t#e reDuest for a =$0; 3o% mig#t 3eJ &"T http/00api.example.com0services=op>update;customer?id>12345?format>@son , nowC ouBre a3o.e %oing t#is. '.en t#oug# t#e Bser.icesB )R6 no%e is a nounC t#is )R6 is not self+ %escripti.e as t#e )R& #ierarc# is t#e same for all reDuests. PlusC it uses ?'T as t#e HTTP .er3 e.en t#oug# weBre performing an up%ate. T#is is counter+intuiti.e an% is painful /e.en %angerous1 to use as a client. HereBs anot#er e@ample following t#e same operation of up%ating a customerJ &"T http/00api.example.com0update;customer012345 An% its e.il twinJ &"T http/00api.example.com0customers0123450update OouBll see t#is one a lot as ou .isit ot#er %e.eloperBs ser.ice suites. ;ote t#at t#e %e.eloper is attempting to create R'$Tful resource names an% #as ma%e some progress. ,ut ouBre 3etter t#an t#is Ha3le to i%entif t#e .er3 p#rase in t#e )R6. ;otice t#at we %onBt nee% to use t#e Bup%ateB .er3 p#rase in t#e )R6 3ecause we can rel on t#e HTTP .er3 to inform t#at operation. =ust to clarif C t#e following resource )R6 is re%un%antJ P6T http/00api.example.com0customers0123450update "it# 3ot# P)T an% Bup%ateB in t#e reDuestC weBre offering to confuse our ser.ice consumersT &s Bup%ateB t#e resource( $oC weB.e spent some time 3eating t#e #orse at t#is point. &Bm certain ou un%erstan%...

Pl#rali/ation
6etBs tal8 a3out t#e %e3ate 3etween t#e pluraliAers an% t#e FsingulariAersG... Ha.enBt #ear% of t#at %e3ate( &t does e@ist. 'ssentiall C it 3oils %own to t#is Duestion... $#oul% )R& no%es in our #ierarc# 3e name% using singular or plural nouns( >or e@ampleC s#oul% our )R& for retrie.ing a representation of a customer resource loo8 li8e t#isJ &"T http/00www.example.com0customer033245

03/26/14

www.RestApiTutorial.com

Page 16 of 40

RESTful Service Best Practices orJ &"T http/00www.example.com0customers033245 T#ere are goo% arguments on 3ot# si%esC 3ut t#e commonl +accepte% practice is to always use plurals in node names to 8eep our AP& )R&s consistent across all HTTP met#o%s. T#e reasoning is 3ase% on t#e concept t#at customers are a collection wit#in t#e ser.ice suite an% t#e &D /e.g. 3324!1 refers to one of t#ose customers in t#e collection. )sing t#is ruleC an e@ample multi+no%e )R& using pluraliAation woul% loo8 li8e /emp#asis a%%e%1J &"T http/00www.example.com0customers0332450orders089:70lineitems01 wit# BcustomersBC Bor%ersBC an% BlineitemsB )R& no%es all 3eing t#eir plural forms. T#is implies t#at ou onl reall nee% two 3ase )R6s for eac# root resource. 0ne for creation of t#e resource wit#in a collection an% t#e secon% for rea%ingC up%ating an% %eleting t#e resource 3 its i%entifier. >or e@ample t#e creation caseC using customers as t#e e@ampleC is #an%le% 3 t#e following )R6J P'#T http/00www.example.com0customers An% t#e rea%C up%ate an% %elete cases are #an%le% 3 t#e followingJ &"T<P6T<!"L"T" http/00www.example.com0customers0AidB As mentione% earlierC t#ere ma 3e multiple )R&s for a gi.en resourceC 3ut as a minimum full 2R)D capa3ilities are aptl #an%le% wit# two simple )R&s. Oou as8 if t#ere is a case w#ere pluraliAation %oesnBt ma8e sense. "ellC esC in fact t#ere is. "#en t#ere isnBt a collection concept in pla . &n ot#er wor%sC itBs accepta3le to use a singulariAe% resource name w#en t#ere can onl 3e one of t#e resourceHitBs a singleton resource. >or e@ampleC if t#ere was a singleC o.erarc#ing configuration resourceC ou mig#t use a singulariAe% noun to represent t#atJ &"T<P6T<!"L"T" http/00www.example.com0configuration ;ote t#e lac8 of a configuration &D an% usage of P0$T .er3. An% sa t#at t#ere was onl one configuration per customerC t#en t#e )R6 mig#t 3eJ &"T<P6T<!"L"T" http/00www.example.com0customers0123450configuration AgainC no &D for t#e configuration an% no P0$T .er3 usage. Alt#oug#C &Bm sure t#at in 3ot# of t#ese cases P0$T usage mig#t 3e argue% to 3e .ali%. "ell... 0P.

Returnin! Re resentations
As mentione% earlierC it is %esira3le for a ser.ice to support multiple representations of resourcesC inclu%ing =$0; an% <-6C as well as wrappe% =$0; an% <-6. As t#e %efault representationC t#e recommen%ation is =$0;C 3ut ser.ices s#oul% allow clients to specif alternati.e representations. >or a client to reDuest a representation formatC t#ere is a Duestion aroun% w#et#er to use t#e Accept #ea%er a file+e@tension+st le format specifierC Duer +string parameterC etc. 0ptimall C ser.ices woul% support all of t#ose met#o%s. Howe.erC in%ustr is currentl con.erging on using a format specifierC w#ic# loo8s more li8e a file e@tension. T#ereforeC t#e recommen%ation is t#atC at a minimumC ser.ices 03/26/14 www.RestApiTutorial.com Page 1* of 40

RESTful Service Best Practices support t#e use of file e@tensions suc# as B.EsonBC B.@mlB an% wrappe% optionsC B.wEsonB an% B.w@mlB. )sing t#is tec#niDueC t#e representation format is specifie% in t#e )R&C en#ancing .isi3ilit . >or e@ampleC &"T http/00www.example.com0customers.xml woul% return t#e list of customer representations in <-6 format. 6i8ewiseC &"T http/00www.example.com0customers.@son woul% return a =$0; representation. T#is ma8es t#e ser.ices simple to use from e.en t#e most 3asic client /suc# as BcurlB1 an% is recommen%e%. AlsoC ser.ices s#oul% return t#e %efault representation format /presuma3l =$0;1 w#en a format specifier is not inclu%e% on t#e url. >or e@ampleJ &"T http/00www.example.com0customers012345 &"T http/00www.example.com0customers012345.@son ,ot# of t#e a3o.e return t#e 1234! customer resource in a =$0; representationC w#ic# is t#e %efault format for t#is ser.ice. &"T http/00www.example.com0customers012345.xml Returns t#e 1234! customer resource in an <-6 representationC if supporte%. &f an <-6 representation of t#is resource is not supporte% 3 t#is ser.iceC an HTTP 404 error s#oul% 3e returne%. )se of t#e HTTP Accept #ea%er is consi%ere% 3 man to 3e a more elegant approac#C an% is in 8eeping wit# t#e meaning an% intent of t#e HTTP specification wit# regar%s to #ow clients notif HTTP ser.ers of w#ic# content t pes t#e support. Howe.erC to support 3ot# wrappe% an% unwrappe% responses from our ser.icesC in or%er to utiliAe t#e Accept #ea%erC ou must implement our own custom t pesHsince t#ere are no stan%ar% t pes for t#ese formats. T#is increases t#e comple@it of 3ot# clients an% ser.ices greatl . $ee $ection 14.1 of R>2 2616 /#ttpJ//www.w3.org/Protocols/rfc2616/rfc2616+sec14.#tmlSsec14.11 for %etails on t#e Accept #ea%er. $upporting file+e@tension+st le format specifiers is simpleC straig#t+forwar%C gets t#e Eo3 %one in t#e fewest num3er of c#aractersC an% easil supports scriptingHwit#out #a.ing to le.erage HTTP #ea%ers. &n generalC w#en we tal8 a3out R'$T ser.icesC <-6 is largel irrele.ant. ,arel an one uses <-6 wit# R'$T alt#oug# supporting <-6 is recommen%e%. <-6 stan%ar%s an% con.entions are reall not in pla . &n particularC namespaces are notC nor s#oul% t#e 3e use in a R'$Tful ser.ice conte@t. &t Eust mu%%ies t#e waters an% ma8es t#ings more complicate%. $o t#e <-6 t#at is returne% is more =$0; li8eHsimple an% eas to rea%C wit#out t#e sc#ema an% namespace constraintsHnon+stan%ar% in ot#er wor%sC 3ut parse+a3le.

"eso#rce ,iscoverability Thro#!h Lin0s (H.T+'.S cont1d)


0ne of t#e gui%ing principals of R'$T /.ia t#e )niform &nterface constraint1 is t#at application state is communicate% .ia # perte@t. T#is is often referre% to as H perte@t As T#e 'ngine of Application $tate /HAT'0A$1 as mentione% a3o.e in t#e Chat is Rest= $ection. Accor%ing to Ro >iel%ingBs 3log /at #ttpJ//ro .g3i..com/untangle%/2004/rest+apis+must+3e+# perte@t+ %ri.en1C t#e most important part of a R'$T interface is its usage of # perte@t. >urt#erC #e states t#at an AP& s#oul% 3e usa3le an% un%erstan%a3le gi.en an initial )R& wit#out prior 8nowle%ge or out+of+3an% information. T#at isC an AP& s#oul% 3e na.iga3le .ia its lin8s to .arious components of t#e %ata. Returning onl %ata representations is %iscourage%. 03/26/14 www.RestApiTutorial.com Page 14 of 40

RESTful Service Best Practices T#is practice is not often followe% 3 current in%ustr lea%ers in ser.icesC reflecting t#at HAT'0A$ usage is #ig#er on t#e maturit mo%el. 6oo8ing aroun% at man ser.icesC con.ention is to return more %ata an% less /or no1 lin8s. T#is is contrar to >iel%ingBs R'$T constraints. >iel%ing sa sC F'.er a%%ressa3le unit of information carries an a%%ress... 7uer results are represente% 3 a list of lin8s wit# summar informationC not 3 arra s of o3Eect representations.G 0n t#e ot#er #an%C simpl returning collections of lin8s can 3e a maEor cause of networ8 c#attiness. &n t#e real worl%C %epen%ing on reDuirements or use casesC c#attiness of t#e AP& interface is manage% 3 3alancing #ow muc# Fsummar G %ata is inclu%e% along wit# t#e relational # perte@t lin8s in ser.ice responses. AlsoC full use of HAT'0A$ can increase implementation comple@it an% impose a significant 3ur%en on ser.ice clientsC %ecreasing %e.eloper pro%ucti.it on 3ot# client an% ser.er en%s of t#e eDuation. 2onseDuentl C it is imperati.e to 3alance # perlin8ing ser.ice implementations wit# a.aila3le %e.elopment resources. A minimal set of # perlin8ing practices pro.i%es maEor gains in ser.ice usa3ilit C na.iga3ilit an% un%erstan%a3ilit w#ile minimiAing %e.elopment impact an% re%ucing t#e coupling 3etween client an% ser.er. T#ese minimal recommen%ations are resources create% .ia P0$T an% for collections returne% from ?'T reDuestsC wit# a%%itional recommen%ations for pagination casesC w#ic# are %escri3e% 3elow.

Minimal ,in(in! Recommendations


&n create use casesC t#e )R& /lin81 for t#e newl +create% resource s#oul% 3e returne% in t#e Location response #ea%er an% t#e response 3o% 3e empt Hor contain onl t#e &D of t#e newl +create% resource. >or collections of representations 3eing returne% from a ser.iceC eac# representation s#oul% minimall carr a BselfB lin8 propert in its own lin,s collection. 0t#er lin8s ma 3e present in t#e returne% as a separate lin8s collection to facilitate paginationC wit# BfirstBC Bpre.iousBC Bne@tBC BlastB lin8s w#ere applica3le. $ee t#e e@amples in t#e Lin, Dormat section 3elow for more information.

,in( -ormat
Regar%ing o.erall lin8 format stan%ar%s it is recommen%e% to a%#ere to some sem3lance of t#e AtomC AtomPu3C or <lin8 st le. =$0;+6D is getting some traction tooC 3ut is not wi%el a%opte% et /if it e.er will 3e1. -ost wi%esprea% in t#e in%ustr is usage of t#e Atom lin8 st le wit# a FrelG element an% an F#refG element t#at contains t#e full )R& for t#e resource wit#out an aut#entication or Duer +string parameters. T#e FrelG elementC can contain t#e stan%ar% .alues IalternateIC Irelate%IC IselfIC IenclosureIC an% I.iaIC plus FfirstGC FlastGC Fpre.iousGC Fne@tG for pagination lin8s. )se t#em w#ere t#e ma8e sense an% a%% our own w#en nee%e%. $ome of t#e <-6 Atom format concepts are somew#at irrele.ant for lin8s 3eing represente% in =$0;. >or instanceC t#e -'TH0D propert is not nee%e% for a R'$Tful resource since t#e )R&s are t#e same for a gi.en resourceC wit# all of t#e HTTP met#o%s 3eing supporte% /for 2R)D 3e#a.ior1++so listing t#em in%i.i%uall is o.er8ill. 03/26/14 www.RestApiTutorial.com Page 19 of 40

RESTful Service Best Practices 6etBs ma8e all t#is tal8 a little more concrete wit# some e@amples. HereBs w#at t#e response woul% loo8 li8e after creating a new resource wit# a call toJ P'#T http/00api.example.com0users An% #ereBs an e@ample set of response #ea%ers wit# t#e Location #ea%er set containing t#e new resource )R&J HTTP01.1 2E1 )R"%T"! #tatus/ 2E1 )onnection/ close )ontentFType/ application0@sonG charset>utfF8 Location: http://api.example.com/users/12346 T#e 3o% is eit#er empt C or contains a wrappe% response /see Crapped Responses 3elow1. Here is an e@ample =$0; response to a ?'T reDuest t#at returns a collection of representations wit#out pagination in.ol.e%J AHdataI/JAHuser;idI/I42I, HnameI/IKobI, links/JAHrelI/IselfI, HhrefI/Ihttp/00api.example.com0users042IBLB, AHuser;idI/I22I, HnameI/IDran,I, links/ JAHrelI/IselfI, HhrefI/Ihttp/00api.example.com0users022IBLB, AHuser;idI/I125I, HnameI/ H#allyI, links/JAHrelI/IselfI, HhrefI/Ihttp/00api.example.com0users0125IBLBLB ;ote t#e lin8s arra containing a single reference to FselfG for eac# item in t#e collection. T#is arra coul% potentiall contain ot#er relations#ipsC suc# as c#il%renC parentC etc. T#e final e@ample is a =$0; response to a ?'T reDuest t#at returns a collection w#ere pagination is in.ol.e% /weBre using t#ree items per page1 an% weBre on t#e t#ir% page of t#e collectionJ AHdataI/JAHuser;idI/I42I, HnameI/IKobI, Hlin,sI/JAHrelI/IselfI, HhrefI/Ihttp/00api.example.com0users042IBLB, AHuser;idI/I22I, HnameI/IDran,I, Hlin,sI/ JAHrelI/IselfI, HhrefI/Ihttp/00api.example.com0users022IBLB, AHuser;idI/I125I, HnameI/ H#allyI, Hlin,sI/JAHrelI/IselfI, HhrefI/Ihttp/00api.example.com0users0125IBLBL, links/JAHrelI/HfirstI, HhrefI/Ihttp/00api.example.com0users=offset>E?limit>3IB, AHrelI/HlastI, HhrefI/Ihttp/00api.example.com0users=offset>55?limit>3IB, AHrelI/HpreviousI, HhrefI/Ihttp/00api.example.com0users=offset>3?limit>3IB, AHrelI/InextI, HhrefI/Ihttp/00api.example.com0users=offset>7?limit>3IBLB &n t#is e@ampleC t#e lin8s collection in t#e response is populate% for pagination purposes along wit# t#e lin8 to FselfG in eac# of t#e items in t#e collection. T#ere coul% 3e a%%itional lin8s #ere relate% to t#e collection 3ut not relate% to pagination. T#e simple summar isC t#ere are two places to inclu%e lin8s in a collection. >or eac# item in t#e collection /t#ose in t#e data o3EectC w#ic# is t#e collection of representations reDueste%1C inclu%e a lin8s collection t#atC minimall C woul% contain a FselfG reference. T#enC in a separate o3EectC lin,sC inclu%e lin8s t#at appl to t#e entire collection as applica3leC suc# as pagination+relate% lin8s. >or t#e create use caseHcreate .ia P0$TC inclu%e a Location #ea%er wit# a lin8 to t#e newl +create% o3Eect.

03/26/14

www.RestApiTutorial.com

Page 20 of 40

RESTful Service Best Practices

2rapped "esponses
$er.ices #a.e t#e opportunit to return 3ot# HTTP status co%es along wit# a 3o% in t#e response. &n man =a.a$cript framewor8sC HTTP status response co%es are not returne% to t#e en%+%e.eloperC often pre.enting t#e client from %etermining 3e#a.ior 3ase% on t#at status co%e. A%%itionall C wit# t#e m ria% response co%es in t#e HTTP specC often t#ere are onl a few t#at clients care a3outHfreDuentl 3oiling %own to BsuccessBC BerrorBC or BfailureB. 2onseDuentl C it is 3eneficial to wrap responses in a representation t#at contains information a3out t#e response as well as t#e response itself. 0ne suc# proposal is t#at from 0mniT& 6a3sC t#e so+calle% =$';D response. -ore information can 3e foun% at #ttpJ//la3s.omniti.com/la3s/Esen%. Anot#er option is propose% 3 Douglas 2roc8for% an% can 3e rea% a3out at #ttpJ//www.Eson.org/=$0;ReDuest.#tml. &n practice neit#er of t#ese proposals a%eDuatel co.ers all cases. ,asicall C current 3est practice is to wrap regular /non+=$0;P1 responses wit# t#e following propertiesJ code 5 contains t#e HTTP response status co%e as an integer. status 5 contains t#e te@tJ FsuccessGC FfailGC or FerrorG. "#ere FfailG is for HTTP status response .alues from !00+!99C FerrorG is for statuses 400+499C an% FsuccessG is for e.er t#ing else /e.g. 1<<C 2<< an% 3<< responses1. message 5 onl use% for FfailG an% FerrorG statuses to contain t#e error message. >or internationaliAation /i14n1 purposesC t#is coul% contain a message num3er or co%eC eit#er alone or containe% wit#in %elimiters. data 5 t#at contains t#e response 3o% . &n t#e case of FerrorG or FfailG statusesC t#is contains t#e causeC or e@ception name.

A successful response in wrappe% st le loo8s similar to t#isJ QIco%eIJ200CIstatusIJIsuccessICI%ataIJ QIlac8sT0$IJfalseCIin.ali%2re%entialsIJfalseCIaut#To8enIJI4ee6433aa2a3332c3c46026%IRR An e@ample error response in wrappe% st le loo8s li8e t#isJ AMcodeM/4E1,MstatusM/MerrorM,MmessageM/Mto,en is invalidM,MdataM/M6nauthoriNed"xceptionMB &n <-6C t#ese two wrappe% responses woul% correspon% toJ UresponseV Uco%eV200U/co%eV UstatusVsuccessU/statusV U%ata classMIAut#enticationResultIV Ulac8sT0$VfalseU/lac8sT0$V Uin.ali%2re%entialsVfalseU/in.ali%2re%entialsV Uaut#To8enV1.0Wi%mWi%mW4ee6433aa2a3332c3c46026%U/aut#To8enV U/%ataV U/responseV An%J UresponseV Uco%eV401U/co%eV 03/26/14 www.RestApiTutorial.com Page 21 of 40

RESTful Service Best Practices UstatusVerrorU/statusV UmessageVto8en is in.ali%U/messageV U%ata classMIstringIV)naut#oriAe%'@ceptionU/%ataV U/responseV

Handlin! Cross),omain Iss#es


"eB.e all #ear% a3out wor8ing aroun% t#e 3rowserBs same origin polic or common+source reDuirement. &n ot#er wor%sC t#e 3rowser can onl ma8e reDuests to t#e site itBs currentl %ispla ing. >or e@ampleC if t#e site currentl 3eing %ispla e% is www."xample1.comC t#en t#at site cannot perform a reDuest against www."xample2.com. 03.iousl C t#is impacts #ow sites access ser.ices. Presentl C t#ere are two wi%el +accepte% met#o%s to support cross+%omain reDuestsJ =$0;P an% 2ross+ 0rigin Resource $#aring /20R$1. =$0;P or I=$0; wit# pa%%ingI is a usage pattern t#at pro.i%es a met#o% to reDuest %ata from a ser.er in a %ifferent %omain. &t wor8s 3 t#e ser.ice returning ar3itrar =a.a$cript co%e instea% of =$0;. T#ese responses are e.aluate% 3 t#e =a.a$cript interpreterC not parse% 3 a =$0; parser. 20R$C on t#e ot#er #an%C is a we3 3rowser tec#nolog specificationC w#ic# %efines wa s for a we3 ser.er to allow its resources to 3e accesse% 3 a we3 page from a %ifferent %omain. &t is seen as a mo%ern alternati.e to =$0;P an% is supporte% 3 all mo%ern 3rowsers. T#ereforeC =$0;P is not recommen%e%. 2#oose 20R$ w#ene.er an% w#ere.er possi3le.

Su

ortin! C%RS

&mplementing 20R$ on a ser.er is as simple as sen%ing an a%%itional HTTP #ea%er in t#e responseC for e@ampleJ Access+2ontrol+Allow+0riginJ X An access origin of BXB s#oul% onl 3e set if t#e %ata is meant for public consumption. &n most cases t#e Access+2ontrol+Allow+0rigin #ea%er s#oul% specif !ic! domains s#oul% 3e a3le to initiate a 20R$ reDuest. 0nl )R6s t#at nee% to 3e accesse% cross+%omain s#oul% #a.e t#e 20R$ #ea%er set. %ccessF)ontrolF%llowF'rigin/ http/00example.com/8E8E http/00foo.example.com Allow onl truste% %omains in Access+2ontrol+Allow+0rigin #ea%er. %ccessF)ontrolF%llowF)redentials/ true )se t#is #ea%er onl w#en necessar as it will sen% t#e coo8ies/sessions if t#e user is logge% into t#e application. T#ese #ea%ers can 3e configure% .ia t#e "e3 ser.erC pro@ or sent from t#e ser.ice itself. &mplementing it wit#in t#e ser.ices is not recommen%e% as itBs not fle@i3le. &nstea%C use t#e secon% formC a space %elimite% list of appropriate %omains configure% on our "e3 ser.er. -ore a3out 20R$ can 3e foun% atJ #ttpJ//ena3le+cors.org/.

Su

ortin! .S%+)

=$0;P gets aroun% t#e 3rowser limitation 3 utiliAing ?'T reDuests to perform all ser.ice calls. &n 03/26/14 www.RestApiTutorial.com Page 22 of 40

RESTful Service Best Practices essenceC t#e reDuester a%%s a Duer +string parameter /e.g. EsonpMGEsonpLcall3ac8G1 to t#e reDuestC w#ere t#e .alue of t#e FEsonpG parameter is t#e name of a Ea.ascript function t#at will 3e calle% w#en t#e response is returne%. T#ere se.ere limitations to t#e functionalit ena3le% 3 =$0;PC since ?'T reDuests %o not contain a reDuest 3o% an%C t#ereforeC information must 3e passe% .ia Duer +string parameters. AlsoC to support P)TC P0$T an% D'6'T' operationsC t#e effecti.e HTTP met#o% must also 3e passe% as a Duer +string argumentC suc# as Lmet#o%MP0$T. Tunneling t#e HTTP met#o% li8e t#is is not recommen%e% an% can open ser.ices up to securit ris8s. =$0;P wor8s on legac 3rowsers w#ic# preclu%e 20R$ supportC 3ut affects #ow ser.ices are 3uilt if t#e Bre going to support it. Alternati.el C =$0;P can 3e implemente% .ia a pro@ . 0.erallC =$0;P is 3eing %e+emp#asiAe% in fa.or of 20R$. >a.or 20R$ w#ene.er possi3le. To support =$0;P on t#e ser.er si%eC w#en t#e =$0;P Duer +string parameter is passe% inC t#e response must 3e manipulate% a 3it as followsJ 1. T#e response 3o% must 3e wrappe% as t#e parameter to t#e gi.en Ea.ascript function in t#e Esonp parameter /e.g. EsonpLcall3ac8/FU=$0; response 3o% VG11. 2. Alwa s return HTTP status 200 /0P1 an% return t#e actual status as part of t#e =$0; response. A%%itionall C itBs also often necessar to inclu%e #ea%ers as part of t#e response 3o% . T#is ena3les t#e =$0;P call3ac8 met#o% to ma8e %ecisions on response #an%ling 3ase% on t#e response 3o% since itBs not pri. to t#e information in response #ea%ers an% status. An e@ample error response following t#e a3o.e wrappe% response recommen%ations is as follows /noteJ HTTP response status is 2001J @sonp;callbac,$HA.code./.4E4., .status./.error.,.headers./JL,.message./.resource OPQ not found.,.data./.(otDound"xception.BI* A successful creation response loo8s li8e t#is /still wit# an HTTP response status of 2001J @sonp;callbac,$HA.code./.2E1., .status./.error.,.headers./ JA.Location./.http/00www.example.com0customers012345.BL,.data./.12345.BI*

'ueryin!/ -ilterin! and )a!ination


>or large %ata setsC limiting t#e amount of %ata returne% is important from a 3an%+wi%t# stan%point. ,ut itBs also important from a )& processing stan%point as a )& often can onl %ispla a small portion of a #uge %ata set. &n cases w#ere t#e %ataset grows in%efinitel C itBs #elpful to limit t#e amount of %ata returne% 3 %efault. >or instanceC in t#e case of Twitter returning a personBs tweets /.ia t#eir #ome timeline1C it returns up to 20 items unless ot#erwise specifie% in t#e reDuest an% e.en t#en will return a ma@imum of 200. Asi%e from limiting t#e amount of %ata returne%C we also nee% to consi%er #ow to FpageG or scroll t#roug# t#at large %ata set if more t#an t#at first su3set nee%s retrie.al. T#is is referre% to as pagination Hcreating FpagesG of %ataC returning 8nown sections of a larger list an% 3eing a3le to page Fforwar%G an% F3ac8war%G t#roug# t#at large %ata set. A%%itionall C we ma want to specif t#e fiel%s or properties of a resource to 3e inclu%e% in t#e responseC t#ere3 limiting t#e amount of %ata t#at comes 03/26/14 www.RestApiTutorial.com Page 23 of 40

RESTful Service Best Practices 3ac8 an% we e.entuall want to Duer for specific .alues an%/ or sort t#e returne% %ata. T#ere are com3inations of two primar wa s to limit Duer results an% perform pagination. >irstC t#e in%e@ing sc#eme is eit#er page+oriente% or item+oriente%. &n ot#er wor%sC incoming reDuests will specif w#ere to 3egin returning %ata wit# eit#er a FpageG num3erC specif ing a num3er of items per pageC or specif a first an% last item num3er %irectl /in a range1 to return. &n ot#er wor%s t#e two options areC Fgi.e me page ! assuming 20 items per pageG or Fgi.e me items 100 t#roug# 120.G $er.ice pro.i%ers are split on #ow t#is s#oul% wor8. Howe.erC some )& toolsC suc# as t#e DoEo =$0; Datastore o3EectC c#ooses to mimic t#e HTTP specifications use of 3 te ranges. &tBs .er #elpful if our ser.ices support t#at rig#t out of t#e 3o@ so no translation is necessar 3etween our )& tool8it an% 3ac8+en% ser.ices. T#e recommen%ations 3elow support 3ot# t#e DoEo mo%el for paginationC w#ic# is to specif t#e range of items 3eing reDueste% using t#e Range #ea%erC an% utiliAation of Duer +string parameters. , supporting 3ot#C ser.ices are more fle@i3leHusa3le from 3ot# a%.ance% )& tool8itsC li8e DoEoC as well as 3 simpleC straig#t+forwar% lin8s an% anc#or tags. &t s#oul%nBt a%% muc# comple@it to t#e %e.elopment effort to support 3ot# options. Howe.erC if our ser.ices %onBt support )& functionalit %irectl C consi%er eliminating support for t#e Range #ea%er option. &tBs important to note t#at Duer ingC filtering an% pagination are not recommen%e% for all ser.ices. T#is 3e#a.ior is resource specific an% s#oul% not 3e supporte% on all resources 3 %efault. Documentation for t#e ser.ices an% resources s#oul% mention w#ic# en%+points support t#ese more comple@ capa3ilities.

Limitin! "es#lts
T#e Fgi.e me items 3 t#roug# !!G wa of reDuesting %ata is more consistent wit# #ow t#e HTTP spec utiliAes t#e Range #ea%er for 3 tes so we use t#at metap#or wit# t#e Range #ea%er. Howe.erC t#e Fstarting wit# item 2 gi.e me a ma@imum of 20 itemsG is easier for #umans to rea%C formulate an% un%erstan% so we use t#at metap#or in supporting t#e Duer +string parameters. As mentione% a3o.eC t#e recommen%ation is to support use of 3ot# t#e HTTP Range #ea%er plus Duer + string parametersC offset an% limitC in our ser.ices to limit results in responses. ;ote t#atC gi.en support for 3ot# optionsC t#e Duer +string parameters s#oul% o.erri%e t#e Range #ea%er. 0ne of t#e first Duestions our going to as8 isC F"# are we supporting two metap#ors wit# t#ese similar functions as t#e num3ers in t#e reDuests will ne.er matc#( &snBt t#at confusing(G )m... T#atBs two Duestions. "ellC to answer our DuestionC it ma 3e confusing. T#e t#ing isC we want to ma8e t#ings in t#e Duer +string especiall clearC easil +un%erstoo%C #uman rea%a3le an% eas to construct an% parse. T#e Range #ea%erC #owe.erC is more mac#ine+3ase% wit# usage %ictate% to us .ia t#e HTTP specification. &n s#ortC t#e Range #ea%er items .alue must 3e parse%C w#ic# increases t#e comple@it C plus t#e client si%e #as to perform some computation in or%er to construct t#e reDuest. )sing t#e in%i.i%ual limit an% offset parameters are easil +un%erstoo% an% create%C usuall wit#out muc# %eman% on t#e #uman element.

03/26/14

www.RestApiTutorial.com

Page 24 of 40

RESTful Service Best Practices

,imitin! "ia the Ran!e Header


"#en a reDuest is ma%e for a range of items using a HTTP #ea%er instea% of Duer +string parametersC inclu%e a Range #ea%er specif ing t#e range as followsJ Range/ items>EF24 ;ote t#at items are Aero+3ase% to 3e consistent wit# t#e HTTP specification in #ow it uses t#e Range #ea%er to reDuest 3 tes. &n ot#er wor%sC t#e first item in t#e %ataset woul% 3e reDueste% 3 a 3eginning range specifier of Aero /01. T#e a3o.e reDuest woul% return t#e first 2! itemsC assuming t#ere were at least 2! items in t#e %ata set. 0n t#e ser.er si%eC inspect t#e Range #ea%er in t#e reDuest to 8now w#ic# items to return. 0nce a Range #ea%er is %etermine% to e@istC it can 3e simpl parse% using a regular e@pression /e.g. FitemsM/YY%Z1+/YY%Z1G1 to retrie.e t#e in%i.i%ual range .alues.

,imitin! "ia 'uery-Strin! )arameters


>or t#e Duer +string alternati.e to t#e Range #ea%erC use parameter names of offset an% limitC w#ere offset is t#e 3eginning item num3er /matc#es t#e first %igit in t#e items string for t#e Range #ea%er a3o.e1 an% limit is t#e ma@imum num3er of items to return. A reDuest using Duer +string parameters t#at matc#es t#e e@ample in t#e Range Hea%er section a3o.e isJ &"T http/00api.example.com0resources=offset= !limit=2" T#e offset .alue is Aero+3ase%C Eust li8e t#e items in t#e Range #ea%er. T#e .alue for limit is t#e ma@imum num3er of items to return. $er.ices can impose t#eir own %efault an% ma@imum .alues for limit for w#en itBs not specifie% in t#e Duer string. ,ut please %ocument t#ose Fin.isi3leG settings. ;ote t#at w#en t#e Duer +string parameters are use%C t#e .alues s#oul% o.erri%e t#ose pro.i%e% in t#e Range #ea%er.

Ran!e-Based Res onses


>or a range+3ase% reDuestC w#et#er .ia Range HTTP #ea%er or Duer +string parametersC t#e ser.er s#oul% respon% wit# a )ontentFRange #ea%er to in%icate #ow man items are 3eing returne% an% #ow man total items e@ist et to 3e retrie.e%J )ontentFRange/ items EF240:: ;ote t#at t#e total items a.aila3le /e.g. 66 in t#is case1 is not Aero+3ase%. HenceC reDuesting t#e last few items in t#is %ata set woul% return a )ontentFRange #ea%er as followsJ )ontentFRange/ items 4EF:50:: Accor%ing to t#e HTTP specificationC it is also .ali% to replace t#e total items a.aila3le /66 in t#is case1 wit# an asteris8 /FXG1 if t#e num3er of items is un8nown at response timeC or if t#e calculation of t#at num3er is too e@pensi.e. &n t#is case t#e response #ea%er woul% loo8 li8e t#isJ )ontentFRange/ items 4EF:50R Howe.erC note t#at DoEo or ot#er )& tools ma not support t#is notation. 03/26/14 www.RestApiTutorial.com Page 2! of 40

RESTful Service Best Practices

Pa!ination
T#e a3o.e response+limiting sc#emes wor8s for pagination 3 allowing reDuesters to specif t#e items wit#in a %ataset in w#ic# t#e Bre intereste%. )sing t#e a3o.e e@ample w#ere 66 total items are a.aila3leC retrie.ing t#e secon% FpageG of %ata using a page siAe of 2! woul% use a Range #ea%er as followsJ Range/ items>25F47 :ia Duer +string parametersC t#is woul% 3e eDui.alent toJ &"T ...=offset=2"!limit=2" "#ereuponC t#e ser.er /gi.en our e@ample1 woul% return t#e %ataC along wit# a )ontentFRange #ea%er as followsJ )ontentFRange/ 25F470:: T#is is wor8s great for most t#ings. Howe.erC occasionall t#ere are cases w#ere item num3ers %onBt translate %irectl to rows in t#e %ata set. AlsoC for an e@tremel acti.e %ata set w#ere new items are regularl a%%e% to t#e top of t#e listC apparent Fpaging issuesG wit# w#at loo8 li8e %uplicates can occur. Date+or%ere% %ata sets are a common case li8e a Twitter fee%. "#ile ou can still page t#roug# t#e %ata using item num3ersC sometimes itBs more 3eneficial an% un%erstan%a3le to use an FafterG or F3eforeG Duer +string parameterC optionall in conEunction wit# t#e Range #ea%er /or Duer +string parametersC offset an% limit1. >or e@ampleC to retrie.e up to 20 remar8s aroun% a gi.en timestampJ &"T http/00www.example.com0remar,s0home;timeline=after>StimestampT Range/ items>EF17 &"T http/00www.example.com0remar,s0home;timeline=before>StimestampT Range/ items>EF17 'Dui.alentl C using Duer +string parametersJ &"T http/00www.example.com0remar,s0home;timeline=after>StimestampT?offset>E?limit>2E &"T http/00www.example.com0remar,s0home;timeline=before>StimestampT?offset>E?limit>2E >or timestamp formatting an% #an%ling in %ifferent casesC please see t#e !ate Handling section 3elow. &f a ser.ice returns a su3set of %ata 3 %efault or a ma@imum num3er of arguments e.en w#en t#e reDuester %oes not set a Range #ea%erC #a.e t#e ser.er respon% wit# a )ontentFRange #ea%er to communicate t#e limit to t#e client. >or e@ampleC in t#e #omeLtimeline e@ample a3o.eC t#at ser.ice call ma onl e.er return 20 items at a time w#et#er t#e reDuester sets t#e Range #ea%er or not. &n t#at caseC t#e ser.er s#oul% alwa s respon% wit# content range #ea%er suc# asJ )ontentFRange/ EF1704125 or )ontentFRange/ EF170R

03/26/14

www.RestApiTutorial.com

Page 26 of 40

RESTful Service Best Practices

(ilterin! and Sortin! "es#lts


Anot#er consi%eration for affecting results is t#e act of filtering %ata an%/or or%ering it on t#e ser.erC retrie.ing a su3set of %ata an%/or in a specifie% or%er. T#ese concepts wor8 in conEunction wit# pagination an% results+limiting an% utiliAe Duer +string parametersC filter an% sort respecti.el C to %o t#eir magic. AgainC filtering an% sorting are comple@ operations an% %onBt nee% to 3e supporte% 3 %efault on all resources. Document t#ose resources t#at offer filtering an% sorting.

-ilterin!
&n t#is caseC filtering is %efine% as re%ucing t#e num3er of results returne% 3 specif ing some criteria t#at must 3e met on t#e %ata 3efore it is returne%. >iltering can get Duite comple@ if ser.ices support a complete set of comparison operators an% comple@ criteria matc#ing. Howe.erC it is Duite often accepta3le to 8eep t#ings sane 3 supporting a simple eDualit C Bstarts+wit#B or contains comparison. ,efore we get starte% %iscussing w#at goes in t#e filter Duer +string parameterC itBs important to un%erstan% w# a single parameter .s. multiple Duer +string parameters is use%. ,asicall C it comes %own to re%ucing t#e possi3ilit of parameter name clas#es. "eBre alrea% em3racing t#e use of offsetC limitC an% sort /see 3elow1 parameters. T#en t#ereBs @sonp if ou c#oose to support itC t#e format specifier an% possi3l after an% before parameters. An% t#atBs Eust t#e Duer +string parameters %iscusse% in t!is %ocument. T#e more parameters we use on t#e Duer +string t#e more possi3ilities we #a.e to #a.e name clas#es or o.erlap. )sing a single filter parameter minimiAes t#at. PlusC itBs easier from t#e ser.er+si%e to %etermine if filtering functionalit is reDueste% 3 simpl c#ec8ing for t#e presence of t#at single filter parameter. AlsoC as comple@it of our Duer ing reDuirements increasesC t#is single parameter option pro.i%es more fle@i3ilit in t#e futureHfor creating our own full +functional Duer s nta@ /see 0Data comments 3elow or at #ttpJ//www.o%ata.org1. , em3racing a set of commonC accepte% %elimitersC eDualit comparison can 3e implemente% in straig#t+forwar% fas#ion. $etting t#e .alue of t#e filter Duer +string parameter to a string using t#ose %elimiters creates a list of name/.alue pairs w#ic# can 3e parse% easil on t#e ser.er+si%e an% utiliAe% to en#ance %ata3ase Dueries as nee%e%. T#e %elimiters t#at #a.e wor8e% as con.entions are t#e .ertical 3ar /FWG1 to separate in%i.i%ual filter p#rases an% a %ou3le colon /FJJG1 to separate t#e names an% .alues. T#is pro.i%es a uniDue+enoug# set of %elimiters to support t#e maEorit of use cases an% creates a user+ rea%a3le Duer +string parameter. A simple e@ample will ser.e to clarif t#e tec#niDue. $uppose we want to reDuest users wit# t#e name FTo%%G w#o li.e in Den.er an% #a.e t#e title of F?ran% Poo3a#G. T#e reDuest )R&C complete wit# Duer +string mig#t loo8 li8e t#isJ &"T http/00www.example.com0users=filter>Mname//todd<city//denver<title//grand poobahI T#e %elimiter of t#e %ou3le colon /FJJG1 separates t#e propert name from t#e comparison .alueC ena3ling t#e comparison .alue to contain spacesHma8ing it easier to parse t#e %elimiter from t#e .alue on t#e ser.er. ;ote t#at t#e propert names in t#e name/.alue pairs matc# t#e name of t#e properties t#at woul% 3e returne% 3 t#e ser.ice in t#e pa loa%. 03/26/14 www.RestApiTutorial.com Page 2* of 40

RESTful Service Best Practices $imple 3ut effecti.e. 2ase sensiti.it is certainl up for %e3ate on a case+3 +case 3asisC 3ut in generalC filtering wor8s 3est w#en case is ignore%. Oou can also offer wil%+car%s as nee%e% using t#e asteris8 /FXG1 as t#e .alue portion of t#e name/.alue pair. >or Dueries t#at reDuire more+t#an simple eDualit or wil%+car% comparisonsC intro%uction of operators is necessar . &n t#is caseC t#e operators t#emsel.es s#oul% 3e part of t#e .alue an% parse% on t#e ser.er si%eC rat#er t#an part of t#e propert name. "#en comple@ Duer +language+st le functionalit is nee%e%C consi%er intro%ucing Duer concept from t#e 0pen Data Protocol /0Data1 >ilter $ stem 7uer 0ption specification /see #ttpJ//www.o%ata.org/%ocumentation/uri+ con.entionsS>ilter$ stem7uer 0ption1.

Sortin!
>or our purposesC sorting is %efine% as %etermining t#e or%er in w#ic# items in a pa loa% are returne% from a ser.ice. &n ot#er wor%sC t#e sort or%er of multiple items in a response pa loa%. AgainC con.ention #ere sa s to %o somet#ing simple. T#e recommen%e% approac# is to utiliAe a sort Duer +string parameter t#at contains a %elimite% set of propert names. ,e#a.ior isC for eac# propert nameC sort in ascen%ing or%erC an% for eac# propert prefi@e% wit# a %as# /F+G1 sort in %escen%ing or%er. $eparate eac# propert name wit# a .ertical 3ar /FWG1C w#ic# is consistent wit# t#e separation of t#e name/.alue pairs in filteringC a3o.e. >or e@ampleC if we want to retrie.e users in or%er of t#eir last name /ascen%ing1C first name /ascen%ing1 an% #ire %ate /%escen%ing1C t#e reDuest mig#t loo8 li8e t#isJ &"T http/00www.example.com0users=sort>last;name<first;name<Fhire;date ;ote t#at again t#e propert names matc# t#e name of t#e properties t#at woul% 3e returne% 3 t#e ser.ice in t#e pa loa%. A%%itionall C 3ecause of its comple@it C offer sorting on a case+3 +case 3asis for onl resources t#at nee% it. $mall collections of resources can 3e or%ere% on t#e clientC if nee%e%.

Ser"ice *ersionin!
$traig#t+upC .ersioning is #ar%C ar%uousC %ifficultC fraug#t wit# #eartac#eC e.en pain an% e@treme sa%ness++let[s Eust sa it a%%s a lot of comple@it to an AP& an% possi3l to t#e clients t#at access it. 2onseDuentl C 3e %eli3erate in our AP& %esign an% ma8e efforts to not nee% .ersione% representations. >a.or not .ersioningC instea% of using .ersioning as a crutc# for poor AP& %esign. Oou[ll #ate ourself in t#e morning if ou nee% to .ersion our AP&s at allC let alone freDuentl . 6ean on t#e i%ea t#at wit# t#e a%.ent of =$0; usage for representationsC clients can 3e tolerant to new properties appearing in a response wit#out 3rea8ing. ,ut e.en t#at is la%en wit# %anger in certain casesC suc# as c#anging t#e meaning of an e@isting propert wit# eit#er contents or .ali%ation rules. &ne.ita3l t#ere will come a time w#en an AP& reDuires a c#ange to its returne% or e@pecte% representation t#at will cause consumers to 3rea8 an% t#at 3rea8ing c#ange must 3e a.oi%e%. :ersioning our AP& is t#e wa to a.oi% 3rea8ing our clients an% consumers.

03/26/14

www.RestApiTutorial.com

Page 24 of 40

RESTful Service Best Practices

S#pport Versionin! via Content $e!otiation


Historicall .ersioning was accomplis#e% .ia a .ersion num3er in t#e )R& itselfC wit# clients in%icating w#ic# .ersion of a resource t#e %esire% %irectl in t#e )R& t#e reDueste%. &n factC man of t#e F3ig 3o sG suc# as TwitterC OammerC >ace3oo8C ?oogleC etc. freDuentl utiliAe .ersion num3ers in t#eir )R&s. '.en AP& management tools suc# as "$02 #a.e re"uired .ersion num3ers in t#e e@pose% )R6s. T#is tec#niDue flies in t#e face of t#e R'$T constraints as it %oesnBt em3race t#e 3uilt+in #ea%er s stem of t#e HTTP specificationC nor %oes it support t#e i%ea t#at a new )R& s#oul% 3e a%%e% onl w#en a new resource or concept is intro%uce%++not representation c#anges. Anot#er argument against it is t#at resource )R&s arenBt meant to c#ange o.er time. A resource is a resource. T#e )R& s#oul% 3e simpl to i%entif t#e resource++not its \s#ape[. Anot#er concept must 3e use% to specif t#e format of t#e response /representation1. T#at Fot#er conceptG is a pair of HTTP #ea%ersJ %ccept an% )ontentFType. T#e %ccept #ea%er allows clients to specif t#e me%ia t pe /or t pes1 of t#e response t#e %esire or can support. T#e )ontentFType #ea%er is use% 3 3ot# clients an% ser.ers to in%icate t#e format of t#e reDuest or response 3o% C respecti.el . >or e@ampleC to retrie.e a user in =$0; formatJ
# Request

?'T #ttpJ//api.e@ample.com/users/1234! AcceptJ application/Eson] .ersionM1


# Response

HTTP/1.1 200 0P 2ontent+T peJ application/Eson] .ersionM1 QFi%GJG1234!GC FnameGJG=oe Di-aggioGR ;owC to retrie.e .ersion 2 of t#at same resource in =$0; formatJ
# Request

?'T #ttpJ//api.e@ample.com/users/1234! AcceptJ application/Eson] .ersionM2


# Response

HTTP/1.1 200 0P 2ontent+T peJ application/Eson] .ersionM2 QFi%GJG1234!GC Ffirst;ameGJG=oeGC Flast;ameGJGDi-aggioGR ;otice #ow t#e )R& is t#e same for 3ot# .ersions as it i%entifies t#e resourceC wit# t#e Accept #ea%er 3eing use% to in%icate t#e format /an% .ersion in t#is case1 of t#e %esire% response. Alternati.el C if t#e 03/26/14 www.RestApiTutorial.com Page 29 of 40

RESTful Service Best Practices client %esire% an <-6 formatte% responseC t#e Accept #ea%er woul% 3e set to \application/@ml[ instea%C wit# a .ersion specifie%C if nee%e%. $ince t#e Accept #ea%er can 3e set to allow multiple me%ia t pesC in respon%ing to t#e reDuestC a ser.er will set t#e 2ontent+T pe #ea%er on t#e response to t#e t pe t#at 3est matc#es w#at was reDueste% 3 t#e client. Please see #ttpJ//www.w3.org/Protocols/rfc2616/rfc2616+sec14.#tml for more information. >or e@ampleJ # Request ?'T #ttpJ//api.e@ample.com/users/1234! AcceptJ application/Eson] .ersionM1C application/@ml] .ersionM1 T#e a3o.e reDuestC assuming t#e ser.er supports one or 3ot# of t#e reDueste% t pesC will eit#er 3e in =$0; or <-6 formatC %epen%ing on w#ic# t#e ser.er fa.ors. ,ut w#ic#e.er t#e ser.er c#oosesC will 3e set on t#e 2ontent+T pe #ea%er in t#e response. >or e@ampleC t#e response from t#e ser.er if it fa.ors application0xml woul% 3eJ # Response HTTP/1.1 200 0P 2ontent+T peJ application/@ml] .ersionM1 UuserV Ui%V1234!U/i%V UnameV=oe Di-aggioU/nameV U/userV To illustrate t#e use of 2ontent+T pe w#en sen%ing %ata to t#e ser.erC #ere is an e@ample of creating a new user using =$0; formatJ # Request P0$T #ttpJ//api.e@ample.com/users 2ontent+T peJ application/Eson] .ersionM1 QFnameGJG-arco PoloGR 0rC if .ersion 2 was in pla J # Request P0$T #ttpJ//api.e@ample.com/users 2ontent+T peJ application/Eson] .ersionM2 QFfirst;ameGJG-arcoGC Flast;ameGJGPoloGR

03/26/14

www.RestApiTutorial.com

Page 30 of 40

RESTful Service Best Practices

What "ersion is returned 0hen no "ersion is s ecified?


$uppl ing a .ersion on eac# reDuest is optional. As HTTP content+negotiation follows a F3est matc#G approac# wit# content t pesC so s#oul% our AP&s. )sing t#is F3est matc#G conceptC w#en t#e consumer %oes not specif a .ersionC t#e AP& s#oul% return t#e ol%est supporte% .ersion of t#e representation. >or e@ampleC to retrie.e a user in =$0; formatJ
# Request

?'T #ttpJ//api.e@ample.com/users/1234! AcceptJ application/Eson


# Response

HTTP/1.1 200 0P 2ontent+T peJ application/Eson] .ersionM1 QFi%GJG1234!GC FnameGJG=oe Di-aggioGR $imilarl C w#en P0$Ting %ata to an en%point t#at supports multiple .ersions wit#out a .ersionC t#e same rules as a3o.e appl ++t#e lowest/earliest supporte% .ersion is e@pecte% in t#e 3o% . To illustrateC #ere is an e@ample of creating a new user on a multi+.ersion en%point using =$0; format /it e@pects .ersion 11J # Request P0$T #ttpJ//api.e@ample.com/users 2ontent+T peJ application/Eson QFnameGJG-arco PoloGR
# Response

HTTP/1.1 201 0P 2ontent+T peJ application/Eson] .ersionM1 6ocationJ #ttpJ//api.e@ample.com/users/1234! QFi%GJG1234!GC FnameGJG-arco PoloGR

1nsu

orted *ersions Re2uested

"#en an unsupporte% .ersion num3er is reDueste%C inclu%ing a resource .ersion t#at #as gone t#roug# t#e AP& %eprecation lifec cleC t#e AP& s#oul% return an error response wit# 406 /;ot Accepta3le1 HTTP status co%e. &n a%%itionC t#e AP& s#oul% return a response 3o% wit# 2ontent+T peJ application/Eson 03/26/14 www.RestApiTutorial.com Page 31 of 40

RESTful Service Best Practices t#at contains a =$0; arra of supporte% content t pes for t#at en%point. # Request >or e@ampleJ ?'T #ttpJ//api.e@ample.com/users/1234! 2ontent+T peJ application/Eson] .ersionM### # Response HTTP/1.1 406 ;0T A22'PTA,6' 2ontent+T peJ application/Eson ^Fapplication/Eson] .ersionM1GC Fapplication/Eson] .ersionM2GC Fapplication/@ml] .ersionM1GC Fapplication/@ml] .ersionM2G_

2hen Sho#ld I Create a $e3 Version4


&n AP& %e.elopment t#ere are man wa s to 3rea8 a contract an% negati.el impact our clients. &f ou are uncertain of t#e conseDuences of our c#ange it is 3etter to pla it safe an% consi%er .ersioning. T#ere are se.eral factors to consi%er w#en ou are tr ing to %eci%e if a new .ersion is appropriate or if a mo%ification of an e@isting representation is sufficient an% accepta3le.

Chan!es that 0ill brea( contracts


2#anging a propert name /ie. FnameG to Ffirst;ameG1 Remo.al of propert 2#anging propert %ata t pe /numeric to stringC 3oolean to 3it/numericC string to %atetimeC etc.1 :ali%ation rule c#ange &n Atom st le lin8sC mo%if ing t#e FrelG .alue. A reDuire% resource is 3eing intro%uce% into an e@isting wor8flow Resource concept/intent c#ange] t#e concept/intent or t#e meaning of t#e resource[s state #as a %ifferent meaning from it[s original. '@amplesJ A resource wit# t#e content t pe te@t/#tml once meant t#at t#e representation woul% 3e a collection of Flin8sG to all supporte% me%ia t pesC new te@t/#tml representation means Fwe3 3rowser formG for user input An AP& populating an Fen%TimeG on t#e resource F.../users/Qi%R/e@ams/Qi%RG once meant t#e stu%ent su3mitte% t#e e@am at t#at timeC t#e new meaning is t#at it will 3e t#e sc#e%ule% en% time of t#e e@am. A%%ing new fiel%s t#at came from an e@isting resource wit# t#e intent to %eprecate t#e e@isting resource. 2om3ining two resources into one an% %eprecating t#e two original resources. T#ere are two resourcesC F.../users/Qi%R/%rop3o@,as8ets/Qi%R/messages/Qi%RG an% F.../users/Qi%R/%rop3o@,as8ets/Qi%R/messages/Qi%R/rea%$tatusG. T#e new reDuirement is

03/26/14

www.RestApiTutorial.com

Page 32 of 40

RESTful Service Best Practices to put t#e properties from t#e rea%$tatus resource into t#e in%i.i%ual message resource an% %eprecate t#e rea%$tatus resource. T#is will cause t#e remo.al of a lin8 to t#e rea%$tatus resource in t#e in%i.i%ual messages resource. "#ile t#is list is not full+inclusi.eC it gi.es ou an i%ea of t#e t pes of c#anges t#at will cause #a.oc for our clients an% reDuire a new resource or a new .ersion.

Chan!es considered non-brea(in!


;ew properties a%%e% to a =$0; response. ;ew/a%%itional Flin8G to ot#er resources. ;ew content+t pe supporte% formats. ;ew content+language supporte% formats. 2asing is irrele.ant as 3ot# t#e AP& pro%ucer an% consumer s#oul% #an%le .arie% casing.

.t 2hat Level Sho#ld Versionin! 'cc#r4


&t is recommen%e% to .ersion at t#e in%i.i%ual resource le.el. $ome c#anges to an AP& suc# as mo%if ing t#e wor8flow ma reDuire .ersioning across multiple resource to pre.ent 3rea8ing clients.

Use Content)Location to +nhance "esponses


0ptional. $ee RD> spec.

Lin0s 3ith Content)Type


Atom+st le lin8s support a Bt peB propert . Pro.i%e enoug# information so t#at clients can construct necessar calls to specific .ersion N content t pe.

(indin! '#t 2hat Versions are S#pported


Ho0 many "ersions should I su ort at once?
ou s#oul% $ince maintaining man .ersions 3ecomes cum3ersomeC comple@C error proneC an% costl support no more t#an 2 .ersions for an gi.en resource.

De recated
T#e term %eprecate% is inten%e% to 3e use% to communicate t#at a resource is still a.aila3le 3 t#e AP&C 3ut will 3ecome una.aila3le an% no longer e@ist in t#e future. Note: The length of time in deprecation
will be determined by the deprecation policy- not yet defined.

03/26/14

www.RestApiTutorial.com

Page 33 of 40

RESTful Service Best Practices

Ho0 do I inform clients about de recated resources?


-an clients will 3e using resources t#at are to 3e %eprecate% after new .ersions are intro%uce% an% in %oing soC t#e will nee% wa s to %isco.er an% monitor t#eir applications use of %eprecate% resources. "#en a %eprecate% resource is reDueste%C t#e AP& s#oul% return a normal response wit# t#e Pearson custom Hea%er FDeprecate%G in a 3oolean format. ,elow is an e@ample to illustrate.
# Request

?'T #ttpJ//api.e@ample.com/users/1234! AcceptJ application/Eson 2ontent+T peJ application/Eson] .ersionM1


# Response

HTTP/1.1 200 0P 2ontent+T peJ application/Eson] .ersionM1 Deprecate%J true QFi%GJG1234!GC FnameGJG=oe Di-aggioGR

Date3Time Handlin!
Dates an% timestamps can 3e a real #ea%ac#e if not %ealt wit# appropriatel an% consistentl . TimeAone issues can crop up easil an% since %ates are Eust strings in =$0; pa loa%sC parsing is a real issue if t#e format isnBt 8nownC consistent or specifie%. &nternall C ser.ices s#oul% storeC processC cac#eC etc. suc# timestamps in )T2 or ?-T time. T#is alle.iates timeAone issues wit# 3ot# %ates an% timestamps.

,ate5Time Seriali/ation In 6ody Content


T#ereBs an eas wa aroun% all of t#isHalwa s use t#e same formatC inclu%ing t#e time portion /along wit# timeAone information1 in t#e string. &$0 4601 time point format is a goo% solutionC using t#e full +en#ance% format t#at inclu%es #oursC minutesC secon%s an% a %ecimal fraction of secon%s /e.g. +--+%%BTBHHJmmJss.$$$B`B1. &t is recommen%e% t#at &$0 4601 3e use% for all %ates represente% in R'$T ser.ice 3o% content /3ot# reDuests an% responses1. &nci%entall C for t#ose %oing =a.a+3ase% ser.icesC t#e DateA%apter= li3rar easil parses an% formats &$04601 %ates an% time points an% HTTP 1.1 #ea%er /R>2 11231 formatsC wit# its DateA%apterC &so4601TimepointA%apter an% HttpHea%erTimestampA%apter implementation classesC respecti.el . &t can 3e %ownloa%e% at #ttpsJ//git#u3.com/tfre%ric#/DateA%apter=. >or t#ose creating 3rowser+3ase% )&sC t#e '2-A$cript ! specification inclu%es parsing an% creating &$04601 %ates in =a.a$cript nati.el C so it s#oul% 3e ma8ing its wa into all mainstream 3rowsers as we spea8. &f ouBre supporting ol%er 3rowsers t#at %onBt nati.el parse t#ose %atesC a =a.a$cript li3rar or fanc regular e@pression is in or%er. A couple of sample =a.a$cript li3raries t#at can parse an% 03/26/14 www.RestApiTutorial.com Page 34 of 40

RESTful Service Best Practices pro%uce &$04601 Timepoints areJ #ttpJ//momentEs.com/ #ttpJ//www.%ateEs.com/

,ate5Time Seriali/ation In HTTP Headers


"#ile t#e a3o.e recommen%ation wor8s for =$0; an% <-6 content in t#e content of an% HTTP reDuest or responseC t#e HTTP specification utiliAes a %ifferent format for HTTP #ea%ers. $pecifie% in R>2 422 w#ic# was up%ate% 3 R>2 1123C t#at format inclu%es .arious %ateC time an% %ate+time formats. Howe.erC it is recommen%e% to alwa s use a timestamp formatC w#ic# en%s up loo8ing li8e t#is in our reDuest #ea%ersJ $unC 06 ;o. 1994 04J49J3* ?-T )nfortunatel C it %oesnBt account for a millisecon% or %ecimal fraction of a secon% in its format. T#e =a.a $impleDate>ormat specifier string isJ I'''C %% --HHJmmJss B?-TBI

Securin! Ser"ices
Aut#entication is t#e act of .erif ing t#at a gi.en reDuest is from someone /or some s stem1 t#at is 8nown to t#e ser.ice an% t#at t#e reDuestor is w#o t#e sa t#e are. "#ile aut#entication is t#e act of .erif ing a reDuestor is w#o t#e sa t#e areC aut#oriAation is .erif ing t#e reDuestor #as permission to perform t#e reDueste% operation. 'ssentiall C t#e process goes somet#ing li8e t#isJ 1. 2lient ma8es a reDuestC inclu%ing aut#entication to8en in OF%uthoriNation #ea%er or to,en Duer +string parameter in t#e reDuest. 2. $er.ice .erifies presence of t#e aut#oriAation to8enC .ali%ates it /t#at itBs .ali% an% not e@pire%1 an% parses or loa%s t#e aut#entication principal 3ase% on t#e to8en contents. 3. $er.ice ma8es a call to t#e aut#oriAation ser.ice pro.i%ing aut#entication principalC reDueste% resource an% reDuire% permission for operation. 4. &f aut#oriAe%C ser.ice continues wit# normal processing. S3 a3o.e coul% 3e e@pensi.eC 3ut assuming a cac#ea3le access+control list /A261C it is concei.a3le to create an aut#oriAation client t#at cac#es t#e most+recent A26s to .ali%ate locall 3efore ma8ing remote calls.

.#thentication
2urrent 3est practice is to use 0Aut# for aut#entication. 0Aut#2 is #ig#l recommen%e%C 3ut is still in %raft state. 0Aut#1 is %efinitel an accepta3le alternati.e. 3+6egge% 0Aut# is also an option for certain cases. Rea% more a3out t#e 0Aut# specification at #ttpJ//oaut#.net/%ocumentation/spec/. 0pen&D is an a%%itional option. Howe.erC it is recommen%e% t#at 0pen&D 3e use% as an additional aut#entication optionC le.eraging 0Aut# as primar . Rea% more a3out t#e 0pen&D specification at 03/26/14 www.RestApiTutorial.com Page 3! of 40

RESTful Service Best Practices #ttpJ//openi%.net/%e.elopers/specs/.

Transport Sec#rity
All aut#entication s#oul% use $$6. 0Aut#2 reDuires t#e aut#oriAation ser.er an% access to8en cre%entials to use T6$. $witc#ing 3etween HTTP an% HTTP$ intro%uces securit wea8nesses an% 3est practice is to use T6$ 3 %efault for all communication.

.#thori/ation
Aut#oriAation for ser.ices is not reall an %ifferent t#an aut#oriAation for an application. &tBs 3ase% on t#e DuestionC FDoes t#is principal #a.e t#e reDueste% permission on t#e gi.en resource(G ?i.en t#at simple trifecta of %ata /principalC resourceC an% permission1C itBs fairl eas to construct an aut#oriAation ser.ice t#at supports t#e concepts. "#ere Principal is t#e person or s stem w#o is grante% a permission on a resource. )sing t#ose generic conceptsC it is possi3le to #a.e a cac#ea3le access control list /A261 for eac# principal.

.pplication Sec#rity
T#e same principles in %e.eloping a secure we3 application #ol%s true for R'$Tful ser.ices. :ali%ate all input on t#e ser.er. Accept F8nownG goo% input an% reEect 3a% input. Protect against $76 an% ;o$76 inEection. 0utput enco%e %ata using 8nown li3raries suc# as -icrosoft[s Anti+<$$ or 0"A$P[s Anti$amm . Restrict t#e message siAe to t#e e@act lengt# of t#e fiel%. $er.ices s#oul% onl %ispla generic error messages. 2onsi%er 3usiness logic attac8s. >or e@ample coul% an attac8er s8ip t#roug# a multi+step or%ering process an% or%er a pro%uct wit#out #a.ing to enter cre%it car% information( 6og suspicious acti.it . :ali%ate =$0; an% <-6 for malforme% %ata. :er3s s#oul% 3e restricte% to t#e allowa3le met#o%. >or e@ampleC a ?'T reDuest s#oul% not 3e a3le to %elete an entit . A ?'T woul% rea% t#e entit w#ile a D'6'T' woul% remo.e t#e entit . ,e aware of race con%itions.

R'$Tful $ecurit 2onsi%erationsJ

AP& gatewa s can 3e use% to monitorC t#rottleC an% control access to t#e AP&. T#e following can 3e %one 3 a gatewa or 3 t#e R'$Tful ser.ice. -onitor usage of t#e AP& an% 8now w#at acti.it is goo% an% w#at falls out of normal usage patterns. T#rottle AP& usage so t#at a malicious user cannot ta8e %own an AP& en%point /D0$ attac81 an% #a.e t#e a3ilit to 3loc8 a malicious &P a%%ress. www.RestApiTutorial.com Page 36 of 40

03/26/14

RESTful Service Best Practices $tore AP& 8e s in a cr ptograp#icall secure 8e store.

Cachin! and Scalability


2ac#ing en#ances scala3ilit 3 ena3ling la ers in t#e s stem to eliminate remote calls to retrie.e reDueste% %ata. $er.ices en#ance cac#e+a3ilit 3 setting #ea%ers on responses. )nfortunatel C cac#ing+relate% #ea%ers in HTTP 1.0 are %ifferent t#an t#ose in HTTP 1.1C so ser.ices s#oul% support 3ot#. ,elow is a ta3le of minimal #ea%ers reDuire% to support cac#ing for ?'T reDuestsC along wit# a %escription of appropriate .alues. HTTP Header Description Date 2ac#e+2ontrol Date an% time t#e response was returne% /in R>21123 format1. T#e ma@imum num3er of secon%s /ma@ age1 a response can 3e cac#e%. Howe.erC if cac#ing is not supporte% for t#e responseC t#en no+cac#e is t#e .alue. &f ma@ age is gi.enC contains t#e timestamp /in R>21123 format1 for w#en t#e response e@piresC w#ic# is t#e .alue of Date /e.g. now1 plus ma@ age. &f cac#ing is not supporte% for t#e responseC t#is #ea%er is not present. E$ample DateJ $unC 06 ;o. 1994 04J49J3* ?-T 2ac#e+2ontrolJ 360 2ac#e+2ontrolJ no+cac#e

'@pires

'@piresJ $unC 06 ;o. 1994 04J49J3* ?-T

Pragma 6ast+-o%ifie%

"#en 2ac#e+2ontrol is Bno+cac#eB t#is #ea%er is PragmaJ no+cac#e also set to Bno+cac#eB. 0t#erwiseC it is not present. T#e timestamp t#at t#e resource itself was mo%ifie% last /in R>21123 format1. 6ast+-o%ifie%J $unC 06 ;o. 1994 04J49J3* ?-T

To simplif C #ereBs an e@ample #ea%er set in response to a simple ?'T reDuest on a resource t#at ena3les cac#ing for one %a /24 #ours1J )acheF)ontrol/ 8:4EE !ate/ Ced, 27 Deb 2E12 23/E1/1E &+T LastF+odified/ +on, 28 Deb 2E11 13/1E/14 &+T "xpires/ Thu, E1 +ar 2E12 23/E1/1E &+T An% 3elow is an e@ample of a similar response t#at %isa3les cac#ing altoget#erJ )acheF)ontrol/ noFcache Pragma/ noFcache

The ETa! Header


T#e 'Tag #ea%er is useful for .ali%ating t#e fres#ness of cac#e% representationsC as well as #elping wit# con%itional rea% an% up%ate operations /?'T an% P)TC respecti.el 1. &ts .alue is an ar3itrar 03/26/14 www.RestApiTutorial.com Page 3* of 40

RESTful Service Best Practices string for t#e .ersion of a representation. Howe.erC it also s#oul% 3e %ifferent for eac# format of a representationHt#e 'Tag for a =$0; response will 3e %ifferent for t#e same resource represente% in <-6. T#e .alue for t#e 'Tag #ea%er can 3e as simple as a #as# of t#e un%erl ing %omain o3Eect /e.g. 03Eect.#as#co%e/1 in =a.a1 wit# t#e format inclu%e% in t#e #as#. &t is recommen%e% to return an 'Tag #ea%er for eac# ?'T /rea%1 operation. A%%itionall C ma8e sure to surroun% t#e 'Tag .alue in %ou3le Duotes. >or e@ampleJ "Tag/ M:8:879:7:a9c89:b9eM

03/26/14

www.RestApiTutorial.com

Page 34 of 40

RESTful Service Best Practices

HTT) Status Codes $To 45&


,elow are t#e most commonl +use% HTTP status co%es returne% from R'$Tful ser.ices or AP&s along wit# a 3rief summar of t#eir commonl +accepte% usage. 0t#er HTTP status co%es are use% occasionall C 3ut are eit#er specialiAations or more a%.ance%. -ost ser.ice suites are well ser.e% 3 supporting onl t#eseC or e.en a su3+set. %&& '()* 5 ?eneral success status co%e. -ost common co%e to in%icate success. %&+ ',RE-TED* 5 $uccessful creation occurre% /.ia eit#er P0$T or P)T1. $et t#e 6ocation #ea%er to contain a lin8 to t#e newl +create% resource. Response 3o% content ma or ma not 3e present. %&. '/( ,(/TE/T* 5 $tatus w#en wrappe% responses are not use% an% not#ing is in t#e 3o% /e.g. D'6'T'1. 0&. '/(T 1(D232ED* 5 )se% in response to con%itional ?'T calls to re%uce 3an%+wi%t# usage. &f use%C must set t#e DateC 2ontent+6ocationC 'tag #ea%ers to w#at t#e woul% #a.e 3een on a regular ?'T call. T#ere must 3e no response 3o% . .&& 'B-D RE45EST* 5 ?eneral error w#en fulfilling t#e reDuest woul% cause an in.ali% state. Domain .ali%ation errorsC missing %ataC etc. are some e@amples. .&+ '5/-5TH(R26ED* 5 'rror co%e for a missing or in.ali% aut#entication to8en. .&0 '3(RB2DDE/* 5 'rror co%e for user not aut#oriAe% to perform t#e operationC %oesnBt #a.e rig#ts to access t#e resourceC or t#e resource is una.aila3le for some reason /e.g. time constraintsC etc.1. .&. '/(T 3(5/D* 5 )se% w#en t#e reDueste% resource is not foun%C w#et#er it %oesnBt e@ist or if t#ere was a 401 or 403 t#atC for securit reasonsC t#e ser.ice wants to mas8. .&# ',(/372,T* 5 "#ene.er a resource conflict woul% 3e cause% 3 fulfilling t#e reDuest. Duplicate entriesC %eleting root o3Eects w#en casca%e+%elete not supporte% are a couple of e@amples. 8&& '2/TER/-7 SERVER ERR(R* 5 T#e general catc#+all error w#en t#e ser.er+si%e t#rows an e@ception.

03/26/14

www.RestApiTutorial.com

Page 39 of 40

RESTful Service Best Practices

#dditional Resources
6oo0s
R"#T %PI !esign Ruleboo,C -ar8 -asseC 2011C 0[Reill -e%iaC &nc. R"#Tful Ceb #ervicesC 6eonar% Ric#ar%son an% $am Ru3 C 2004C 0[Reill -e%iaC &nc. R"#Tful Ceb #ervices )oo,boo,C $u33u AllamaraEuC 2010C 0[Reill -e%iaC &nc. R"#T in Practice/ Hypermedia and #ystems %rchitectureC =im "e33erC et al.C 2010C 0[Reill -e%iaC &nc. %PIs/ % #trategy &uideC Daniel =aco3son] ?reg ,rail] Dan "oo%sC 2011C 0BReill -e%iaC &nc.

2ebsites
#ttpJ//www.restapitutorial.com #ttpJ//www.to%%fre%ric#.com #ttpJ//www.ics.uci.e%u/Kfiel%ing/pu3s/%issertation/restLarc#Lst le.#tm #ttpJ//www.Eson.org/ #ttpsJ//git#u3.com/tfre%ric#/DateA%apter= #ttpJ//openi%.net/%e.elopers/specs/ #ttpJ//oaut#.net/%ocumentation/spec/ #ttpJ//www.Eson.org/=$0;ReDuest.#tml #ttpJ//la3s.omniti.com/la3s/Esen% #ttpJ//ena3le+cors.org/ #ttpJ//www.o%ata.org/%ocumentation/uri+con.entionsS>ilter$ stem7uer 0ption #ttpJ//ro .g3i..com/untangle%/2004/rest+apis+must+3e+# perte@t+%ri.en #ttpsJ//%e.eloper.lin8e%in.com/apis #ttpJ//%e.elopers.face3oo8.com/%ocs/reference/api/ #ttpsJ//%e..twitter.com/%ocs/api #ttpJ//momentEs.com/ #ttpJ//www.%ateEs.com/

03/26/14

www.RestApiTutorial.com

Page 40 of 40

You might also like