+ All Categories
Home > Documents > RESTful Best Practices-v1_2.odt

RESTful Best Practices-v1_2.odt

Date post: 03-Jun-2018
Category:
Upload: julietagoebbels
View: 226 times
Download: 0 times
Share this document with a friend

of 40

Transcript
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    1/40

    RESTful Service Best Practices

    RESTful Service Best PracticesRecommendations for Creating Web Services

    Todd Fredrich

    Pearson eCollege

    @tfredrich

    www.RestApiTutorial.com

    03/26/14 www.RestApiTutorial.com Page 1 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    2/40

    RESTful Service Best Practices

    03/26/14 www.RestApiTutorial.com Page 2 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    3/40

    RESTful Service Best Practices

    Table of ContentsDocument 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+%escriptie -essages................................................................................................................*

    Hperme%ia as t#e 'ngine of Application $tate HAT'A$.........................................................*$tateless.................................................................................................................................................*

    ac#eale..............................................................................................................................................

    lient5serer.........................................................................................................................................aere% sstem......................................................................................................................................

    o%e on %eman% optional...................................................................................................................

    R'$T 7uic8 Tips.......................................................................................................................................9)se HTTP :ers to -ean $omet#ing...................................................................................................9$ensile Resource ;ames.....................................................................................................................9

    ine+?raine% Resources...........................................................................................................10onsi%er onnecte%ness......................................................................................................................10

    Definitions................................................................................................................................................10

    &%empotence........................................................................................................................................10$afet...................................................................................................................................................11

    HTTP :ers..............................................................................................................................................11

    ?'T.....................................................................................................................................................11

    P)T.....................................................................................................................................................12P$T...................................................................................................................................................12

    P)T s P$T for reation..................................................................................................................13

    D''T'..............................................................................................................................................13Resource ;aming.....................................................................................................................................14

    Resource )R& '@amples.....................................................................................................................1!

    Resource ;aming Anti+Patterns..........................................................................................................16Pluraliation.........................................................................................................................................16

    Returning Representations.......................................................................................................................1*

    Resource Discoerailit T#roug# in8s HAT'A$ contB%...........................................................1-inimal in8ing Recommen%ations..............................................................................................19

    in8 >ormat....................................................................................................................................19"rappe% Responses.............................................................................................................................21

    Han%ling ross+Domain &ssues...........................................................................................................22$upporting R$...........................................................................................................................22

    $upporting =$;P..........................................................................................................................22

    7ueringC >iltering an% Pagination..........................................................................................................23imiting Results..................................................................................................................................24

    03/26/14 www.RestApiTutorial.com Page 3 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    4/40

    RESTful Service Best Practices

    imiting ia t#e Range Hea%er.......................................................................................................2!imiting ia 7uer+$tring Parameters............................................................................................2!

    Range+,ase% Responses.................................................................................................................2!

    Pagination............................................................................................................................................26

    >iltering an% $orting Results...............................................................................................................2*>iltering..........................................................................................................................................2*

    $orting............................................................................................................................................2

    $erice :ersioning...................................................................................................................................2$upport :ersioning ia ontent ;egotiation.......................................................................................29

    "#at ersion is returne% w#en no ersion is specifie%(.................................................................31

    )nsupporte% :ersions Reueste%...................................................................................................31"#en $#oul% & reate a ;ew :ersion(...............................................................................................32

    #anges t#at will rea8 contracts...................................................................................................32

    #anges consi%ere% non+rea8ing..................................................................................................33

    At "#at eel $#oul% :ersioning ccur(..........................................................................................33)se ontent+ocation to 'n#ance Responses.....................................................................................33

    in8s wit# ontent+Tpe.....................................................................................................................33

    >in%ing ut "#at :ersions are $upporte%..........................................................................................33How man ersions s#oul% & support at once(...............................................................................33

    Deprecate%......................................................................................................................................33

    How %o & inform clients aout %eprecate% resources(....................................................................34Date/Time Han%ling.................................................................................................................................34

    Date/Time $erialiation &n ,o% ontent...........................................................................................34

    Date/Time $erialiation &n HTTP Hea%ers..........................................................................................3!$ecuring $erices.....................................................................................................................................3!

    Aut#entication.....................................................................................................................................3!

    Transport $ecurit...............................................................................................................................36

    Aut#oriation.......................................................................................................................................36Application $ecurit............................................................................................................................36

    ac#ing an% $calailit...........................................................................................................................3*

    T#e 'Tag Hea%er............................................................................................................................3*HTTP $tatus o%es Top 10...................................................................................................................39

    A%%itional Resources...............................................................................................................................40

    ,oo8s...................................................................................................................................................40"esites...............................................................................................................................................40

    03/26/14 www.RestApiTutorial.com Page 4 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    5/40

    RESTful Service Best Practices

    Document History

    Date Version Description

    >e 10C 2012 Draft &nitial %raft ersion.Apr 24C 2012 1.0 &nitial pulic non+%raft ersion.

    -a 29C 2012 1.1 -inor up%ates to correct misspellings an% clarif wor%ing afterfee%ac8 from AP& ,est Practices Tas8 force.

    Aug 2C 2013 1.2 )p%ate% ersioning section. A%%itional minor corrections of

    misspellingsC wor%ingC etc.

    Who Should Read This Document

    T#is est+practices %ocument is inten%e% for %eelopers w#o are intereste% in creating R'$Tful "e

    serices t#at proi%e #ig# reliailit an% consistenc across multiple serice suites. , following t#esegui%elinesC serices are well positione% for rapi%C wi%esprea%C pulic a%option ot# 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 serices

    %eelope% using t#ese est practices. "#ile t#eir concerns ma e focuse% on cac#ing practicesC pro@

    rulesC monitoringC securit an% suc#C t#is %ocument ma e useful as an oerarc#ing serice%ocumentation gui%e of sorts.

    A%%itionallC management personnel ma enefit from t#ese gui%elines en%eaoring to un%erstan%

    t#e effort reuire% to create serices t#at are pulicl consumale an% offer #ig# leels of consistenc

    across t#eir serice suites.

    03/26/14 www.RestApiTutorial.com Page ! of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    6/40

    RESTful Service Best Practices

    Introduction

    T#ere are numerous resources on est practices for creating R'$Tful we serices see t#e Resources

    section at t#e en% of t#is %ocument. -an of t#e aailale resources are conflictingC %epen%ing on

    w#en t#e were written. PlusC rea%ing an% compre#en%ing seeral oo8s on t#e suEect in or%er toimplement serices FtomorrowG is not %oale. &n or%er to facilitate t#e uic8 upta8e an% un%erstan%ingof R'$Tful conceptsC wit#out reuiring t#e rea%ing of at least t#ree to fie oo8s on t#e suEectC t#is

    gui%e is meant to spee% up t#e processcon%ensing R'$T est practices an% conentions 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. t#er t#an its oer+arc#ing si@constraints not#ing is %ictate%. T#ere are Iest practicesI an% %e+facto stan%ar%s ut t#ose are

    constantl eolingwit# religious attles waging continuousl.

    Designe% to e riefC t#is %ocument proi%es recommen%ations an% some coo8oo8+stle %iscussion on

    man of t#e common uestions aroun% R'$T an% proi%es some s#ort ac8groun% information to offer

    support for effectie creation of real+worl%C pro%uction+rea%C consistent R'$Tful serices. T#is%ocument aggregates information aailale in ot#er sourcesC a%apting it wit# e@perience gaine% t#roug#

    #ar% 8noc8s.

    T#ere is still consi%erale %eate as to w#et#er R'$T is etter t#an $AP an% ice ersaC an% per#apst#ere are still reasons to create $AP serices. "#ile touc#ing on $APC t#is %ocument wonBt spen% a

    lot of time %iscussing t#e relatie merits. &nstea%C ecause tec#nolog an% t#e in%ustr marc#es onC we

    will procee% wit# t#e assumption t#at leeraging R'$T is t#e current est practice for "e sericecreation.

    T#e first section offers an oeriew of w#at R'$T isC its constraintsC an% w#at ma8es it uniue. T#e

    secon% section supplies some uic8 tips as little remin%ers of R'$T serice concepts. ater sections go

    more in %ept# to proi%e t#e "e serice creator more support an% %iscussion aroun% t#e nitt+gritt%etails of creating #ig#+ualit R'$T serices capale of eing pulicl e@pose% in a pro%uction

    enironment.

    What is REST?

    T#e R'$T arc#itectural stle %escries si@ constraints. T#ese constraintsC applie% to t#e arc#itectureC

    were originall communicate% Ro >iel%ing in #is %octoral %issertation see#ttpJ//www.ics.uci.e%u/Kfiel%ing/pus/%issertation/restLarc#Lstle.#tm an% %efines t#e asis of

    R'$Tful+stle.

    T#e si@ constraints areJ

    )niform &nterface

    $tateless

    ac#eale

    lient+$erer

    aere% $stem

    o%e on Deman%

    03/26/14 www.RestApiTutorial.com Page 6 of 40

    http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htmhttp://www.restapitutorial.com/http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htmhttp://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    7/40

    RESTful Service Best Practices

    A more %etaile% %iscussion of t#e constraints followsJ

    Uniform Interface

    T#e uniform interface constraint %efines t#e interface etween clients an% serers. &t simplifies an%

    %ecouples t#e arc#itectureC w#ic# enales eac# part to eole in%epen%entl. T#e four gui%ingprinciples of t#e uniform interface areJ

    Resource-Based

    &n%ii%ual resources are i%entifie% in reuests using )R&s as resource i%entifiers. T#e resources

    t#emseles are conceptuall separate from t#e representations t#at are returne% to t#e client. >or

    e@ampleC t#e serer %oes not sen% its %ataaseC ut rat#erC some HT-C innis# an% enco%e% in )T>+C %epen%ing on t#e

    %etails of t#e reuest an% t#e serer implementation.

    Maniulation of Resources Throu!h Reresentations

    "#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 sererC proi%e% it #as permission to %o so.

    Self-descriti"e Messa!es

    'ac# message inclu%es enoug# information to %escrie #ow to process t#e message. >or e@ampleC

    w#ic# parser to ino8e ma e specifie% an &nternet me%ia tpe preiousl 8nown as a -&-'

    tpe. Responses also e@plicitl in%icate t#eir cac#e+ailit.

    Hyermedia as the En!ine of #lication State $H#TE%#S&lients %elier state ia o% contentsC uer+string parametersC reuest #ea%ers an% t#e reueste% )R&

    t#e resource name. $erices %elier state to clients ia o% contentC response co%esC an% response#ea%ers. T#is is tec#nicall referre%+to as #perme%ia or #perlin8s wit#in #perte@t.

    Asi%e from t#e %escription aoeC HAT'$ also means t#atC w#ere necessarC lin8s are containe% in

    t#e returne% o% or #ea%ers to suppl t#e )R& for retrieal of t#e oEect itself or relate% oEects.

    "eBll tal8 aout t#is in more %etail later.

    T#e uniform interface t#at an R'$T serices must proi%e is fun%amental to its %esign.

    StatelessAs R'$T is an acronm for REpresentational State TransferCstatelessnessis 8e. 'ssentiallC w#att#is means is t#at t#e necessar state to #an%le t#e reuest is containe% wit#in t#e reuest itselfC

    w#et#er as part of t#e )R&C uer+string parametersC o%C or #ea%ers. T#e )R& uniuel i%entifies t#e

    resource an% t#e o% contains t#e state or state c#ange of t#at resource. T#en after t#e serer %oesitBs processingC t#e appropriate stateC or t#e pieces of state t#at matterC are communicate% ac8 to t#e

    client ia #ea%ersC status an% response o%.

    03/26/14 www.RestApiTutorial.com Page * of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    8/40

    RESTful Service Best Practices

    -ost of us w#o #ae een in t#e in%ustr for a w#ile are accustome% to programming wit#in acontainer w#ic# proi%es us wit# t#e concept of FsessionG w#ic# maintains state across multiple HTTP

    reuests. &n R'$TC t#e client must inclu%e all information for t#e serer to fulfill t#e reuestC resen%ing

    state as necessar if t#at state must span multiple reuests. $tatelessness enales greater scalailit

    since t#e serer %oes not #ae to maintainC up%ate or communicate t#at session state. A%%itionallC loa%alancers %onBt #ae to worr aout session affinit for stateless sstems.

    $o w#atBs t#e %ifference etween state an% a resource( $tateC or application stateC is t#at w#ic# t#e

    serer cares aout to fulfill a reuest%ata necessar for t#e current session or reuest. A resourceC or

    resource stateC is t#e %ata t#at %efines t#e resource representationt#e %ata store% in t#e %ataaseC forinstance. onsi%er application stateto e %ata t#at coul% ar clientC an% per reuest. Resource

    state,on t#e ot#er #an%C is constant across eer client w#o reuests it.

    'er #a% ac8+utton issues wit# a we application w#ere it went A" at a certain point ecause it

    e@pecte% ou to %o t#ings in a certain or%er( T#atBs ecause it iolate% t#estatelessnessprinciple.T#ere are cases t#at %onBt #onor t#estatelessnessprincipleC suc# as t#ree+legge% Aut#C AP& call rate

    limitingC etc. HoweerC ma8e eer effort to ensure t#at application state %oesnBt span multiple reuests

    of our serices.

    Cacheable

    As on t#e "orl% "i%e "eC clients can cac#e responses. Responses must t#ereforeC implicitl or

    e@plicitlC %efine t#emseles as cac#ealeC or notC to preent clients reusing stale or inappropriate %atain response to furt#er reuests. "ell+manage% cac#ing partiall or completel eliminates some client5

    serer interactionsC furt#er improing scalailit an% performance.

    Clientserver

    T#e uniform interface separates clients from serers. T#is separation of concerns means t#atC fore@ampleC clients are not concerne% wit# %ata storageC w#ic# remains internal to eac# sererC so t#at t#e

    portailit of client co%e is improe%. $erers are not concerne% wit# t#e user interface or user stateC sot#at serers can e simpler an% more scalale. $erers an% clients ma also e replace% an% %eelope%

    in%epen%entlC 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% sererC or to an interme%iar

    along t#e wa. &nterme%iar serers ma improe sstem scalailit enaling loa%+alancing an%

    proi%ing s#are% cac#es. aers ma also enforce securit policies.

    Code on demand (optional)

    $erers are ale to temporaril e@ten% or customie t#e functionalit of a client transferring logic toit t#at it can e@ecute. '@amples of t#is ma inclu%e compile% components suc# as =aa applets an%

    client+si%e scripts suc# as =aa$cript.

    ompling wit# t#ese constraintsC an% t#us conforming to t#e R'$T arc#itectural stleC will enale an

    03/26/14 www.RestApiTutorial.com Page of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    9/40

    RESTful Service Best Practices

    8in% of %istriute% #perme%ia sstem to #ae %esirale emergent propertiesC suc# as performanceCscalailitC simplicitC mo%ifiailitC isiilitC portailit an% reliailit.

    ;T'J T#e onl optional constraint of R'$T arc#itecture is code on demand. &f a serice iolates an

    ot#er constraintC it cannot strictl e referre% to as R'$Tful.

    REST 'uic( Tis

    "#et#er itBs tec#nicall R'$Tful or not accor%ing to t#e si@ constraints mentione% aoeC #ere are afew recommen%e% R'$T+li8e concepts t#at will result in etterC more usale sericesJ

    Use HTTP Verbs to ean Somethin!

    An AP& consumer is capale of sen%ing ?'TC P$TC P)TC an% D''T' ersC an% t#e greatlen#ance t#e clarit of w#at a gien reuest %oes. AlsoC ?'T reuests mustnot c#ange an un%erling

    resource %ata. -easurements an% trac8ing ma still occurC w#ic# up%ates %ataC ut not resource %ata

    i%entifie% t#e )R&.

    Sensible "eso#rce $ames

    Haing sensile resource names or pat#s e.g.C /posts/23 instea% of /api(tpeMpostsNi%M23 improes

    t#e clarit of w#at a gien reuest %oes. )sing )R uer+string parameters is fantastic for filteringCut not for resource names.

    Appropriate resource names proi%e conte@t for a serice reuestC increasing un%erstan%ailit of t#e

    serice AP&. Resources are iewe% #ierarc#icall ia t#eir )R& namesC offering consumers a frien%lC

    easil+un%erstoo% #ierarc# of resources to leerage in t#eir applications.

    Resource names s#oul% e nounsaoi% ers as resource names. &t ma8es t#ings more clear. )se t#eHTTP met#o%s to specif t#e er portion of t#e reuest.

    %L and &S'$

    >aor =$; support as t#e %efaultC ut unless t#e costs of offering ot# =$; an%

  • 8/12/2019 RESTful Best Practices-v1_2.odt

    10/40

    RESTful Service Best Practices

    comple@ t#an t#isC see t#e first paragrap# of t#is tipt#e cost of rom a R'$Tful serice stan%pointC for an operation or serice call to e i%empotentC clients canma8e t#at same call repeate%l w#ile pro%ucing t#e same resultoperating muc# li8e a FsetterG

    met#o% in a programming language. &n ot#er wor%sC ma8ing multiple i%entical reuests #as t#e same

    effect as ma8ing a single reuest. ;ote t#at w#ile i%empotent operations pro%uce t#e same result on t#e

    serer si%e effectsC t#e response itself ma not e t#e same e.g. a resourceBs state ma c#angeetween reuests.

    T#e P)T an% D''T' met#o%s are %efine% to e i%empotent. HoweerC rea% t#e caeat on D''T'

    in t#eHTTP erbs, !"L"T"section elow.

    ?'TC H'ADC PT&;$ an% TRA' met#o%s are %efine% as i%empotent alsoC since t#e are %efine% assafe. Rea% t#e section on safet elow.

    03/26/14 www.RestApiTutorial.com Page 10 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    11/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 thestate 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 orincrementing a web counter. +aing arbitrary &"T re-uests without regard to the context

    of the applications state should therefore be considered safe.

    &n s#ortC safet means t#at calling t#e met#o% %oes not cause si%e effects. onseuentlC clients can

    ma8e safe reuests repeate%l wit#out worr of si%e effects on t#e serer. T#is means t#at serices

    must a%#ere to t#e safet %efinitions of ?'TC H'ADC PT&;$ an% TRA' operations. t#erwiseCesi%es eing confusing to serice consumersC it can cause prolems for "e cac#ingC searc# engines

    an% ot#er automate% agentsma8ing uninten%e% c#anges on t#e serer.

    , %efinitionC safe operations are i%empotentC since t#e pro%uce t#e same result on t#e serer.

    $afe met#o%s are implemente% as rea%+onl operations. HoweerC safet %oes not mean t#at t#e serer

    must return t#e same response eer time.

    HTT) *erbs

    T#e HTTP ers comprise a maEor portion of our Funiform interfaceG constraint an% proi%e us t#eaction counterpart to t#e noun+ase% resource. T#e primar or most+commonl+use% HTTP ers or

    met#o%sC as t#e are properl calle% are P$TC ?'TC P)TC an% D''T'. T#ese correspon% to createC

    rea%C up%ateC an% %elete or R)D operationsC respectiel. T#ere are a numer of ot#er ersC tooCut are utilie% less freuentl. f t#ose less+freuent met#o%sC PT&;$ an% H'AD are use% more

    often t#an ot#ers.

    *+T

    T#e HTTP ?'T met#o% is use% to retriee or rea% a representation of a resource. &n t#e F#appG or

    non+error pat#C ?'T returns a representation in );D or 400 ,AD R'7)'$T.

    '@amplesJ&"T http/00www.example.com0customers012345

    &"T http/00www.example.com0customers0123450orders

    &"T http/00www.example.com0bucets0sampleAccor%ing to t#e %esign of t#e HTTP specificationC ?'T along wit# H'AD reuests are use% onl torea% %ata an% not c#ange it. T#ereforeC w#en use% t#is waC t#e are consi%ere%safe. T#at isC t#e can

    e calle% wit#out ris8 of %ata mo%ification or corruptioncalling it once #as t#e same effect as calling

    it 10 timesC or none at all. A%%itionallC ?'T an% H'AD is i%empotentC w#ic# means t#at ma8ingmultiple i%entical reuests en%s up #aing t#e same result as a single reuest.

    03/26/14 www.RestApiTutorial.com Page 11 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    12/40

    RESTful Service Best Practices

    Do not e@pose unsafe operations ia ?'Tit s#oul% neer mo%if an resources on t#e serer.

    PUT

    P)T is most+often utilie% for up%ate capailitiesC P)T+ing to a 8nown resource )R& wit# t#e reuest

    reuest o% containing t#e newl+up%ate% representation of t#e original resource.

    HoweerC P)T can also e use% to create a resource in t#e case w#ere t#e resource &D is c#osen t#eclient instea% of t#e serer. &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 reuest o% contains a resource representation. -an feel t#is is

    conolute% an% confusing. onseuentlC t#is met#o% of creation s#oul% e use% sparinglC if at all.

    AlternatielC use P$T to create new resources an% proi%e t#e client+%efine% &D in t#e o%representationpresumal to a )R& t#at %oesnBt inclu%e t#e &D of t#e resource seeP'#Telow.

    '@amplesJ

    P6T http/00www.example.com0customers012345

    P6T http/00www.example.com0customers0123450orders0789:5P6T http/00www.example.com0bucets0secret;stuff

    n successful up%ateC return 200 or 204 if not returning an content in t#e o% from a P)T. &f using

    P)T for createC return HTTP status 201 on successful creation. A o% in t#e response is optional

    proi%ing one consumes more an%wi%t#. &t is not necessar to return a lin8 ia a ocation #ea%er int#e creation case since t#e client alrea% set t#e resource &D. $ee t#eReturn aluessection elow.

    P)T is not asafeoperationC in t#at it mo%ifies or creates state on t#e sererC ut 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 e enoug# to %ocument t#at t#e call is notidempotent. HoweerC itBs recommen%e% to 8eep P)T reuests idempotent. &t is strongl

    recommen%e% to use P$T for non+i%empotent reuests.

    P'ST

    T#e P$T er is most+often utilie% for creation of new resources. &n particularC itBs use% to create

    subordinateresources. T#at isC suor%inate to some ot#er e.g. parent resource. &n ot#er wor%sC w#en

    creating a new resourceC P$T to t#e parent an% t#e serice ta8es care of associating t#e new resource

    wit# t#e parentC assigning an &D new resource )R&C etc.

    '@amplesJ

    P'#T http/00www.example.com0customersP'#T http/00www.example.com0customers0123450orders

    n successful creationC return HTTP status 201C returning aLocation#ea%er wit# a lin8 to t#e newl+

    create% resource wit# t#e 201 HTTP status.

    P$T is neit#ersafeor idempotent. &t is t#erefore recommen%e% for non+i%empotent resource reuests.-a8ing two i%entical P$T reuests will most+li8el result in two resources containing t#e same

    03/26/14 www.RestApiTutorial.com Page 12 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    13/40

    RESTful Service Best Practices

    information.

    PUT vs P'ST for Creation

    &n s#ortC faor using P$T for resource creation. t#erwiseC use P)T w#en t#e client is in c#arge of

    %eci%ing w#ic# )R& ia itBs resource name or &D t#e new resource will #aeJ if t#e client 8nows w#att#e resulting )R& or resource &D will eC use P)T at t#at )R&. t#erwiseC use P$T w#en t#e serer

    or serice 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%nBt 8now w#at t#e resulting )R& will e efore creationC use P$T to createt#e new resource.

    ,+L+T+

    D''T' is prett eas to un%erstan%. &t is use% to %elete a resource i%entifie% a )R&.

    '@amplesJ

    !"L"T" http/00www.example.com0customers012345!"L"T" http/00www.example.com0customers0123450orders

    !"L"T" http/00www.example.com0bucets0sample

    n successful %eletionC return HTTP status 200 along wit# a response o%C per#aps t#erepresentation of t#e %elete% item often %eman%s too muc# an%wi%t#C or a wrappe% response see

    Return alueselow. 'it#er t#at or return HTTP status 204 ; ;T';T wit# no response o%.

    &n ot#er wor%sC a 204 status wit# no o%C or t#e =$';D+stle response an% HTTP status 200 are t#erecommen%e% responses.

    HTTP+spec+wiseC D''T' operations are idempotent. &f ou D''T' a resourceC itBs remoe%.

    Repeate%l calling D''T' on t#at resource en%s up t#e sameJ t#e resource is gone. &f calling

    D''T' saC %ecrements a counter wit#in t#e resourceC t#e D''T' call is no longer idempotent.As mentione% preiouslC usage statistics an% measurements ma e up%ate% w#ile still consi%ering t#e

    serice i%empotent as long as no resource %ata is c#ange%. )sing P$T for non+i%empotent resource

    reuests is recommen%e%.

    T#ere is a caeat aout D''T' i%empotenceC #oweer. alling D''T' on a resource a secon% timewill often return a 404 ;T >);D since it was alrea% remoe% an% t#erefore is no longer

    fin%ale. T#is ma8es D''T' operations no longer i%empotentC ut is an appropriate compromise if

    resources are remoe% from t#e %ataase instea% of eing simpl mar8e% as %elete%.

    ,elow is a tale summariing recommen%e% return alues of t#e primar HTTP met#o%s incomination wit# t#e resource )R&sJ

    HTTP Verb /customers /customers/{id}

    ?'T 200 C list of customers. )se paginationC

    sorting an% filtering to naigate ig lists.

    200 C single customer. 404 ;ot

    >oun%C if &D not foun% or inali%.

    P)T 404 ;ot >oun%C unless ou want toup%ate/replace eer resource in t#e entire

    collection.

    200 or 204 ;o ontent. 404;ot >oun%C if &D not foun% or

    inali%.

    03/26/14 www.RestApiTutorial.com Page 13 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    14/40

    RESTful Service Best Practices

    P$T 201 reate%C BocationB #ea%er wit# lin8 to

    /customers/Qi% containing new &D.

    404 ;ot >oun%.

    D''T' 404 ;ot >oun%C unless ou want to %elete t#e

    w#ole collectionnot often %esirale.

    200 . 404 ;ot >oun%C if &D

    not foun% or inali%.

    Resource +amin!

    &n a%%ition to utiliing t#e HTTP ers appropriatelC resource naming is argual t#e most %eate%

    an% most important concept to grasp w#en creating an un%erstan%aleC easil leerage% "e sericeAP&. "#en resources are name% wellC an AP& is intuitie an% eas to use. Done poorlC t#at same AP&

    can feel 8lut an% e %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&.

    'ssentiallC a R'$T>ul AP& en%s up eing simpl a collection of )R&sC HTTP calls to t#ose )R&s an%some =$; an%/or

  • 8/12/2019 RESTful Best Practices-v1_2.odt

    15/40

    RESTful Service Best Practices

    "eso#rce U"I +-amples

    To insert create a new customer in t#e sstemC we mig#t useJP'#T http/00www.example.com0customers

    To rea% a customer wit# ustomer &DS 3324!J&"T http/00www.example.com0customers033245

    T#e same )R& woul% e use% for P)T an% D''T'C to up%ate an% %eleteC respectiel.

    Here are propose% )R&s for pro%uctsJP'#T http/00www.example.com0products

    for creating a new pro%uct.

    &"T

    ne option mig#t eJ

    P'#T http/00www.example.com0ordersAn% t#at coul% wor8 to create an or%erC ut itBs argual outsi%e t#e conte@t of a customer.

    ,ecause we want to create an or%er for a customer note t#e relations#ipC t#is )R& per#aps is not as

    intuitie as it coul% e. &t coul% e argue% t#at t#e following )R& woul% offer etter claritJ

    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

    Proal a list of or%ers t#at customer S3324! #as create% or owns. ;oteJ we ma c#oose to not

    support D''T' or P)T for t#at url since itBs operating on a collection.

    ;owC to continue t#e #ierarc#ical conceptC w#at aout t#e following )R&(P'#T http/00www.example.com0customers0332450orders089:70lineitems

    T#at mig#t a%% a line item to or%er S*69 w#ic# is for customer S3324!. Rig#t ?'T for t#at )R&

    mig#t return all t#e line items for t#at or%er. HoweerC if line items %onBt ma8e sense onl in customerconte@t or also ma8e sense outsi%e t#e conte@t of a customerC we woul% offer aP'#T

    www.example.com0orders089:70lineitems)R&.

    Along t#ose linesC ecause t#ere ma e multiple )R&s for a gien resourceC we mig#t also offer a &"T

    http/00www.example.com0orders089:7)R& t#at supports retrieing an or%er numer wit#out #aingto 8now t#e customer numer.

    To go one laer %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 serices. As wit# eert#ing in t#e craft

    of $oftware DeelopmentC naming is critical to success.

    oo8 at some wi%el use% AP&s to get t#e #ang of t#is an% leerage t#e intuition of our teammates to

    03/26/14 www.RestApiTutorial.com Page 1! of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    16/40

    RESTful Service Best Practices

    refine our AP& resource )R&s. $ome e@ample AP&s areJ

    TwitterJ#ttpsJ//%e.twitter.com/%ocs/api

    >aceoo8J #ttpJ//%eelopers.faceoo8.com/%ocs/reference/api/

    in8e%&nJ #ttpsJ//%eeloper.lin8e%in.com/apis

    "eso#rce $amin! .ntiPatterns

    "#ile weBe %iscusse% some e@amples of appropriate resource namesC sometimes itBs informatie to see

    some anti+patterns. ,elow are some e@amples of poor R'$Tful resource )R&s seen in t#e Fwil%.GT#ese are e@amples of w#at notto %o

    >irst upC often serices use a single )R& to specif t#e serice interfaceC using uer+string parameters

    to specif t#e reueste% operation an%/or HTTP er. >or e@ample to up%ate customer wit# &D 1234!C

    t#e reuest for a =$; o% mig#t eJ

    &"T http/00api.example.com0services=op>update;customer?id>12345?format>@son

    , nowC ouBre aoe %oing t#is. 'en t#oug# t#e BsericesB )R no%e is a nounC t#is )R is not self+%escriptie as t#e )R& #ierarc# is t#e same for all reuests. PlusC it uses ?'T as t#e HTTP er een

    t#oug# weBre performing an up%ate. T#is is counter+intuitie an% is painful een %angerous 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 eil twinJ

    &"T http/00api.example.com0customers0123450update

    OouBll see t#is one a lot as ou isit ot#er %eeloperBs serice suites. ;ote t#at t#e %eeloper is

    attempting to create R'$Tful resource names an% #as ma%e some progress. ,ut ouBre etter t#an t#is

    ale to i%entif t#e er p#rase in t#e )R. ;otice t#at we %onBt nee% to use t#e Bup%ateB er p#rasein t#e )R ecause we can rel on t#e HTTP er to inform t#at operation. =ust to clarifC t#e

    following resource )R is re%un%antJ

    P6T http/00api.example.com0customers0123450update

    "it# ot# P)T an% Bup%ateB in t#e reuestC weBre offering to confuse our serice consumers &s Bup%ateB

    t#e resource( $oC weBe spent some time eating t#e #orse at t#is point. &Bm certain ou un%erstan%...

    Pl#rali/ation

    etBs tal8 aout t#e %eate etween t#e pluraliers an% t#e FsingulariersG... HaenBt #ear% of t#at%eate( &t doese@ist. 'ssentiallC it oils %own to t#is uestion...

    $#oul% )R& no%es in our #ierarc# e name% using singular or plural nouns( >or e@ampleC s#oul%

    our )R& for retrieing 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

    https://dev.twitter.com/docs/apihttps://dev.twitter.com/docs/apihttp://developers.facebook.com/docs/reference/api/https://developer.linkedin.com/apishttp://www.restapitutorial.com/https://dev.twitter.com/docs/apihttp://developers.facebook.com/docs/reference/api/https://developer.linkedin.com/apishttp://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    17/40

    RESTful Service Best Practices

    orJ

    &"T http/00www.example.com0customers033245

    T#ere are goo% arguments on ot# si%esC ut t#e commonl+accepte% practice is to always use pluralsin node namesto 8eep our AP& )R&s consistent across all HTTP met#o%s. T#e reasoning is ase% on

    t#e concept t#at customers are a collection wit#in t#e serice suite an% t#e &D e.g. 3324! refers to one

    of t#ose customers in t#e collection.

    )sing t#is ruleC an e@ample multi+no%e )R& using pluraliation woul% loo8 li8e emp#asis a%%e%J

    &"T http/00www.example.com0customers0332450orders089:70lineitems01

    wit# BcustomersBC Bor%ersBC an% BlineitemsB )R& no%es all eing t#eir plural forms.

    T#is implies t#at ou onl reall nee% two ase )Rs for eac# root resource. ne for creation of t#e

    resource wit#in a collection an% t#e secon% for rea%ingC up%ating an% %eleting t#e resource its

    i%entifier. >or e@ample t#e creation caseC using customers as t#e e@ampleC is #an%le% t#e following)RJ

    P'#T http/00www.example.com0customers

    An% t#e rea%C up%ate an% %elete cases are #an%le% t#e followingJ

    &"T

    Returnin! Reresentations

    As mentione% earlierC it is %esirale for a serice to support multiple representations of resourcesCinclu%ing =$; an%

  • 8/12/2019 RESTful Best Practices-v1_2.odt

    18/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#niueC t#e representation format is specifie% in t#e )R&C en#ancing isiilit. >ore@ampleC &"T http/00www.example.com0customers.xmlwoul% return t#e list of customer representations

    in urt#erC #e states t#at an

    AP& s#oul% e usale an% un%erstan%ale gien an initial )R& wit#out prior 8nowle%ge or out+of+an%information. T#at isC an AP& s#oul% e naigale ia its lin8s to arious components of t#e %ata.

    Returning onl %ata representations is %iscourage%.

    03/26/14 www.RestApiTutorial.com Page 1 of 40

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-drivenhttp://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-drivenhttp://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-drivenhttp://www.restapitutorial.com/http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-drivenhttp://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-drivenhttp://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    19/40

    RESTful Service Best Practices

    T#is practice is not often followe% current in%ustr lea%ers in sericesC reflecting t#at HAT'A$usage is #ig#er on t#e maturit mo%el. oo8ing aroun% at man sericesC conention is to return more

    %ata an% less or no lin8s. T#is is contrar to >iel%ingBs R'$T constraints. >iel%ing sasC F'er

    a%%ressale unit of information carries an a%%ress... 7uer results are represente% a list of lin8s wit#

    summar informationC not arras of oEect representations.Gn t#e ot#er #an%C simpl returning collections of lin8s can e a maEor cause of networ8 c#attiness. &n

    t#e real worl%C %epen%ing on reuirements or use casesC c#attiness of t#e AP& interface is manage%

    alancing #ow muc# FsummarG %ata is inclu%e% along wit# t#e relational #perte@t lin8s in serice

    responses.

    AlsoC full use of HAT'A$ can increase implementation comple@it an% impose a significant ur%en

    on serice clientsC %ecreasing %eeloper pro%uctiit on ot# client an% serer en%s of t#e euation.

    onseuentlC it is imperatie to alance #perlin8ing serice implementations wit# aailale

    %eelopment resources.

    A minimal set of #perlin8ing practices proi%es maEor gains in serice usailitC naigailit an%

    un%erstan%ailit w#ile minimiing %eelopment impact an% re%ucing t#e coupling etween client an%serer. T#ese minimal recommen%ations are resources create% ia P$T an% for collections returne%

    from ?'T reuestsC wit# a%%itional recommen%ations for pagination casesC w#ic# are %escrie% elow.

    Minimal ,in(in! Recommendations

    &n create use casesC t#e )R& lin8 for t#e newl+create% resource s#oul% e returne% in t#eLocationresponse #ea%er an% t#e response o% e emptor contain onl t#e &D of t#e newl+create%

    resource.

    >or collections of representations eing returne% from a sericeC eac# representation s#oul% minimall

    carr a BselfB lin8 propert in its own linscollection. t#er lin8s ma e present in t#e returne% as a

    separate lin8s collection to facilitate paginationC wit# BfirstBC BpreiousBC Bne@tBC BlastB lin8s w#ereapplicale.

    $ee t#e e@amples in t#eLin Dormatsection elow for more information.

    ,in( ormat

    Regar%ing oerall lin8 format stan%ar%s it is recommen%e% to a%#ere to some semlance of t#e AtomC

    AtomPuC or

  • 8/12/2019 RESTful Best Practices-v1_2.odt

    20/40

    RESTful Service Best Practices

    etBs 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#eLocation#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 o% is eit#er emptC or contains a wrappe% response see Crapped Responseselow.

    Here is an e@ample =$; response to a ?'T reuest t#at returns a collection of representations wit#outpagination inole%J

    Adata/JAuser;id/42, name/Kob, links/JArel/self,href/http/00api.example.com0users042BB, Auser;id/22, name/Dran, links/

    JArel/self, href/http/00api.example.com0users022BB, Auser;id/125, name/ #ally,links/JArel/self, href/http/00api.example.com0users0125BBB

    ;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 =$; response to a ?'T reuest t#at returns a collection w#ere pagination isinole% weBre using t#ree items per page an% weBre on t#e t#ir% page of t#e collectionJ

    Adata/JAuser;id/42, name/Kob, lins/JArel/self,

    href/http/00api.example.com0users042BB, Auser;id/22, name/Dran, lins/

    JArel/self, href/http/00api.example.com0users022BB, Auser;id/125, name/ #ally,lins/JArel/self, href/http/00api.example.com0users0125BB, links/JArel/first,

    href/http/00api.example.com0users=offset>E?limit>3B, Arel/last,

    href/http/00api.example.com0users=offset>55?limit>3B, Arel/previous,

    href/http/00api.example.com0users=offset>3?limit>3B, Arel/next,href/http/00api.example.com0users=offset>7?limit>3BB

    &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% e a%%itional lin8s #ere relate% to t#e

    collection ut not relate% to pagination. T#e simple summar isC t#ere are two places to inclu%e lin8s ina collection. >or eac# item in t#e collection t#ose in t#e dataoEectC w#ic# is t#e collection of

    representations reueste%C inclu%e a lin8s collection t#atC minimallC woul% contain a FselfG reference.T#enC in a separate oEectC linsC inclu%e lin8s t#at appl to t#e entire collection as applicaleC suc# aspagination+relate% lin8s.

    >or t#e create use casecreate ia P$TC inclu%e aLocation#ea%er wit# a lin8 to t#e newl+create%

    oEect.

    03/26/14 www.RestApiTutorial.com Page 20 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    21/40

    RESTful Service Best Practices

    2rapped "esponses

    $erices #ae t#e opportunit to return ot# HTTP status co%es along wit# a o% in t#e response. &nman =aa$cript framewor8sC HTTP status response co%es are not returne% to t#e en%+%eeloperC often

    preenting t#e client from %etermining e#aior ase% on t#at status co%e. A%%itionallC wit# t#e

    mria% response co%es in t#e HTTP specC often t#ere are onl a few t#at clients care aoutfreuentloiling %own to BsuccessBC BerrorBC or BfailureB. onseuentlC it is eneficial to wrap responses in a

    representation t#at contains information aout t#e response as well as t#e response itself.

    ne suc# proposal is t#at from mniT& asC t#e so+calle% =$';D response. -ore information can e

    foun% at #ttpJ//las.omniti.com/las/Esen%. Anot#er option is propose% Douglas roc8for% an% cane rea% aout at #ttpJ//www.Eson.org/=$;Reuest.#tml.

    &n practice neit#er of t#ese proposals a%euatel coers all cases. ,asicallC current est practice is to

    wrap regular non+=$;P responses wit# t#e following propertiesJ

    code5 contains t#e HTTP response status co%e as an integer.

    status5 contains t#e te@tJ FsuccessGC FfailGC or FerrorG. "#ere FfailG is for HTTP statusresponse alues from !00+!99C FerrorG is for statuses 400+499C an% FsuccessG is for eert#ing

    else e.g. 1

  • 8/12/2019 RESTful Best Practices-v1_2.odt

    22/40

    RESTful Service Best Practices

    UstatusVerrorU/statusV UmessageVto8en is inali%U/messageV

    U%ata classMIstringIV)naut#orie%'@ceptionU/%ataV

    U/responseV

    Handlin! Cross,omain Iss#es

    "eBe all #ear% aout wor8ing aroun% t#e rowserBs same origin polic or common+source reuirement.

    &n ot#er wor%sC t#e rowser can onl ma8e reuests to t#e site itBs currentl %isplaing. >or e@ampleC ift#e site currentl eing %isplae% is www."xample1.comC t#en t#at site cannot perform a reuest against

    www."xample2.com. iouslC t#is impacts #ow sites access serices.

    PresentlC t#ere are two wi%el+accepte% met#o%s to support cross+%omain reuestsJ =$;P an% ross+

    rigin Resource $#aring R$. =$;P or I=$; wit# pa%%ingI is a usage pattern t#at proi%es amet#o% to reuest %ata from a serer in a %ifferent %omain. &t wor8s t#e serice returning aritrar

    =aa$cript co%e instea% of =$;. T#ese responses are ealuate% t#e =aa$cript interpreterC not

    parse% a =$; parser. R$C on t#e ot#er #an%C is a we rowser tec#nolog specificationC w#ic#%efines was for a we serer to allow its resources to e accesse% a we page from a %ifferent%omain. &t is seen as a mo%ern alternatie to =$;P an% is supporte% all mo%ern rowsers.

    T#ereforeC =$;P is not recommen%e%. #oose R$ w#eneer an% w#ereer possile.

    Suortin! C%RS

    &mplementing R$ on a serer is as simple as sen%ing an a%%itional HTTP #ea%er in t#e responseC for

    e@ampleJ

    Access+ontrol+Allow+riginJ X

    An access origin of BXB s#oul% onl e set if t#e %ata is meant for public consumption. &n most casest#e Access+ontrol+Allow+rigin #ea%er s#oul% specif !ic! domainss#oul% e ale to initiate a

    R$ reuest. nl )Rs t#at nee% to e accesse% cross+%omain s#oul% #ae t#e R$ #ea%er set.

    %ccessF)ontrolF%llowF'rigin/ http/00example.com/8E8E http/00foo.example.com

    Allow onl truste% %omains in Access+ontrol+Allow+rigin #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#eapplication.

    T#ese #ea%ers can e configure% ia t#e "e sererC pro@ or sent from t#e serice itself.

    &mplementing it wit#in t#e serices is not recommen%e% as itBs not fle@ile. &nstea%C use t#e secon%formC a space %elimite% list of appropriate %omains configure% on our "e serer. -ore aout R$can e foun% atJ #ttpJ//enale+cors.org/.

    Suortin! .S%+)

    =$;P gets aroun% t#e rowser limitation utiliing ?'T reuests to perform all serice calls. &n

    03/26/14 www.RestApiTutorial.com Page 22 of 40

    http://enable-cors.org/http://www.restapitutorial.com/http://enable-cors.org/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    23/40

    RESTful Service Best Practices

    essenceC t#e reuester a%%s a uer+string parameter e.g. EsonpMGEsonpLcallac8G to t#e reuestCw#ere t#e alue of t#e FEsonpG parameter is t#e name of a Eaascript function t#at will e calle% w#en

    t#e response is returne%.

    T#ere seere limitations to t#e functionalit enale% =$;PC since ?'T reuests %o not contain a

    reuest o% an%C t#ereforeC information must e passe% ia uer+string parameters. AlsoC to supportP)TC P$T an% D''T' operationsC t#e effectie HTTP met#o% must also e passe% as a uer+string

    argumentC suc# as Lmet#o%MP$T. Tunneling t#e HTTP met#o% li8e t#is is not recommen%e% an% can

    open serices up to securit ris8s.

    =$;P wor8s on legac rowsers w#ic# preclu%e R$ supportC ut affects #ow serices are uilt ift#eBre going to support it. AlternatielC =$;P can e implemente% ia a pro@. erallC =$;P is

    eing %e+emp#asie% in faor of R$. >aor R$ w#eneer possile.

    To support =$;P on t#e serer si%eC w#en t#e =$;P uer+string parameter is passe% inC t#e

    response must e manipulate% a it as followsJ

    1. T#e response o% must e wrappe% as t#e parameter to t#e gien Eaascript function in t#e

    Esonp parameter e.g. EsonpLcallac8FU=$; response o%VG.

    2. Alwas return HTTP status 200 an% return t#e actual status as part of t#e =$; response.

    A%%itionallC itBs also often necessar to inclu%e #ea%ers as part of t#e response o%. T#is enales t#e

    =$;P callac8 met#o% to ma8e %ecisions on response #an%ling ase% on t#e response o% since itBs

    not pri to t#e information in response #ea%ers an% status.

    An e@ample error response following t#e aoe wrappe% response recommen%ations is as followsnoteJ HTTP response status is 200J

    @sonp;callbac$Acode/4E4, status/error,headers/J,message/resource OQ not

    found,data/(otDound"xceptionB*

    A successful creation response loo8s li8e t#is still wit# an HTTP response status of 200J

    @sonp;callbac$Acode/2E1, status/error,headers/JALocation/http/00www.example.com0customers012345B,data/12345B*

    'ueryin!/ ilterin! and )a!ination

    >or large %ata setsC limiting t#e amount of %ata returne% is important from a an%+wi%t# stan%point.

    ,ut itBs also important from a )& processing stan%point as a )& often can onl %ispla a small portion ofa #uge %ata set. &n cases w#ere t#e %ataset grows in%efinitelC itBs #elpful to limit t#e amount of %ata

    returne% %efault. >or instanceC in t#e case of Twitter returning a personBs tweets ia t#eir #ome

    timelineC it returns up to 20 items unless ot#erwise specifie% in t#e reuest an% een t#en will return ama@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 suset nee%s retrieal. T#is is referre% to as pagination

    creating FpagesG of %ataC returning 8nown sections of a larger list an% eing ale to page Fforwar%Gan% Fac8war%G t#roug# t#at large %ata set. A%%itionallC we ma want to specif t#e fiel%s or

    properties of a resource to e inclu%e% in t#e responseC t#ere limiting t#e amount of %ata t#at comes

    03/26/14 www.RestApiTutorial.com Page 23 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    24/40

    RESTful Service Best Practices

    ac8 an% we eentuall want to uer for specific alues an%/ or sort t#e returne% %ata.

    T#ere are cominations of two primar was to limit uer results an% perform pagination. >irstC t#ein%e@ing sc#eme is eit#er page+oriente% or item+oriente%. &n ot#er wor%sC incoming reuests will

    specif w#ere to egin returning %ata wit# eit#er a FpageG numerC specifing a numer of items per

    pageC or specif a first an% last item numer %irectl in a range to return. &n ot#er wor%s t#e twooptions areC Fgie me page ! assuming 20 items per pageG or Fgie me items 100 t#roug# 120.G

    $erice proi%ers are split on #ow t#is s#oul% wor8. HoweerC some )& toolsC suc# as t#e DoEo =$;

    Datastore oEectC c#ooses to mimic t#e HTTP specifications use of te ranges. &tBs er #elpful if our

    serices support t#at rig#t out of t#e o@ so no translation is necessar etween our )& tool8it an%ac8+en% serices.

    T#e recommen%ations elow support ot# t#e DoEo mo%el for paginationC w#ic# is to specif t#e range

    of items eing reueste% using t#eRange#ea%erC an% utiliation of uer+string parameters. ,

    supporting ot#C serices are more fle@ileusale from ot# a%ance% )& tool8itsC li8e DoEoC as wellas simpleC straig#t+forwar% lin8s an% anc#or tags. &t s#oul%nBt a%% muc# comple@it to t#e

    %eelopment effort to support ot# options. HoweerC if our serices %onBt support )& functionalit%irectlC consi%er eliminating support for t#eRange#ea%er option.

    &tBs important to note t#at ueringC filtering an% pagination are not recommen%e% for all serices. T#ise#aior is resource specific an% s#oul% not e supporte% on all resources %efault. Documentation

    for t#e serices an% resources s#oul% mention w#ic# en%+points support t#ese more comple@

    capailities.

    Limitin! "es#lts

    T#e Fgie me items 3 t#roug# !!G wa of reuesting %ata is more consistent wit# #ow t#e HTTP spec

    utilies t#eRange#ea%er for tes so we use t#at metap#or wit# t#e Range #ea%er. HoweerC t#e

    Fstarting wit# item 2 gie 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 uer+string parameters.

    As mentione% aoeC t#e recommen%ation is to support use of ot# t#e HTTPRange#ea%er plus uer+

    string parametersC offsetan% limitC in our serices to limit results in responses. ;ote t#atC gien supportfor ot# optionsC t#e uer+string parameters s#oul% oerri%e t#eRange#ea%er.

    ne of t#e first uestions our going to as8 isC F"# are we supporting two metap#ors wit# t#ese

    similar functions as t#e numers in t#e reuests will neer matc#( &snBt t#at confusing(G )m... T#atBs

    two uestions. "ellC to answer our uestionC it ma e confusing. T#e t#ing isC we want to ma8et#ings in t#e uer+string especiall clearC easil+un%erstoo%C #uman rea%ale an% eas to construct an%

    parse. T#e Range #ea%erC #oweerC is more mac#ine+ase% wit# usage %ictate% to us ia t#e HTTP

    specification.

    &n s#ortC t#e Range #ea%er items alue must e parse%C w#ic# increases t#e comple@itC plus t#e clientsi%e #as to perform some computation in or%er to construct t#e reuest. )sing t#e in%ii%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

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    25/40

    RESTful Service Best Practices

    ,imitin! "ia the Ran!e Header

    "#en a reuest is ma%e for a range of items using a HTTP #ea%er instea% of uer+string parametersCinclu%e aRange#ea%er specifing t#e range as followsJ

    Range/ items>EF24;ote t#at items are ero+ase% to e consistent wit# t#e HTTP specification in #ow it uses t#eRange

    #ea%er to reuest tes. &n ot#er wor%sC t#e first item in t#e %ataset woul% e reueste% a eginning

    range specifier of ero 0. T#e aoe reuest woul% return t#e first 2! itemsC assuming t#ere were atleast 2! items in t#e %ata set.

    n t#e serer si%eC inspect t#eRange#ea%er in t#e reuest to 8now w#ic# items to return. nce a

    Range#ea%er is %etermine% to e@istC it can e simpl parse% using a regular e@pression e.g.

    FitemsMYY%Z+YY%ZG to retriee t#e in%ii%ual range alues.

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

    >or t#e uer+string alternatie to t#e Range #ea%erC use parameter names of offsetan% limitC w#ereoffsetis t#e eginning item numer matc#es t#e first %igit in t#e itemsstring for t#eRange#ea%er

    aoe an% limitis t#e ma@imum numer of items to return. A reuest using uer+string parameters

    t#at matc#es t#e e@ample in t#e Range Hea%er section aoe isJ

    &"T http/00api.example.com0resources=offset=!limit=2"

    T#e offsetalue is ero+ase%C Eust li8e t#e itemsin t#eRange#ea%er. T#e alue for limitis t#ema@imum numer of items to return. $erices can impose t#eir own %efault an% ma@imum alues for

    limit for w#en itBs not specifie% in t#e uer string. ,ut please %ocument t#ose FinisileG settings.

    ;ote t#at w#en t#e uer+string parameters are use%C t#e alues s#oul% oerri%e t#ose proi%e% in t#e

    Range#ea%er.

    Ran!e-Based Resonses

    >or a range+ase% reuestC w#et#er iaRangeHTTP #ea%er or uer+string parametersC t#e serer

    s#oul% respon% wit# a )ontentFRange#ea%er to in%icate #ow man items are eing returne% an% #owman total items e@ist et to e retriee%J

    )ontentFRange/ items EF240::

    ;ote t#at t#e total items aailale e.g. 66 in t#is case is not ero+ase%. HenceC reuesting 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 aailale 66 in t#is casewit# an asteris8 FXG if t#e numer of items is un8nown at response timeC or if t#e calculation of t#at

    numer is too e@pensie. &n t#is case t#e response #ea%er woul% loo8 li8e t#isJ

    )ontentFRange/ items 4EF:50

    HoweerC note t#at DoEo or ot#er )& tools ma not support t#is notation.

    03/26/14 www.RestApiTutorial.com Page 2! of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    26/40

    RESTful Service Best Practices

    Pa!ination

    T#e aoe response+limiting sc#emes wor8s for pagination allowing reuesters to specif t#e itemswit#in a %ataset in w#ic# t#eBre intereste%. )sing t#e aoe e@ample w#ere 66 total items are

    aailaleC retrieing t#e secon% FpageG of %ata using a page sie of 2! woul% use aRange#ea%er as

    followsJ

    Range/ items>25F47

    :ia uer+string parametersC t#is woul% e euialent toJ

    &"T ...=offset=2"!limit=2"

    "#ereuponC t#e serer gien our e@ample woul% return t#e %ataC along wit# a )ontentFRange#ea%er

    as followsJ

    )ontentFRange/ 25F470::

    T#is is wor8s great for most t#ings. HoweerC occasionall t#ere are cases w#ere item numers %onBt

    translate %irectl to rows in t#e %ata set. AlsoC for an e@tremel actie %ata set w#ere new items areregularl 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 numersC sometimes itBs more eneficial an% un%erstan%ale to use an FafterG or FeforeG

    uer+string parameterC optionall in conEunction wit# t#eRange#ea%er or uer+string parametersCoffsetan% limit.

    >or e@ampleC to retriee up to 20 remar8s aroun% a gien timestampJ

    &"T http/00www.example.com0remars0home;timeline=after>Stimestamp

    Range/ items>EF17

    &"T http/00www.example.com0remars0home;timeline=before>StimestampRange/ items>EF17

    'uialentlC using uer+string parametersJ

    &"T http/00www.example.com0remars0home;timeline=after>Stimestamp?offset>E?limit>2E

    &"T http/00www.example.com0remars0home;timeline=before>Stimestamp?offset>E?limit>2E

    >or timestamp formatting an% #an%ling in %ifferent casesC please see t#e!ate Handlingsection elow.

    &f a serice returns a suset of %ata %efault or a ma@imum numer of arguments een w#en t#ereuester %oes not set a Range #ea%erC #ae t#e serer respon% wit# a )ontentFRange#ea%er to

    communicate t#e limit to t#e client. >or e@ampleC in t#e #omeLtimeline e@ample aoeC t#at serice

    call ma onl eer return 20 items at a time w#et#er t#e reuester sets t#e Range #ea%er or not. &n t#at

    caseC t#e serer s#oul% alwas respon% wit# content range #ea%er suc# asJ

    )ontentFRange/ EF1704125

    or )ontentFRange/ EF170

    03/26/14 www.RestApiTutorial.com Page 26 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    27/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 sererCretrieing a suset of %ata an%/or in a specifie% or%er. T#ese concepts wor8 in conEunction wit#

    pagination an% results+limiting an% utilie uer+string parametersCfilteran%sortrespectielC to %o

    t#eir magic.

    AgainC filtering an% sorting are comple@ operations an% %onBt nee% to e supporte% %efault on allresources. Document t#ose resources t#at offer filtering an% sorting.

    ilterin!

    &n t#is caseC filtering is %efine% as re%ucing t#e numer of results returne% specifing some criteriat#at must e met on t#e %ata efore it is returne%. >iltering can get uite comple@ if serices support a

    complete set of comparison operators an% comple@ criteria matc#ing. HoweerC it is uite often

    acceptale to 8eep t#ings sane supporting a simple eualitC Bstarts+wit#B or contains comparison.

    ,efore we get starte% %iscussing w#at goes in t#e filter uer+string parameterC itBs important toun%erstan% w# a single parameter s. multiple uer+string parameters is use%. ,asicallC it comes

    %own to re%ucing t#e possiilit of parameter name clas#es. "eBre alrea% emracing t#e use of offsetC

    limitC an%sortsee elow parameters. T#en t#ereBs@sonpif ou c#oose to support itC t#eformatspecifier an% possil afteran% beforeparameters. An% t#atBs Eust t#e uer+string parameters

    %iscusse% in t!is%ocument. T#e more parameters we use on t#e uer+string t#e more possiilities we

    #ae to #ae name clas#es or oerlap. )sing a single filter parameter minimies t#at.

    PlusC itBs easier from t#e serer+si%e to %etermine if filtering functionalit is reueste% simplc#ec8ing for t#e presence of t#at singlefilterparameter. AlsoC as comple@it of our uering

    reuirements increasesC t#is single parameter option proi%es more fle@iilit in t#e futurefor

    creating our own full+functional uer snta@ see Data comments elow or at

    #ttpJ//www.o%ata.org .

    , emracing a set of commonC accepte% %elimitersC eualit comparison can e implemente% in

    straig#t+forwar% fas#ion. $etting t#e alue of t#e filter uer+string parameter to a string using t#ose

    %elimiters creates a list of name/alue pairs w#ic# can e parse% easil on t#e serer+si%e an% utilie%to en#ance %ataase ueries as nee%e%. T#e %elimiters t#at #ae wor8e% as conentions are t#e ertical

    ar FWG to separate in%ii%ual filter p#rases an% a %oule colon FJJG to separate t#e names an% alues.

    T#is proi%es a uniue+enoug# set of %elimiters to support t#e maEorit of use cases an% creates a user+rea%ale uer+string parameter. A simple e@ample will sere to clarif t#e tec#niue. $uppose we want

    to reuest users wit# t#e name FTo%%G w#o lie in Dener an% #ae t#e title of F?ran% Pooa#G. T#e

    reuest )R&C complete wit# uer+string mig#t loo8 li8e t#isJ

    &"T http/00www.example.com0users=filter>Mname//todd

  • 8/12/2019 RESTful Best Practices-v1_2.odt

    28/40

    RESTful Service Best Practices

    $imple ut effectie. ase sensitiit is certainl up for %eate on a case++case asisC ut in generalCfiltering wor8s est w#en case is ignore%. Oou can also offer wil%+car%s as nee%e% using t#e asteris8

    FXG as t#e alue portion of t#e name/alue pair.

    >or ueries t#at reuire more+t#an simple eualit or wil%+car% comparisonsC intro%uction of operators

    is necessar. &n t#is caseC t#e operators t#emseles s#oul% e part of t#e alue an% parse% on t#e serersi%eC rat#er t#an part of t#e propert name. "#en comple@ uer+language+stle functionalit is

    nee%e%C consi%er intro%ucing uer concept from t#e pen Data Protocol Data >ilter $stem 7uer

    ption specification see #ttpJ//www.o%ata.org/%ocumentation/uri+

    conentionsS>ilter$stem7uerption.

    Sortin!

    >or our purposesC sorting is %efine% as %etermining t#e or%er in w#ic# items in a paloa% are returne%from a serice. &n ot#er wor%sC t#e sort or%er of multiple items in a response paloa%.

    AgainC conention #ere sas to %o somet#ing simple. T#e recommen%e% approac# is to utilie asort

    uer+string parameter t#at contains a %elimite% set of propert names. ,e#aior isC for eac# propertnameC sort in ascen%ing or%erC an% for eac# propert prefi@e% wit# a %as# F+G sort in %escen%ing or%er.$eparate eac# propert name wit# a ertical ar FWGC w#ic# is consistent wit# t#e separation of t#e

    name/alue pairs in filteringC aoe.

    >or e@ampleC if we want to retriee users in or%er of t#eir last name ascen%ingC first name ascen%ing

    an% #ire %ate %escen%ingC t#e reuest mig#t loo8 li8e t#isJ

    &"T http/00www.example.com0users=sort>last;name

  • 8/12/2019 RESTful Best Practices-v1_2.odt

    29/40

    RESTful Service Best Practices

    S#pport Versionin! via Content $e!otiation

    Historicall ersioning was accomplis#e% ia a ersion numer in t#e )R& itselfC wit# clients in%icatingw#ic# ersion of a resource t#e %esire% %irectl in t#e )R& t#e reueste%. &n factC man of t#e Fig

    osG suc# as TwitterC OammerC >aceoo8C ?oogleC etc. freuentl utilie ersion numers in t#eir)R&s. 'en AP& management tools suc# as "$2 #ae re"uiredersion numers in t#e e@pose%)Rs.

    T#is tec#niue flies in t#e face of t#e R'$T constraints as it %oesnBt emrace t#e uilt+in #ea%er sstem

    of t#e HTTP specificationC nor %oes it support t#e i%ea t#at a new )R& s#oul% e a%%e% onl w#en a

    new resource or concept is intro%uce%++not representation c#anges. Anot#er argument against it is t#atresource )R&s arenBt meant to c#ange oer time. A resource is a resource.

    T#e )R& s#oul% e simpl to i%entif t#e resource++not its \s#ape[. Anot#er concept must e use% to

    specif t#e format of t#e response representation. T#at Fot#er conceptG is a pair of HTTP #ea%ersJ

    %cceptan% )ontentFType. T#e%ccept#ea%er allows clients to specif t#e me%ia tpe or tpes of t#eresponse t#e %esire or can support. T#e )ontentFType#ea%er is use% ot# clients an% serers to

    in%icate t#e format of t#e reuest or response o%C respectiel.

    >or e@ampleC to retriee a user in =$; formatJ

    # Request

    ?'T #ttpJ//[email protected]/users/1234!

    AcceptJ application/Eson] ersionM1

    # Response

    HTTP/1.1 200

    ontent+TpeJ application/Eson] ersionM1

    QFi%GJG1234!GC FnameGJG=oe Di-aggioG

    ;owC to retriee ersion 2 of t#at same resource in =$; formatJ

    # Request

    ?'T #ttp J// api .e@ample .com /users /1234!

    AcceptJ application/Eson] ersionM2

    # Response

    HTTP/1.1 200

    ontent+TpeJ application/Eson] ersionM2

    QFi%GJG1234!GC Ffirst;ameGJG=oeGC Flast;ameGJGDi-aggioG

    ;otice #ow t#e )R& is t#e same for ot# ersions as it i%entifies t#e resourceC wit# t#e Accept #ea%er

    eing use% to in%icate t#e format an% ersion in t#is case of t#e %esire% response. AlternatielC if t#e

    03/26/14 www.RestApiTutorial.com Page 29 of 40

    http://api.example.com/users/12345http://www.restapitutorial.com/http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    30/40

    RESTful Service Best Practices

    client %esire% an or e@ampleJ

    # Request

    ?'T #ttp J// api .e@ample .com /users /1234!

    AcceptJ application/Eson] ersionM1C application/@ml] ersionM1

    T#e aoe reuestC assuming t#e serer supports one or ot# of t#e reueste% tpesC will eit#er e in=$; or or e@ampleC t#e response from t#e serer if it faors application0xmlwoul% eJ# Response

    HTTP/1.1 200

    ontent+TpeJ application/@ml] ersionM1

    UuserV

    Ui%V1234!U/i%V

    UnameV=oe Di-aggioU/nameV

    U/userV

    To illustrate t#e use of ontent+Tpe w#en sen%ing %ata to t#e sererC #ere is an e@ample of creating a

    new user using =$; formatJ# Request

    P$T #ttp J// api .e@ample .com /users

    ontent+TpeJ application/Eson] ersionM1

    QFnameGJG-arco PoloG

    rC if ersion 2 was in plaJ

    # Request

    P$T #ttp J// api .e@ample .com /users

    ontent+TpeJ application/Eson] ersionM2

    QFfirst;ameGJG-arcoGC Flast;ameGJGPoloG

    03/26/14 www.RestApiTutorial.com Page 30 of 40

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://api.example.com/users/12345http://api.example.com/usershttp://api.example.com/usershttp://www.restapitutorial.com/http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.htmlhttp://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/users/12345http://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    31/40

    RESTful Service Best Practices

    What "ersion is returned 0hen no "ersion is secified?

    $uppling a ersion on eac# reuest is optional. As HTTP content+negotiation follows a Fest matc#G

    approac# wit# content tpesC so s#oul% our AP&s. )sing t#is Fest 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#erepresentation.

    >or e@ampleC to retriee a user in =$; formatJ

    # Request

    ?'T #ttpJ//[email protected]/users/1234!

    AcceptJ application/Eson

    # Response

    HTTP/1.1 200

    ontent+TpeJ application/Eson] ersionM1

    QFi%GJG1234!GC FnameGJG=oe Di-aggioG

    $imilarlC w#en P$Ting %ata to an en%point t#at supports multiple ersions wit#out a ersionC t#esame rules as aoe appl++t#e lowest/earliest supporte% ersion is e@pecte% in t#e o%. To illustrateC

    #ere is an e@ample of creating a new user on a multi+ersion en%point using =$; format it e@pects

    ersion 1J

    # Request

    P$T #ttp J// api .e@ample .com /users

    ontent+TpeJ application/Eson

    QFnameGJG-arco PoloG

    # Response

    HTTP/1.1 201

    ontent+TpeJ application/Eson] ersionM1

    ocationJ #ttpJ//[email protected]/users/1234!

    QFi%GJG1234!GC FnameGJG-arco PoloG

    1nsuorted *ersions Re2uested

    "#en an unsupporte% ersion numer is reueste%C inclu%ing a resource ersion t#at #as gone t#roug#

    t#e AP& %eprecation lifeccleC t#e AP& s#oul% return an error response wit# 406 ;ot Acceptale HTTP

    status co%e. &n a%%itionC t#e AP& s#oul% return a response o% wit# ontent+TpeJ application/Eson

    03/26/14 www.RestApiTutorial.com Page 31 of 40

    http://api.example.com/usershttp://www.restapitutorial.com/http://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    32/40

    RESTful Service Best Practices

    t#at contains a =$; arra of supporte% content tpes for t#at en%point.

    # Request

    >or e@ampleJ

    ?'T #ttp J// api .e@ample .com /users/1234!

    ontent+TpeJ application/Eson] ersionM###

    # Response

    HTTP/1.1 406 ;T A'PTA,'

    ontent+TpeJ application/Eson

    ^Fapplication/Eson] ersionM1GC Fapplication/Eson] ersionM2GC Fapplication/@ml] ersionM1GC

    Fapplication/@ml] ersionM2G_

    2hen Sho#ld I Create a $e3 Version4&n AP& %eelopment t#ere are man was to rea8 a contract an% negatiel impact our clients. &f ouare uncertain of t#e conseuences of our c#ange it is etter to pla it safe an% consi%er ersioning.

    T#ere are seeral factors to consi%er w#en ou are tring to %eci%e if a new ersion is appropriate or if

    a mo%ification of an e@isting representation is sufficient an% acceptale.

    Chan!es that 0ill brea( contracts

    #anging a propert name ie. FnameG to Ffirst;ameG

    Remoal of propert

    #anging propert %ata tpe numeric to stringC oolean to it/numericC string to %atetimeC etc. :ali%ation rule c#ange

    &n Atom stle lin8sC mo%ifing t#e FrelG alue.

    A reuire% resource is eing 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 tpe te@t/#tml once meant t#at t#e representation woul% e a

    collection of Flin8sG to all supporte% me%ia tpesC new te@t/#tml representation means

    Fwe rowser formG for user input

    An AP& populating an Fen%TimeG on t#e resource F.../users/Qi%/e@ams/Qi%G once

    meant t#e stu%ent sumitte% t#e e@am at t#at timeC t#e new meaning is t#at it will e 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. omining two resources into one an% %eprecating t#e two original resources.

    T#ere are two resourcesC F.../users/Qi%/%ropo@,as8ets/Qi%/messages/Qi%G an%

    F.../users/Qi%/%ropo@,as8ets/Qi%/messages/Qi%/rea%$tatusG. T#e new reuirement is

    03/26/14 www.RestApiTutorial.com Page 32 of 40

    http://api.example.com/usershttp://www.restapitutorial.com/http://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://api.example.com/usershttp://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    33/40

    RESTful Service Best Practices

    to put t#e properties from t#e rea%$tatus resource into t#e in%ii%ual message resource

    an% %eprecate t#e rea%$tatus resource. T#is will cause t#e remoal of a lin8 to t#e

    rea%$tatus resource in t#e in%ii%ual messages resource.

    "#ile t#is list is not full+inclusieC it gies ou an i%ea of t#e tpes of c#anges t#at will cause #aoc for

    our clients an% reuire a new resource or a new ersion.

    Chan!es considered non-brea(in!

    ;ew properties a%%e% to a =$; response.

    ;ew/a%%itional Flin8G to ot#er resources.

    ;ew content+tpe supporte% formats.

    ;ew content+language supporte% formats.

    asing is irreleant as ot# 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%ii%ual resource leel. $ome c#anges to an AP& suc# as

    mo%ifing t#e wor8flow ma reuire ersioning across multiple resource to preent rea8ing clients.

    Use ContentLocation to +nhance "esponses

    ptional. $ee RD> spec.

    Lin0s 3ith ContentTypeAtom+stle lin8s support a BtpeB propert. Proi%e enoug# information so t#at clients can construct

    necessar calls to specific ersion N content tpe.

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

    Ho0 many "ersions should I suort at once?

    $ince maintaining man ersions ecomes cumersomeC comple@C error proneC an% costl ou s#oul%

    support no more t#an 2 ersions for an gien resource.

    Derecated

    T#e term %eprecate% is inten%e% to e use% to communicate t#at a resource is still aailale t#e AP&C

    ut will ecome unaailale an% no longer e@ist in t#e future. Note: The length of time in deprecationwill be determined by the deprecation policy- not yet defined.

    03/26/14 www.RestApiTutorial.com Page 33 of 40

    http://www.restapitutorial.com/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    34/40

    RESTful Service Best Practices

    Ho0 do I inform clients about derecated resources?

    -an clients will e using resources t#at are to e %eprecate% after new ersions are intro%uce% an% in

    %oing soC t#e will nee% was to %iscoer an% monitor t#eir applications use of %eprecate% resources.

    "#en a %eprecate% resource is reueste%C t#e AP& s#oul% return a normal response wit# t#e Pearsoncustom Hea%er FDeprecate%G in a oolean format. ,elow is an e@ample to illustrate.

    # Request

    ?'T #ttpJ//[email protected]/users/1234!

    AcceptJ application/Eson

    ontent+TpeJ application/Eson] ersionM1

    # Response

    HTTP/1.1 200

    ontent+TpeJ application/Eson] ersionM1Deprecate%J true

    QFi%GJG1234!GC FnameGJG=oe Di-aggioG

    Date3Time Handlin!

    Dates an% timestamps can e a real #ea%ac#e if not %ealt wit# appropriatel an% consistentl.Timeone issues can crop up easil an% since %ates are Eust strings in =$; paloa%sC parsing is a real

    issue if t#e format isnBt 8nownC consistent or specifie%.

    &nternallC serices s#oul% storeC processC cac#eC etc. suc# timestamps in )T or ?-T time. T#is

    alleiates timeone issues wit# ot# %ates an% timestamps.

    ,ate5Time Seriali/ation In 6ody Content

    T#ereBs an eas wa aroun% all of t#isalwas use t#e same formatC inclu%ing t#e time portion along

    wit# timeone information in t#e string. &$ 601 time point format is a goo% solutionC using t#efull+en#ance% format t#at inclu%es #oursC minutesC secon%s an% a %ecimal fraction of secon%s e.g.

    +--+%%BTBHHJmmJss.$$$B`B. &t is recommen%e% t#at &$ 601 e use% for all %ates represente%

    in R'$T serice o% content ot# reuests an% responses.

    &nci%entallC for t#ose %oing =aa+ase% sericesC t#e DateA%apter= lirar easil parses an% formats

    &$601 %ates an% time points an% HTTP 1.1 #ea%er R> 1123 formatsC wit# its DateA%apterC&so601TimepointA%apter an% HttpHea%erTimestampA%apter implementation classesC respectiel. &t

    can e %ownloa%e% at #ttpsJ//git#u.com/tfre%ric#/DateA%apter=.

    >or t#ose creating rowser+ase% )&sC t#e '-A$cript ! specification inclu%es parsing an% creating&$601 %ates in =aa$cript natielC so it s#oul% e ma8ing its wa into all mainstream rowsers as

    we spea8. &f ouBre supporting ol%er rowsers t#at %onBt natiel parse t#ose %atesC a =aa$cript lirar

    or fanc regular e@pression is in or%er. A couple of sample =aa$cript liraries t#at can parse an%

    03/26/14 www.RestApiTutorial.com Page 34 of 40

    https://github.com/tfredrich/DateAdapterJhttp://www.restapitutorial.com/https://github.com/tfredrich/DateAdapterJhttp://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    35/40

    RESTful Service Best Practices

    pro%uce &$601 Timepoints areJ

    #ttpJ//momentEs.com/

    #ttpJ//www.%ateEs.com/

    ,ate5Time Seriali/ation In HTTP Headers

    "#ile t#e aoe recommen%ation wor8s for =$; an% 22 w#ic# was up%ate% R> 1123C t#at format inclu%es arious %ateC time an% %ate+time

    formats. HoweerC it is recommen%e% to alwas use a timestamp formatC w#ic# en%s up loo8ing li8e

    t#is in our reuest #ea%ersJ

    $unC 06 ;o 1994 0J49J3* ?-T

    )nfortunatelC it %oesnBt account for a millisecon% or %ecimal fraction of a secon% in its format. T#e

    =aa $impleDate>ormat specifier string isJ I'''C %% --- HHJmmJss B?-TBI

    Securin! Ser"ices

    Aut#entication is t#e act of erifing t#at a gien reuest is from someone or some sstem t#at is8nown to t#e serice an% t#at t#e reuestor is w#o t#e sa t#e are. "#ile aut#entication is t#e act of

    erifing a reuestor is w#o t#e sa t#e areC aut#oriation is erifing t#e reuestor #as permission to

    perform t#e reueste% operation.

    'ssentiallC t#e process goes somet#ing li8e t#isJ

    1. lient ma8es a reuestC inclu%ing aut#entication to8en inOF%uthoriNation#ea%er or toenuer+string parameter in t#e reuest.

    2. $erice erifies presence of t#e aut#oriation to8enC ali%ates it t#at itBs ali% an% not e@pire%

    an% parses or loa%s t#e aut#entication principal ase% on t#e to8en contents.

    3. $erice ma8es a call to t#e aut#oriation serice proi%ing aut#entication principalC reueste%

    resource an% reuire% permission for operation.

    4. &f aut#orie%C serice continues wit# normal processing.

    S3 aoe coul% e e@pensieC ut assuming a cac#eale access+control list AC it is conceiale to

    create an aut#oriation client t#at cac#es t#e most+recent As to ali%ate locall efore ma8ing

    remote calls.

    .#thenticationurrent est practice is to use Aut# for aut#entication. Aut#2 is #ig#l recommen%e%C ut is still in

    %raft state. Aut#1 is %efinitel an acceptale alternatie. 3+egge% Aut# is also an option for certaincases. Rea% more aout t#e Aut# specification at #ttpJ//oaut#.net/%ocumentation/spec/.

    pen&D is an a%%itional option. HoweerC it is recommen%e% t#at pen&D e use% as an additional

    aut#entication optionC leeraging Aut# as primar. Rea% more aout t#e pen&D specification at

    03/26/14 www.RestApiTutorial.com Page 3! of 40

    http://momentjs.com/http://www.datejs.com/http://oauth.net/documentation/spec/http://www.restapitutorial.com/http://momentjs.com/http://www.datejs.com/http://oauth.net/documentation/spec/http://www.restapitutorial.com/
  • 8/12/2019 RESTful Best Practices-v1_2.odt

    36/40

    RESTful Service Best Practices

    #ttpJ//openi%.net/%eelopers/specs/.

    Transport Sec#rity

    All aut#entication s#oul% use $$. Aut#2 reuires t#e aut#oriation serer an% a


Recommended