rest soap

Document Sample
rest soap Powered By Docstoc
					rest / soap
and the future of web services
Andrew Babiec
New England Code Camp 12: “The Developer Dozen”
Two Camps on Web Services
   SOAP, WS-* / XML-RPC
   REST
       Representational State Transfer

   What is REST?
   How does it differ from SOAP?
   When should you use one over the other?
       Is it an either/or decision?
What is REST?
   Chapter 5 - Roy Fielding Dissertation
   “An architecture style for distributed systems”
   Characteristics
       Resources
         Referenced by Unique Identifiers
         Representations

     Uniform Interfaces
     Connections

     Stateless

     Other – Cacheable, Idempotent (No Side Effects)
REST Example
   Web Sites
     GET
     GET

   Web Services
       Flickr REST API
         http://farm{farm-id}{server-
Differences: SOAP and REST
   SOAP: Operations
       Procedural (RPC over HTTP)
         GetAccountBalance(), SubmitOrder()

   REST: Resources                               NOUNS
     Start    with the data/entities/resources first
         Define   the URI
              Then expose uniform interfaces:
                  Create/Read/Update/Delete
SOAP Philosophy
   SOAP: use the web as a means to facilitate
    distributed computing and exchange information
       Easier interoperability
         XML  instead of binary formats
         HTTP instead of proprietary protocols
         Platform and language independent

     Standards for advanced scenarios
     Contracts

     Versatile and Flexible
REST Philosophy
   REST: stay true to the existing web design/style
     It already provides everything you need (re-use!)
     HTTP + KISS
         Security? Use  SSL and HTTP Authentication
         HTTP methods/verbs: GET / POST / PUT / DELETE / HEAD
         Results should include URI for more info
         HTTP Headers, encoding, compression, caching, proxies
         Error handling? Use HTTP status/response codes & messages
               Resource location change? Use HTTP Redirect
         Distributed Transactions,   Reliable Messaging? YAGNI
   One URI for a resource, multiple operations
       Add a new presentation “RestTalk” for Code Camp 12
         PUT
       Get the slides
         GET
       Remove the slides
         DELETE

       Metadata
         HEAD

              Notice a pattern? Consistent Resource Identifier
RESTful (cont.)
   Compare to
     SearchContent
     CreateEvent

     GetDocumentByID

     ShowDocumentsForEvent

     UploadFileCollection

     PublishDocToSite
RPC compared to RESTful
RPC Operation               Method   URI Template
SearchContent               GET      /q={search text}
CreateEvent                 PUT      /events/{eventName}
CreateEvent                 POST     /events
GetDocumentByID             GET      /events/{eventName}/docs/{id}
RetrieveDocumentsForEvent   GET      /events/{eventName}/docs
UploadFileCollection        POST     /events/{eventName}/docs
PublishDocToSite            PUT      /events/{eventName}/docs/{DocName}
DeleteEvent                 DELETE   /events/{eventName}
ShowPageFromDoc             GET      /events/{eventName}/docs/{id}/{page#}
GetAllEvents                GET      /events
Sidenote: POST vs. PUT
   PUT – Create when specifying a new URI
   PUT – Edit when specifying an existing URI
   POST – Create when specifying the “parent” URI
         Similar to   an Append

   PUT /diary/2009/12/09
       Will create if not exists, edit if already exists
   POST /diary
       Service will determine the new URI for the resource,
        returning it as part of the response
REST method guidelines
   Safe methods – do not change data
     Get
     Head

   Idempotent methods – no side effects, can be
    called multiple times
     Get
     Head

     Put

     Delete
RESTful Best Practices
   Method info goes into the HTTP method used
   Scoping information goes into the URI
       RPC-style web services tend to ignore the HTTP method, looking
        for method and scoping information in the URI, HTTP headers, or
        entity-body. Some RPC-style web services use HTTP as an
        envelope containing a document, and others only use it as an
        unlabelled envelope containing another envelope.

   A RESTful, resource-oriented service exposes a URI
    for every piece of data the client might want to
    operate on.
       A REST-RPC hybrid exposes a URI for every operation the client
        might perform: one URI to fetch a piece of data, a different URI
        to delete that same data.
 Paths (slashes) for hierarchy
 Querystring used for arguments into an

 Representing multiple pieces of scope info

     Use comma if order matters - like longitude,

     Use   semi-colon if order not important
Benefit of URI approach - Caching
   REST web services can re-use standard web caching
    – Conditional HTTP Get
       Last-Modified in response header
         If-Modified-Since in   request header
              Return 304 (“Not Modified”) if data has not changed
     Etag
     Expires / Cache-Control

   SOAP – custom implementation
Differences: SOAP and REST
   Protocols
     REST – HTTP
     SOAP – usually HTTP but can also use TCP, MSMQ,
      SMTP, File, etc.
         Transport Independent

   Representations (Data Format)
     SOAP – always XML
     REST – XML, JSON, XHTML, anything
Sidenote: JSON
   JSON is a simple and language-independent way of
    formatting programming language data structures
    (numbers, arrays, hashes, and so on) as strings.
       In addition, JSON is a tightly constrained JavaScript
        program, can be parsed by calling eval.
           Not TIED to just JavaScript – can be useful outside of JavaScript

       Every web browser offers a slightly different JavaScript
        interface to its XML parser, but a JSON string works the
        same way in every browser.
           When an Ajax response is XML, the web browser parses it (tree-
            style) and makes it available via the responseXML property of the
            XMLHttpRequest object.
    JSON Example
<menu id="file" value="File">
 <popup>                                                   XML
  <menuitem value="New" onclick="CreateNewDoc()" />
  <menuitem value="Open" onclick="OpenDoc()" />
  <menuitem value="Close" onclick="CloseDoc()" />

                                {"menu": { "id": "file", "value": "File",
                                  "popup": {
                                    "menuitem": [
                JSON                  {"value": "New", "onclick": "CreateNewDoc()"},
                                      {"value": "Open", "onclick": "OpenDoc()"},
                                      {"value": "Close", "onclick": "CloseDoc()"}
SOAP / REST Security
   SOAP: Protocol and message security
       SAML assertions, Kerberos tickets, X.509 certificates
         WS-Security: Defines how to convey various security tokens and
          more. Support for identity through SOAP intermediaries. Not just
         WS-Trust: Defines how to get security tokens
         WS-SecureConversation: Allows establishing a security context

   REST: Re-use existing web security
       SSL and HTTP Authentication (Basic, Digest, WSSE)
Describing REST web services
   SOAP: WSDL (Web Services Description Language)

   REST: ?

       WADL (Web Application Description Language)
         Not supported
              Resistance due to fear it would impose an RPC style
     Write-up Documentation
     Popular Web Services provide client libraries for
      popular languages/platforms
Error Handling in REST
   Use HTTP codes (use the entity-body for more info)
     200 OK
     201 Created
            HTTP Location Header should have URI to new resource
     400 Bad Request
     404 Not Found
     500 Internal Server Error
     301 Moved Permanently
     403 Forbidden
     401 Unauthorized
     409 Conflict
Advanced SOAP Features
   WS-*
     WS-Addressing: Allows using SOAP over protocols
      other than HTTP
     WS-ReliableMessaging: Allows reliable end-to-end
      communication through SOAP intermediaries. Builds
      acknowledgement/retry logic into the communications
     WS-AtomicTransaction, WS-Coordination: Define how
      to do two-phase commit for ACID transactions
     WS-Policy: allow services to advertise their policy and
      consumers to specify their requirements
Which approach to use?
   Are you exposing data or logic?
   Do you need the advanced WS-* capabilities?
   Do you need to support a diverse set of clients?
       Are you exposing this to the public?
   Support by your technology stack?
     REST is built in to Ruby by Rails
     Strong support in J2EE/.NET for SOAP/WS-*/WSDL

   Do you need protocol flexibility?
   Support for PUT / DELETE
Steps to develop a RESTful web service
1.   Figure out the data set
2.   Split the data set into resources
     For each kind of resource:
3.   Name the resources with URIs
4.   Expose a subset of the uniform interface (methods)
5.   Design the representation(s) accepted from the client
6.   Design the representation(s) served to the client
7.   Integrate this resource into existing resources, using
     hypermedia links and forms
8.   Consider the typical course of events: what’s supposed to
9.   Consider error conditions: what might go wrong?
   Properties of REST Architecture
     Addressability
     Uniform Interface
     Statelessness
     Connectedness

   Both REST and SOAP support SOA
   In the same way it is possible to create non-
    OO/procedural code using Java/.NET, it is also
    possible to create RPC-Style web services that claim to
    be RESTful
Example: Amazon S3{name-of-bucket}/{name-of-bucket}/{name-of-object}
Support in .NET
   WCF .NET 3.5 – added support for building REST
    Style services
   WCF .NET 3.5sp1 - UriTemplate flexibility, support
    ADO.NET Entity Framework entities in WCF
    contracts, improvements in the dev tools
   .NET 4.0: URL Routing in web forms
   WCF REST Starter Kit (beta) – makes it easier
       Help page, Representation formats using Accepts HTTP
        Header, Declarative caching, X-HTTP-Method-Override
   aka Atom Publishing Protocol
   An application-level protocol for publishing and
    editing Web resources
   Microsoft has bet on it as the future direction for
    Web APIs - using it for ADO.NET Data Services
    (Astoria), Windows Live Platform and Azure
Support in other technologies
   Java: JAX-RS
       Jersey, RESTEasy, Enunciate, CXF, RESTlet
   Python: Django
   Flash/Flex: URLRequest class
     Browser plug-ins limited to GET and POST
     AIR – supports all methods

   Ruby – ActiveResource
       Mapping RESTful resources as models in a Rails application
   iPhone – ObjectiveResource, json-framework
   REST in WCF

   This presentation:
   Contact me with questions
Questions and Discussion

Shared By: