SlideShare ist ein Scribd-Unternehmen logo
1 von 62
DESIGNING
A RESTFUL WEB SERVICE
INTRODUCTION
XML over HTTP
Pretty URLs


                REST ?

      Any web service that’s not SOAP
THEORY
• REpresentational   State Transfer

• Defined   in 2000 by Roy Fielding in his doctoral dissertation
 ‘Architectural Styles and the Design of Network-based Software
 Architectures’

• Architectural   style for network-based software applications

    • not   a protocol, unlike SOAP

    • implementations    use standards like HTTP, URI, XML, etc
RESOURCES

• What   your web service is all about ≈ domain entities

                     Order, Customer, ...

• Nouns, not Verbs

• Identified   by a URI
BEHAVIOR

POST = Create

GET = Read

PUT = Update ... and Create

DELETE = Delete
BEHAVIOR
• Safe   = no side effects

• Idempotent    = multiple requests same effect as single request

                     GET        POST         PUT        DELETE

     SAFE             Y           N           N           N

IDEMPOTENT            Y           N           Y            Y

              DON’T abuse GET for unsafe operations
REPRESENTATION

• Client   and server exchange representations of a resource
• HTTP       headers provide info about chosen representation
  •   Content-Type:   media type of representation
  •   Content-Length: size   of representation in bytes
  •   Content-Encoding: for   compressing representations
  •   Content-Language: for   localized representations
BASIC DESIGN

1. IDENTIFYING RESOURCES

2. CHOOSING REPRESENTATION

3. RESPONSES

4. HANDLING ERRORS
IDENTIFYING RESOURCES
IDENTIFYING RESOURCES

                             Asset



/assets                        /assets/{id}

GET = retrieve all assets      GET = retrieve asset details
PUT = update all assets        PUT = update asset
POST = add a new asset         POST = -
DELETE = delete all assets     DELETE = remove asset
IDENTIFYING RESOURCES

               Asset                                 Attachment
                                           0 ... *




/assets/{id}/attachments

GET = retrieve all attachments of asset
PUT = update all attachments of asset
POST = create a new attachment
DELETE = delete all attachments of asset
IDENTIFYING RESOURCES

              Asset                                 Attachment
                                          0 ... *




/assets/{id}/attachments/{role}

GET = retrieve attachment with given role
PUT = replace or create attachment with given role
POST = -
DELETE = delete attachment with given role
IDENTIFYING RESOURCES

                            0 ... *
                                                       links

                              Asset
                                          1




/assets/{id}/links                    /assets/{id}/links/{id}

GET = retrieve all links              GET = check if link exists
PUT = replace all links               PUT = create link
POST = add links                      POST = -
DELETE = remove all links             DELETE = remove link
IDENTIFYING RESOURCES
• We   only need two URIs:
 • one   for a collection resource
 • one   for an instance resource
• Use-case   scalability
 • which   resources will be added in the future ?
CHOOSING REPRESENTATION
CHOOSING REPRESENTATION
• No    single format for all representations

  • varying   application use cases and client needs

• XML (application/xml)      and JSON (application/json) most
 used

• Alternative   formats for special cases

  •   image/jpeg, image/png, application/pdf,
      application/vnd.ms-excel, text/plain, text/csv, ...
CHOOSING REPRESENTATION
• Sometimes     need for combination of textual and binary data

  • e.g. XML   and image data

• Possible   with multipart media types

  •   multipart/form-data   most used

• Content-Disposition           header for giving extra info

• DON’T       encode binary data using Base64 encoding
CHOOSING REPRESENTATION
Content-Type: multipart/form-data; boundary=“abcd”
--abcd
Content-Type: application/xml
Content-Disposition: form-data; name=asset
<asset>
  <name>New asset</name>
  ...
</asset>
--abcd
Content-Type: image/jpeg
Content-Disposition: form-data; name=binary; filename=newasset.jpg
... image here ...
--abcd
CHOOSING REPRESENTATION
• Media     type extensions
 • XML       based types end with +xml
 • for     vendor specific extensions the subtype starts with vnd.
• Examples

 •   application/atom+xml

 •   application/vnd.google-earth.kml+xml

 •   application/vnd.diocontent+xml

 •   ...
RESPONSES
RESPONSES

GET is obvious:

    # Request
    GET /assets/1234 HTTP/1.1
    # Response
    HTTP/1.1 200 OK
    Content-Type: application/xml
    <asset>
      <name>image.jpg</name>
      ...
    </asset>
RESPONSES

POST not so obvious:
    # Request
    POST /assets HTTP/1.1
    Content-Type: multipart/form-data; boundary=“abcd”
    ...

    # Response
    HTTP/1.1 201 Created
    Location: http://diocontent.persgroep.be/assets/1234
    Content-Type: application/xml
    <asset id=“1234”>
      <name>image.jpg</name>
      ...
    </asset>
RESPONSES

PUT for update:

    # Request
    PUT /assets/1234 HTTP/1.1
    Content-Type: application/xml
    <asset id=“1234”>
      <name>updated name</name>
      ...
    </asset>
    # Response
    HTTP/1.1 200 OK
    Content-Type: application/xml
    <asset id=“1234”>
      <name>updated name</name>
      ...
    </asset>
RESPONSES

DELETE



   # Request
   DELETE /assets/1234 HTTP/1.1
   # Response
   HTTP/1.1 204 No Content
HANDLING ERRORS
HANDLING ERRORS
• Return    response with a 4xx status code for client errors

• Indicate   server-side errors with a 5xx status code

• DON’T        use a success status code, i.e. 2xx

• Include    message in body with more information
              DON’T                                   DO
   HTTP/1.1 200 OK                       HTTP/1.1 404 Not Found
   Content-Type: application/xml         Content-Type: application/xml
   <error>                               <error>
    Asset ‘1234’ not found                Asset ‘1234’ not found
   </error>                              </error>
HANDLING ERRORS
•   400 Bad Request
    •   the request cannot be fulfilled due to bad syntax
•   401 Unauthorized
    •   authentication is required but has failed or has not yet been provided
•   403 Forbidden
    •   request was valid but server is refusing to respond to it
•   404 Not Found
    •   requested resource could not be found but may be available again in the future
•   405 Method Not Allowed
    •   request was made using a method not supported by the resource
•   406 Not Acceptable
    •   cannot generate representation indicated by Accept headers of request
•   409 Conflict
    •   request could not be processed because of conflict in the request
HANDLING ERRORS
•   500 Internal Server Error

    •   best code to return when server fails due to some implementation bug

•   503 Service Unavailable

    •   the server is currently unavailable (because it is overloaded or down for
        maintenance). Generally, this is a temporary state
ADVANCED DESIGN
1. CONTENT NEGOTIATION

2. QUERYING

3. BASE WEB SERVICE URL

4. SECURITY

5. EXTENSIBILITY AND VERSIONING

6. ASYNCHRONOUS TASKS

7. HATEOAS

8. ENABLING DISCOVERY
CONTENT NEGOTIATION
CONTENT NEGOTIATION
• Let   client choose representation as much as possible

• Different   mechanisms

  • Accept-*   headers

  • query   parameters

  • extensions

• Use   response code 406 (Not Acceptable) for failures
CONTENT NEGOTIATION
• Accept    for preferred media type(s)

• Accept-Language         for preferred language(s)

• Accept-Encoding        when client can handle (de)compre

•q   parameter indicates relative preference

 • floating-point   number in a range of 0.0 to 1.0 (default)
CONTENT NEGOTIATION

     # Request headers
     Accept: application/xml, application/json;q=0.5, */*;q=0.0
     Accept-Language: nl, en-gb;q=0.8, en;q=0.7, *;q=0.1
     Accept-Encoding: gzip



• XML   is preferred media type, JSON is second choice, anything
  else not acceptable

• ‘nl’ first   choice, ‘en-gb’ second, ‘en’ third choice

• gzip   compression is supported
CONTENT NEGOTIATION
• Query   parameter like type, lang

   GET /assets/1234?type=json&lang=fr HTTP/1.1


• Resource   extension
   GET /assets/1234.json HTTP/1.1


• Conventionally   override Accept header
QUERYING
QUERYING
• GET   on collection resource with query parameters
  # Request
  GET /assets?q=obama&sortbyAsc=createDate HTTP/1.1
  # Response
  HTTP/1.1 200 OK
  Content-Type: application/xml
  <assets>
    <asset id=“1234”>...</asset>
    <asset id=“4567”>...</asset>
    ...
  </assets>


• POST   for large queries exceeding maximum length of URI
  # Request
  POST /assets HTTP/1.1
  Content-Type: application/x-www-form-urlencoded
  q=obama&sortbyAsc=createDate
QUERYING
• Pagination
  # Request
  GET /assets?q=obama&sortbyAsc=createDate&offset=50&limit=25 HTTP/1.1


• Letting   clients decide what they want
  # Request
  GET /assets?q=SELECT NAME FROM IMAGES WHERE FULLTEXT='obama'
  # Response
  HTTP/1.1 200 OK
  Content-Type: application/xml
  <results>
    <assetResult>
        <attribute name="NAME">obama001.jpg</attribute>
    </assetResult>
    <assetResult>
        <attribute name="NAME">obama002.jpg</attribute>
    </assetResult>
    ...
  </results>
QUERYING
• Storing   queries
  # Request
  POST /assets HTTP/1.1
  Content-Type: application/x-www-form-urlencoded
  q=obama&sortbyAsc=createDate
  # Response
  HTTP/1.1 201 Created
  Content-Type: application/xml
  Location: http://diocontent.persgroep.be/searches/1
  # Use the created resource to fetch query results
  GET /searches/1 HTTP/1.1
  # Response
  HTTP/1.1 200 OK
  Content-Type: application/xml
  <assets>
    ...
  </assets>
  # ... and with pagination
  GET /searches/1?offset=50&limit=25 HTTP/1.1
BASE WEB SERVICE URL
BASE WEB SERVICE URL
• Dedicated   URL

• Same    URL for browser and REST client

 • only   different representations: HTML vs XML/JSON

               http://diocontent.persgroep.be
                               vs.
         http://diocontentwebservice.persgroep.be
SECURITY
SECURITY
• REST   is stateless so DON’T use HTTP sessions

• Different   protocols

  • Basic

  • Oauth

• Add   authentication from the start !
EXTENSIBILITY
AND VERSIONING
EXTENSIBILITY
•   Preserve backwards compatibility !

•   Use HTTP redirects

    •   301 Moved Permanently

        •   this and all future requests should be directed to the given URI

    •   304 Temporary Redirect

        •   request should be repeated with another URI, using same method

    •   410 Gone

        •   when resource used to exist, but it does not anymore
VERSIONING


• Don’t   introduce a version unless you have breaking changes

• URL: http://diocontentwebservice.persgroep.be/v2

• Media   type: application/vnd.diocontent+xml;v=2
ASYNCHRONOUS TASKS
ASYNCHRONOUS TASKS
• Creating   assets in dio:content is an asynchronous operation

• Each   new asset is placed on a queue as a check-in
ASYNCHRONOUS TASKS
# Adding new asset
POST /assets HTTP/1.1
Content-Type: multipart/form-data; boundary=“abcd”
--abcd
Content-Type: application/xml
...
--abcd
Content-Type: image/jpeg
...
--abcd
# Response
HTTP/1.1 202 Accepted
Content-Type: application/xml
Content-Location: http://diocontent.persgroep.be/checkins/1
<checkIn id=“1”>
  <state>PENDING</state>
  <created>2012-02-01T18:20:10.000</created>
</checkIn>
ASYNCHRONOUS TASKS
# Checking status of check-in
GET /checkins/1 HTTP/1.1
# Processing asset
HTTP/1.1 200 OK
Content-Type: application/xml
<checkIn id=“1”>
  <state>PROCESSING</state>
  <created>2012-02-01T12:00:00.000</created>
  <processingStarted>2012-02-01T12:00:10.000</processingStarted>
</checkIn>
# Asset successfully added
HTTP/1.1 303 See Other
Content-Type: application/xml
Location: http://diocontent.persgroep.be/assets/1234
Content-Location: http://diocontent.persgroep.be/checkins/1
<checkIn id=“1”>
  <state>DONE</state>
  <created>2012-02-01T18:20:10.000</created>
  <processingStarted>2012-02-01T12:00:10.000</processingStarted>
  <completed>2012-02-01T12:00:10.000</completed>
  <assetId>1234</assetId>
</checkIn>
ASYNCHRONOUS TASKS
# Canceling check-in
DELETE /checkins/1 HTTP/1.1
# check-in canceled
HTTP/1.1 204 No Content



# Already completed check-in cannot be canceled
HTTP/1.1 409 Conflict
Content-Type: application/xml;charset=utf-8
Location: http://diocontent.persgroep.be/assets/1234
Content-Location: http://diocontent.persgroep.be/checkins/1
<checkIn id=“1”>
  <state>DONE</state>
  <created>2012-02-01T18:20:10.000</created>
  <processingStarted>2012-02-01T12:00:10.000</processingStarted>
  <completed>2012-02-01T12:00:10.000</completed>
  <assetId>1234</assetId>
</checkIn>
HATEOAS
HATEOAS
        Hypermedia As The Engine Of Application State
• Use   links to allow clients to discover locations and operations

• Clients   do not need to known URLs, so they can change

• The   entire application workflow is abstracted, thus changeable

• The   hypermedia type itself could be versioned if necessary

• No    breaking of clients if the implementation is updated !
HATEOAS
# Request
GET /assets?q=SELECT NAME FROM IMAGES WHERE FULLTEXT=‘obama’&limit=50 HTTP/1.1
Accept: application/vnd.diocontent+xml
# Response
HTTP/1.1 200 OK
Content-Type: application/vnd.diocontent+xml
<?xml version=“1.0” encoding=“utf-8” ?>
<results xmlns=“http://diocontentapi.persgroep.be/schema/api”
     xmlns:atom=“http://www.w3.org/2005/Atom”>
  <assetResult>
   <attribute name="NAME">obama001.jpg</attribute>
   <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234”/>
  </assetResult>
  <assetResult>
   <attribute name="NAME">obama002.jpg</attribute>
   <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/4567”/>
  </assetResult>
  ...
  <atom:link rel=“first”
     href=“http://diocontent.persgroep.be/assets?q=...&offset=0&limit=50”/>
  <atom:link rel=“next”
     href=“http://diocontent.persgroep.be/assets?q=...&offset=50&limit=50”/>
  <atom:link rel=“last”
     href=“http://diocontent.persgroep.be/assets?q=...&offset=800&limit=50”/>
</results>
HATEOAS
# Request
GET /assets/1234 HTTP/1.1
Accept: application/vnd.diocontent+xml
# Response
HTTP/1.1 200 OK
Content-Type: application/vnd.diocontent+xml
<?xml version=“1.0” encoding=“utf-8” ?>
<asset id=“123” xmlns=“http://diocontentapi.persgroep.be/schema/api”
    xmlns:atom=“http://www.w3.org/2005/Atom”>
  <name>image.jpg</name>
  <createDate>2012-02-01T18:20:10.000</createDate>
  ...
  <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234”/>
  <atom:link rel=“alternate” href=“http://diocontent.persgroep.be/assets/1234”
         type=“image/jpeg”/>
  <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234/attachments”/>
  <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234/links”/>
</asset>
HATEOAS
# Request
GET /assets/1234/attachments HTTP/1.1
Accept: application/vnd.diocontent+xml
# Response
HTTP/1.1 200 OK
Content-Type: application/vnd.diocontent+xml
<?xml version=“1.0” encoding=“utf-8” ?>
<attachments id=“123” xmlns=“http://diocontentapi.persgroep.be/schema/api”
    xmlns:atom=“http://www.w3.org/2005/Atom”>
 <attachment>
  <role>original</role>
  ...
  <atom:link rel=“self”
      href=“http://diocontent.persgroep.be/assets/1234/attachments/original”/>
  <atom:link rel=“alternate” type=“image/jpeg”
      href=“http://diocontent.persgroep.be/assets/1234/attachments/original”/>
 </attachment>
 ...
 <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234/attachments”/>
 <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234”/>
</attachments>
HATEOAS



Without HATEOAS, your HTTP interface is not RESTful !
ENABLING DISCOVERY
ENABLING DISCOVERY
• Please   document your REST API !

  • describe   resources, methods, media types, authentication, ...

  • provide   XML schema’s when using XML representations

  • http://diocontentwebservice.persgroep.be

• Implement    OPTIONS method to list supported methods
   # Request
   OPTIONS /asset/1234 HTTP/1.1
   # Response
   HTTP/1.1 204 No Content
   Allow: GET, PUT, DELETE, HEAD, OPTIONS
THE END ... QUESTIONS ?
BOOKS ON REST


•   Subbu Allamaraju RESTful Web Services Cookbook ISBN:
    978-0596801687

•   Leonard Richardson, Sam Ruby RESTful Web Services ISBN:
    978-0596529260
FURTHER READING
•   RyanTomayko
    How I Explained REST to my Wife
    http://tomayko.com/writings/rest-to-my-wife

•   Jim Webber, Savas Parastatidis & Ian Robinson
    How to GET a Cup of Coffee
    http://www.infoq.com/articles/webber-rest-workflow

•   Roy Thomas Fielding
    Architectural Styles and the Design of Network-based Software
    Architectures
    http://www.ics.uci.edu/~fielding/pubs/disser tation/top.htm

Weitere ähnliche Inhalte

Was ist angesagt?

Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webserviceDong Ngoc
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSKatrien Verbert
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Hadoop introduction
Hadoop introductionHadoop introduction
Hadoop introductionDong Ngoc
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEREST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEreneechemel
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)Jef Claes
 
Restful web services by Sreeni Inturi
Restful web services by Sreeni InturiRestful web services by Sreeni Inturi
Restful web services by Sreeni InturiSreeni I
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API RecommendationsJeelani Shaik
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionseyelliando dias
 
HTTP protocol and Streams Security
HTTP protocol and Streams SecurityHTTP protocol and Streams Security
HTTP protocol and Streams SecurityBlueinfy Solutions
 

Was ist angesagt? (20)

Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
 
L18 REST API Design
L18 REST API DesignL18 REST API Design
L18 REST API Design
 
SOAP-based Web Services
SOAP-based Web ServicesSOAP-based Web Services
SOAP-based Web Services
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Web Services
Web ServicesWeb Services
Web Services
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Hadoop introduction
Hadoop introductionHadoop introduction
Hadoop introduction
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEREST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
Web service introduction
Web service introductionWeb service introduction
Web service introduction
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)REST and ASP.NET Web API (Milan)
REST and ASP.NET Web API (Milan)
 
Restful web services by Sreeni Inturi
Restful web services by Sreeni InturiRestful web services by Sreeni Inturi
Restful web services by Sreeni Inturi
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
REST API Design
REST API DesignREST API Design
REST API Design
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
 
OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
HTTP protocol and Streams Security
HTTP protocol and Streams SecurityHTTP protocol and Streams Security
HTTP protocol and Streams Security
 

Andere mochten auch

RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...
RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...
RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...Weijun Qin
 
Restful Web Service
Restful Web ServiceRestful Web Service
Restful Web ServiceBin Cai
 
Secure RESTful Web Services for ASP.NET Web API
Secure RESTful Web Services for ASP.NET Web APISecure RESTful Web Services for ASP.NET Web API
Secure RESTful Web Services for ASP.NET Web APIRob Daigneau
 
Rest presentation
Rest  presentationRest  presentation
Rest presentationsrividhyau
 
Ultimate Guide to 30+ API Documentation Solutions
Ultimate Guide to 30+ API Documentation SolutionsUltimate Guide to 30+ API Documentation Solutions
Ultimate Guide to 30+ API Documentation SolutionsBill Doerrfeld
 
Modularizing RESTful Web Service Management with Aspect Oriented Programming
Modularizing RESTful Web Service Management with Aspect Oriented ProgrammingModularizing RESTful Web Service Management with Aspect Oriented Programming
Modularizing RESTful Web Service Management with Aspect Oriented ProgrammingWidhian Bramantya
 
Web api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunalWeb api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunalKrunal Trivedi
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web ServicesBruno Pedro
 

Andere mochten auch (12)

RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...
RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...
RestThing: A Restful Web Service Infrastructure for Mash-up Physical and Web ...
 
Web Api vs MVC
Web Api vs MVCWeb Api vs MVC
Web Api vs MVC
 
Restful Web Service
Restful Web ServiceRestful Web Service
Restful Web Service
 
Rest application
Rest applicationRest application
Rest application
 
Implementation advantages of rest
Implementation advantages of restImplementation advantages of rest
Implementation advantages of rest
 
End to End Security with MVC and Web API
End to End Security with MVC and Web APIEnd to End Security with MVC and Web API
End to End Security with MVC and Web API
 
Secure RESTful Web Services for ASP.NET Web API
Secure RESTful Web Services for ASP.NET Web APISecure RESTful Web Services for ASP.NET Web API
Secure RESTful Web Services for ASP.NET Web API
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
 
Ultimate Guide to 30+ API Documentation Solutions
Ultimate Guide to 30+ API Documentation SolutionsUltimate Guide to 30+ API Documentation Solutions
Ultimate Guide to 30+ API Documentation Solutions
 
Modularizing RESTful Web Service Management with Aspect Oriented Programming
Modularizing RESTful Web Service Management with Aspect Oriented ProgrammingModularizing RESTful Web Service Management with Aspect Oriented Programming
Modularizing RESTful Web Service Management with Aspect Oriented Programming
 
Web api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunalWeb api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunal
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web Services
 

Ähnlich wie Designing a RESTful web service

Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
RESTful for opentravel.org by HP
RESTful for opentravel.org by HPRESTful for opentravel.org by HP
RESTful for opentravel.org by HPRoni Schuetz
 
OpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML ResourcesOpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML ResourcesOpenTravel Alliance
 
Webservices Workshop - september 2014
Webservices Workshop -  september 2014Webservices Workshop -  september 2014
Webservices Workshop - september 2014clairvoyantllc
 
WordPress APIs
WordPress APIsWordPress APIs
WordPress APIsmdawaffe
 
RESTFul Tools For Lazy Experts - CFSummit 2016
RESTFul Tools For Lazy Experts - CFSummit 2016RESTFul Tools For Lazy Experts - CFSummit 2016
RESTFul Tools For Lazy Experts - CFSummit 2016Ortus Solutions, Corp
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...Lviv Startup Club
 
JavaOne 2014 - Supporting Multi-tenancy Applications with Java EE
JavaOne 2014 - Supporting Multi-tenancy Applications with Java EEJavaOne 2014 - Supporting Multi-tenancy Applications with Java EE
JavaOne 2014 - Supporting Multi-tenancy Applications with Java EERodrigo Cândido da Silva
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 
Embracing HTTP in the era of API’s
Embracing HTTP in the era of API’sEmbracing HTTP in the era of API’s
Embracing HTTP in the era of API’sVisug
 

Ähnlich wie Designing a RESTful web service (20)

Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
RESTful for opentravel.org by HP
RESTful for opentravel.org by HPRESTful for opentravel.org by HP
RESTful for opentravel.org by HP
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
OpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML ResourcesOpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML Resources
 
Webservices Workshop - september 2014
Webservices Workshop -  september 2014Webservices Workshop -  september 2014
Webservices Workshop - september 2014
 
WordPress APIs
WordPress APIsWordPress APIs
WordPress APIs
 
Rest ful tools for lazy experts
Rest ful tools for lazy expertsRest ful tools for lazy experts
Rest ful tools for lazy experts
 
RESTFul Tools For Lazy Experts - CFSummit 2016
RESTFul Tools For Lazy Experts - CFSummit 2016RESTFul Tools For Lazy Experts - CFSummit 2016
RESTFul Tools For Lazy Experts - CFSummit 2016
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Web services
Web servicesWeb services
Web services
 
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Rest web services
Rest web servicesRest web services
Rest web services
 
JavaOne 2014 - Supporting Multi-tenancy Applications with Java EE
JavaOne 2014 - Supporting Multi-tenancy Applications with Java EEJavaOne 2014 - Supporting Multi-tenancy Applications with Java EE
JavaOne 2014 - Supporting Multi-tenancy Applications with Java EE
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
Embracing HTTP in the era of API’s
Embracing HTTP in the era of API’sEmbracing HTTP in the era of API’s
Embracing HTTP in the era of API’s
 

Kürzlich hochgeladen

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Kürzlich hochgeladen (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Designing a RESTful web service

  • 3. XML over HTTP Pretty URLs REST ? Any web service that’s not SOAP
  • 4. THEORY • REpresentational State Transfer • Defined in 2000 by Roy Fielding in his doctoral dissertation ‘Architectural Styles and the Design of Network-based Software Architectures’ • Architectural style for network-based software applications • not a protocol, unlike SOAP • implementations use standards like HTTP, URI, XML, etc
  • 5. RESOURCES • What your web service is all about ≈ domain entities Order, Customer, ... • Nouns, not Verbs • Identified by a URI
  • 6. BEHAVIOR POST = Create GET = Read PUT = Update ... and Create DELETE = Delete
  • 7. BEHAVIOR • Safe = no side effects • Idempotent = multiple requests same effect as single request GET POST PUT DELETE SAFE Y N N N IDEMPOTENT Y N Y Y DON’T abuse GET for unsafe operations
  • 8. REPRESENTATION • Client and server exchange representations of a resource • HTTP headers provide info about chosen representation • Content-Type: media type of representation • Content-Length: size of representation in bytes • Content-Encoding: for compressing representations • Content-Language: for localized representations
  • 9. BASIC DESIGN 1. IDENTIFYING RESOURCES 2. CHOOSING REPRESENTATION 3. RESPONSES 4. HANDLING ERRORS
  • 11. IDENTIFYING RESOURCES Asset /assets /assets/{id} GET = retrieve all assets GET = retrieve asset details PUT = update all assets PUT = update asset POST = add a new asset POST = - DELETE = delete all assets DELETE = remove asset
  • 12. IDENTIFYING RESOURCES Asset Attachment 0 ... * /assets/{id}/attachments GET = retrieve all attachments of asset PUT = update all attachments of asset POST = create a new attachment DELETE = delete all attachments of asset
  • 13. IDENTIFYING RESOURCES Asset Attachment 0 ... * /assets/{id}/attachments/{role} GET = retrieve attachment with given role PUT = replace or create attachment with given role POST = - DELETE = delete attachment with given role
  • 14. IDENTIFYING RESOURCES 0 ... * links Asset 1 /assets/{id}/links /assets/{id}/links/{id} GET = retrieve all links GET = check if link exists PUT = replace all links PUT = create link POST = add links POST = - DELETE = remove all links DELETE = remove link
  • 15. IDENTIFYING RESOURCES • We only need two URIs: • one for a collection resource • one for an instance resource • Use-case scalability • which resources will be added in the future ?
  • 17. CHOOSING REPRESENTATION • No single format for all representations • varying application use cases and client needs • XML (application/xml) and JSON (application/json) most used • Alternative formats for special cases • image/jpeg, image/png, application/pdf, application/vnd.ms-excel, text/plain, text/csv, ...
  • 18. CHOOSING REPRESENTATION • Sometimes need for combination of textual and binary data • e.g. XML and image data • Possible with multipart media types • multipart/form-data most used • Content-Disposition header for giving extra info • DON’T encode binary data using Base64 encoding
  • 19. CHOOSING REPRESENTATION Content-Type: multipart/form-data; boundary=“abcd” --abcd Content-Type: application/xml Content-Disposition: form-data; name=asset <asset> <name>New asset</name> ... </asset> --abcd Content-Type: image/jpeg Content-Disposition: form-data; name=binary; filename=newasset.jpg ... image here ... --abcd
  • 20. CHOOSING REPRESENTATION • Media type extensions • XML based types end with +xml • for vendor specific extensions the subtype starts with vnd. • Examples • application/atom+xml • application/vnd.google-earth.kml+xml • application/vnd.diocontent+xml • ...
  • 22. RESPONSES GET is obvious: # Request GET /assets/1234 HTTP/1.1 # Response HTTP/1.1 200 OK Content-Type: application/xml <asset> <name>image.jpg</name> ... </asset>
  • 23. RESPONSES POST not so obvious: # Request POST /assets HTTP/1.1 Content-Type: multipart/form-data; boundary=“abcd” ... # Response HTTP/1.1 201 Created Location: http://diocontent.persgroep.be/assets/1234 Content-Type: application/xml <asset id=“1234”> <name>image.jpg</name> ... </asset>
  • 24. RESPONSES PUT for update: # Request PUT /assets/1234 HTTP/1.1 Content-Type: application/xml <asset id=“1234”> <name>updated name</name> ... </asset> # Response HTTP/1.1 200 OK Content-Type: application/xml <asset id=“1234”> <name>updated name</name> ... </asset>
  • 25. RESPONSES DELETE # Request DELETE /assets/1234 HTTP/1.1 # Response HTTP/1.1 204 No Content
  • 27. HANDLING ERRORS • Return response with a 4xx status code for client errors • Indicate server-side errors with a 5xx status code • DON’T use a success status code, i.e. 2xx • Include message in body with more information DON’T DO HTTP/1.1 200 OK HTTP/1.1 404 Not Found Content-Type: application/xml Content-Type: application/xml <error> <error> Asset ‘1234’ not found Asset ‘1234’ not found </error> </error>
  • 28. HANDLING ERRORS • 400 Bad Request • the request cannot be fulfilled due to bad syntax • 401 Unauthorized • authentication is required but has failed or has not yet been provided • 403 Forbidden • request was valid but server is refusing to respond to it • 404 Not Found • requested resource could not be found but may be available again in the future • 405 Method Not Allowed • request was made using a method not supported by the resource • 406 Not Acceptable • cannot generate representation indicated by Accept headers of request • 409 Conflict • request could not be processed because of conflict in the request
  • 29. HANDLING ERRORS • 500 Internal Server Error • best code to return when server fails due to some implementation bug • 503 Service Unavailable • the server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state
  • 30. ADVANCED DESIGN 1. CONTENT NEGOTIATION 2. QUERYING 3. BASE WEB SERVICE URL 4. SECURITY 5. EXTENSIBILITY AND VERSIONING 6. ASYNCHRONOUS TASKS 7. HATEOAS 8. ENABLING DISCOVERY
  • 32. CONTENT NEGOTIATION • Let client choose representation as much as possible • Different mechanisms • Accept-* headers • query parameters • extensions • Use response code 406 (Not Acceptable) for failures
  • 33. CONTENT NEGOTIATION • Accept for preferred media type(s) • Accept-Language for preferred language(s) • Accept-Encoding when client can handle (de)compre •q parameter indicates relative preference • floating-point number in a range of 0.0 to 1.0 (default)
  • 34. CONTENT NEGOTIATION # Request headers Accept: application/xml, application/json;q=0.5, */*;q=0.0 Accept-Language: nl, en-gb;q=0.8, en;q=0.7, *;q=0.1 Accept-Encoding: gzip • XML is preferred media type, JSON is second choice, anything else not acceptable • ‘nl’ first choice, ‘en-gb’ second, ‘en’ third choice • gzip compression is supported
  • 35. CONTENT NEGOTIATION • Query parameter like type, lang GET /assets/1234?type=json&lang=fr HTTP/1.1 • Resource extension GET /assets/1234.json HTTP/1.1 • Conventionally override Accept header
  • 37. QUERYING • GET on collection resource with query parameters # Request GET /assets?q=obama&sortbyAsc=createDate HTTP/1.1 # Response HTTP/1.1 200 OK Content-Type: application/xml <assets> <asset id=“1234”>...</asset> <asset id=“4567”>...</asset> ... </assets> • POST for large queries exceeding maximum length of URI # Request POST /assets HTTP/1.1 Content-Type: application/x-www-form-urlencoded q=obama&sortbyAsc=createDate
  • 38. QUERYING • Pagination # Request GET /assets?q=obama&sortbyAsc=createDate&offset=50&limit=25 HTTP/1.1 • Letting clients decide what they want # Request GET /assets?q=SELECT NAME FROM IMAGES WHERE FULLTEXT='obama' # Response HTTP/1.1 200 OK Content-Type: application/xml <results> <assetResult> <attribute name="NAME">obama001.jpg</attribute> </assetResult> <assetResult> <attribute name="NAME">obama002.jpg</attribute> </assetResult> ... </results>
  • 39. QUERYING • Storing queries # Request POST /assets HTTP/1.1 Content-Type: application/x-www-form-urlencoded q=obama&sortbyAsc=createDate # Response HTTP/1.1 201 Created Content-Type: application/xml Location: http://diocontent.persgroep.be/searches/1 # Use the created resource to fetch query results GET /searches/1 HTTP/1.1 # Response HTTP/1.1 200 OK Content-Type: application/xml <assets> ... </assets> # ... and with pagination GET /searches/1?offset=50&limit=25 HTTP/1.1
  • 41. BASE WEB SERVICE URL • Dedicated URL • Same URL for browser and REST client • only different representations: HTML vs XML/JSON http://diocontent.persgroep.be vs. http://diocontentwebservice.persgroep.be
  • 43. SECURITY • REST is stateless so DON’T use HTTP sessions • Different protocols • Basic • Oauth • Add authentication from the start !
  • 45. EXTENSIBILITY • Preserve backwards compatibility ! • Use HTTP redirects • 301 Moved Permanently • this and all future requests should be directed to the given URI • 304 Temporary Redirect • request should be repeated with another URI, using same method • 410 Gone • when resource used to exist, but it does not anymore
  • 46. VERSIONING • Don’t introduce a version unless you have breaking changes • URL: http://diocontentwebservice.persgroep.be/v2 • Media type: application/vnd.diocontent+xml;v=2
  • 48. ASYNCHRONOUS TASKS • Creating assets in dio:content is an asynchronous operation • Each new asset is placed on a queue as a check-in
  • 49. ASYNCHRONOUS TASKS # Adding new asset POST /assets HTTP/1.1 Content-Type: multipart/form-data; boundary=“abcd” --abcd Content-Type: application/xml ... --abcd Content-Type: image/jpeg ... --abcd # Response HTTP/1.1 202 Accepted Content-Type: application/xml Content-Location: http://diocontent.persgroep.be/checkins/1 <checkIn id=“1”> <state>PENDING</state> <created>2012-02-01T18:20:10.000</created> </checkIn>
  • 50. ASYNCHRONOUS TASKS # Checking status of check-in GET /checkins/1 HTTP/1.1 # Processing asset HTTP/1.1 200 OK Content-Type: application/xml <checkIn id=“1”> <state>PROCESSING</state> <created>2012-02-01T12:00:00.000</created> <processingStarted>2012-02-01T12:00:10.000</processingStarted> </checkIn> # Asset successfully added HTTP/1.1 303 See Other Content-Type: application/xml Location: http://diocontent.persgroep.be/assets/1234 Content-Location: http://diocontent.persgroep.be/checkins/1 <checkIn id=“1”> <state>DONE</state> <created>2012-02-01T18:20:10.000</created> <processingStarted>2012-02-01T12:00:10.000</processingStarted> <completed>2012-02-01T12:00:10.000</completed> <assetId>1234</assetId> </checkIn>
  • 51. ASYNCHRONOUS TASKS # Canceling check-in DELETE /checkins/1 HTTP/1.1 # check-in canceled HTTP/1.1 204 No Content # Already completed check-in cannot be canceled HTTP/1.1 409 Conflict Content-Type: application/xml;charset=utf-8 Location: http://diocontent.persgroep.be/assets/1234 Content-Location: http://diocontent.persgroep.be/checkins/1 <checkIn id=“1”> <state>DONE</state> <created>2012-02-01T18:20:10.000</created> <processingStarted>2012-02-01T12:00:10.000</processingStarted> <completed>2012-02-01T12:00:10.000</completed> <assetId>1234</assetId> </checkIn>
  • 53. HATEOAS Hypermedia As The Engine Of Application State • Use links to allow clients to discover locations and operations • Clients do not need to known URLs, so they can change • The entire application workflow is abstracted, thus changeable • The hypermedia type itself could be versioned if necessary • No breaking of clients if the implementation is updated !
  • 54. HATEOAS # Request GET /assets?q=SELECT NAME FROM IMAGES WHERE FULLTEXT=‘obama’&limit=50 HTTP/1.1 Accept: application/vnd.diocontent+xml # Response HTTP/1.1 200 OK Content-Type: application/vnd.diocontent+xml <?xml version=“1.0” encoding=“utf-8” ?> <results xmlns=“http://diocontentapi.persgroep.be/schema/api” xmlns:atom=“http://www.w3.org/2005/Atom”> <assetResult> <attribute name="NAME">obama001.jpg</attribute> <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234”/> </assetResult> <assetResult> <attribute name="NAME">obama002.jpg</attribute> <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/4567”/> </assetResult> ... <atom:link rel=“first” href=“http://diocontent.persgroep.be/assets?q=...&offset=0&limit=50”/> <atom:link rel=“next” href=“http://diocontent.persgroep.be/assets?q=...&offset=50&limit=50”/> <atom:link rel=“last” href=“http://diocontent.persgroep.be/assets?q=...&offset=800&limit=50”/> </results>
  • 55. HATEOAS # Request GET /assets/1234 HTTP/1.1 Accept: application/vnd.diocontent+xml # Response HTTP/1.1 200 OK Content-Type: application/vnd.diocontent+xml <?xml version=“1.0” encoding=“utf-8” ?> <asset id=“123” xmlns=“http://diocontentapi.persgroep.be/schema/api” xmlns:atom=“http://www.w3.org/2005/Atom”> <name>image.jpg</name> <createDate>2012-02-01T18:20:10.000</createDate> ... <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234”/> <atom:link rel=“alternate” href=“http://diocontent.persgroep.be/assets/1234” type=“image/jpeg”/> <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234/attachments”/> <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234/links”/> </asset>
  • 56. HATEOAS # Request GET /assets/1234/attachments HTTP/1.1 Accept: application/vnd.diocontent+xml # Response HTTP/1.1 200 OK Content-Type: application/vnd.diocontent+xml <?xml version=“1.0” encoding=“utf-8” ?> <attachments id=“123” xmlns=“http://diocontentapi.persgroep.be/schema/api” xmlns:atom=“http://www.w3.org/2005/Atom”> <attachment> <role>original</role> ... <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234/attachments/original”/> <atom:link rel=“alternate” type=“image/jpeg” href=“http://diocontent.persgroep.be/assets/1234/attachments/original”/> </attachment> ... <atom:link rel=“self” href=“http://diocontent.persgroep.be/assets/1234/attachments”/> <atom:link rel=“related” href=“http://diocontent.persgroep.be/assets/1234”/> </attachments>
  • 57. HATEOAS Without HATEOAS, your HTTP interface is not RESTful !
  • 59. ENABLING DISCOVERY • Please document your REST API ! • describe resources, methods, media types, authentication, ... • provide XML schema’s when using XML representations • http://diocontentwebservice.persgroep.be • Implement OPTIONS method to list supported methods # Request OPTIONS /asset/1234 HTTP/1.1 # Response HTTP/1.1 204 No Content Allow: GET, PUT, DELETE, HEAD, OPTIONS
  • 60. THE END ... QUESTIONS ?
  • 61. BOOKS ON REST • Subbu Allamaraju RESTful Web Services Cookbook ISBN: 978-0596801687 • Leonard Richardson, Sam Ruby RESTful Web Services ISBN: 978-0596529260
  • 62. FURTHER READING • RyanTomayko How I Explained REST to my Wife http://tomayko.com/writings/rest-to-my-wife • Jim Webber, Savas Parastatidis & Ian Robinson How to GET a Cup of Coffee http://www.infoq.com/articles/webber-rest-workflow • Roy Thomas Fielding Architectural Styles and the Design of Network-based Software Architectures http://www.ics.uci.edu/~fielding/pubs/disser tation/top.htm

Hinweis der Redaktion

  1. Als voorbeeld gebruiken we dio:content\n
  2. \n
  3. \n
  4. \n
  5. hoe URI ontworpen worden is heel belangrijk en daar gaan we veel aandacht aan besteden\n
  6. \n
  7. \n
  8. resource is abstract, representation is iets heel concreet\n\nContent-Type zegt hoe ontvanger data moet interpreteren of parsen\n\n
  9. Als voorbeeld gebruiken we dio:content\n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. POST op zelfde URI als die om nieuw asset resource te maken\n-&gt; dmv Content-Type kan server dit onderscheiden\n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n