REST & JAX-RS

Content

 

REST and Software Architecture

HTTP and REST

REST Principles Detail

JAX-RS Intro

 

Example: Web Store (JAX-RS)

 

 

REST

Intro

  • Roy Fielding
    • principal author of HTTP
    • co-founder of Apache HTTP Server
  • Roy Fielding PhD Thesis in 2000
    • Why is the web so prevalent and ubiquitos?
    • What makes the Web scale?
    • How can the architecture of the web be applied on applications
  • REpresentational State Transfer (REST)

Software Architecture

  • Components
    • Unit of software instructions and state that provides a transformation of data via an interface
  • Connectors
    • Allows communication between Components
  • Data
    • Info transferred between components, via connectors
    • In REST
      • Resource
      • Resource Id (URI, URL)
      • Representation
      • Metadata

Roy Fielding on REST

REST's client–server separation of concerns simplifies component implementation, reduces the complexity of connector semantics, improves the effectiveness of performance tuning, and increases the scalability of pure server components. Layered system constraints allow intermediaries - proxies, gateways, and firewalls - to be introduced at various points in the communication without changing the interfaces between components, thus allowing them to assist in communication translation or improve performance via large-scale, shared caching. REST enables intermediate processing by constraining messages to be self-descriptive: interaction is stateless between requests, standard methods and media types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.

Architectural Principles

  • Addressable resources
    • Data/information as resource
    • Each resource addressable via URI
  • Uniform, constrained interface
    • Small set of well-defined methods to manipulate resources
  • Representation-oriented
    • Interact with service using representations
    • Resources can have different formats (html, json, xml)
  • Communicate statelessly
    • Easier to scale apps
  • Hypermedia as the Engine of Application (HATEOAS)
    • Data formats info about state transitions

HTTP and REST

  • REST not protocol specific - usually HTTP
  • Non-RESTful services use HTTP only as transport
  • HTTP
    • Request/Response-based application network protocol
    • Client sends a request message
    • Message consists of
      • HTTP method
      • Message Header (HTTP headers)
      • Message Body (html, json, xml, binary data, plain text..
      • (Demo HTTP req)

REST Principles

  • Addressability
    • Every object reachable via unique id
    • URIs
      • scheme://host:port/part?query#fragment
    • Host is DNS name or ip address
    • Port is optional
    • Query string
      • List of parameters represented as name value pairs
      • http://example.com/customers?lastname=Max&city=Vienna
    • Fragment
      • Points to certain place in document
    • Not all characters allowed in URI (e.g.: + for space char)

Rest Principles #2

  • Uniform, constrained interface
    • Use small set of operations of the application protocol
    • Use methods of HTTP for web services
    • HTTP methods
      • GET
        • Read-only operation
        • Query server for specific information
        • Idempotent and safe operation
        • Does not change state of server
      • PUT
        • Store data in message body under the URI
        • Insert or update operation
        • Idempotent
        • Sending same PUT has no effect

Rest Principles #3

  • Uniform, constrained interface cont'd
    • HTTP methods
      • DELETE
        • Remove resources
        • Idempotent
      • POST
        • Not idempotent, unsafe operation
        • May modify service in unique way
      • HEAD
        • Same as GET but
        • Only returns headers and response code
      • OPTIONS
        • Request info about communication options
        • Client gets info about capabilities of the server

REST Principles #4

  • Uniform, constrained interface cont'd
    • All services implemented with 4-6 operations
    • Familiarity
    • Interoperability
      • HTTP client or
      • HTTP lib required
      • CORBA/SOAP more difficult to setup
    • Scalability
      • HTTP supports caching

REST Principles #5

  • Representation Oriented
    • GET operation receives representation of resource
    • PUT/POST passes representation to server
    • HTTP uses Content-Type header to define representation format
    • MIME (Multipurpose Internet Mail Extension)
      • type/subtype;name=value,name=value
      • E.g.: text/html;chartset=iso-8859-1
    • HTTP supports message type negotiation
    • Accept headers define preferred response formats

REST Principles #6

  • Communicate statelessly
    • No client session data stored on server
    • Server only manages state of the resources
    • Session specific data maintained by client
    • Must be sent to server with each request
    • Mid 90's:
      • Fat GUI written in Visual Basic
      • Talking to RPCs to middle layer in front of DB
      • Server was stateless
      • Client managed session state
      • Problem
        • Upgrade/Path/Maintain client GUI
        • Solved by (modern browsers and) web apps nowdays since app is delivered by central server (since 2008)

REST Principles #7

  • Hypermedia as the Engine of Application state
    • Hyperlinks allow data aggregation
    • E.g.: Buy book on amazon
      • Follow series of links, fill forms before credit card is charged
      • Each request from server tells which new interactions are possible
    • E.g.: Pagination on book lists

JAX-RS

Intro

  • Many years server programming via servlets
    • Close to HTTP protcol
    • Require lots of boilerplate code to move info from and to HTTP request
  • Since 2008 JAX-RS specification to simplify development of RESTful services
  • Focus on applying Java annotations to plain Java objects
  • Annotations to bind URI patterns and HTTP operations to certain methods
  • Parameter injection annotations allow easy info pulling
  • Message body readers and writes
  • Exception mappers
    • Map app exception to HTTP response code and message

Example: Web Store

  • Ecommerce web store
  • Clients will buy goods, modify orders, view info about customers and products
  • Object Model
    • Each order represents a purchase and is associated with a customer
    • Orders consist of line items
    • Line items
      • Represent type and number of each product

Customer Data Class

public class Customer {
    private String firstName;
    // ...

    public String getFirstName() { return firstName; }

    public void setFirstName(String firstName) { this.firstName = firstName; }
    // ...
}
  • Usual Java Bean
  • In Java EE
    • Java Persistance API (JPA) Entity Bean
    • Simplifies interaction with DB
  • Could be annotated with JAXB
    • Allows mapping directly to XML

Customer Resource Class

  • Use JAX-RS annotations to bind incoming HTTP requests to Java methods
  • Per-request objects
    • Java object created to process request, thrown away afterwards
  • Singletons
@Path("/customers")
public class CustomerResource {
    // ...

    @POST
    @Consumes("application/xml")
    public Response createCustomer(InputStream is) {
        // ...
    }
}

Annotation Basics

@Path("/customers")
class A {

    @POST
    @Path("{id}")
    @Consumes("application/xml")
    public Response foo(@PathParam("id") int id, InputStream is) {
        // ...
    }
}
  • Path annotation defines JAX-RS service
  • All resources designated by Path annotations
  • Specify relative URI
  • E.g.: @POST annotation used to bind post requests to Java method
  • @Consumes annotation defines expected media type in the message body
    • If other media type is specified, error code is sent back

Message Body

@POST
@Consumes("application/xml")
public Response createCustomer(InputStream is) {
    // ...
    return Response.created(URI.create("/customers/" + c.getId())).build();
}
  • Any non JAX-RS annotated parameter is considered as message body of HTTP request
  • Only 1 method parameter can represent the message body
  • InputStream is most basic representation
  • Response handling
    • Response.created will set Location header to specified URI
    • WebApplicationException(Response.Status.NOT_FOUND) will set response code to 404 "Not found"

Manual Streaming

public interface StreamingOutput {
    public void write(OutputStream os) 
        throws IOException, WebApplicationException;
}

// E.g. GET /customer/{id}

    return new StreamingOutput {
        @Override
        public void write(OutputStream os)
            throws IOException, WebApplicationException {
                outputCustomer(os,c);
        }
    }
  • Usually StreamingOutput is not used
  • JAX-RS has some content handlers

Application Class

  • Define per-request objects and singletons
@ApplicationPath("/api")
public class WebShopServer extends Application {
    private Set<Object> singeltons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();

    public WebShopServer() {
        singeltons.add(new CustomerResource());
    }

    @Override
    public Set<Class<?>> getClasses() {
        return empty;
    }

    @Override
    public Set<Object> getSingletons() {
        return singeltons;
    }
}

Application Class and Deployment

public abstract class Application {
    private static final Set<Object> emptySet = Collections.emptySet();
    public abstract Set<Class<?>> getClasses();
    public Set<Object> getSingletons() { 
        return emptySet;
    }
}
  • @ApplicationPath defines relative URL of all JAX-RS resources
  • JAX-RS classes must be deployed within application server's servlet container as Web ARchive (WAR)
  • Everything outside WEB-INF is published by servlet container (html, images, etc)
  • All classes in WEB-INF
WEB-INF/
    web.xml
    classes/
        Customer.class
        ...

Annotations and Interfaces

@Path("customers")
public interface ICustomerResource {
    @POST
    @Consumes("application/xml")
    public Response createCustomer(InputStream is);

    // ...
}

public class CustomerResource implements ICustomerResource {
    public Response createCustomer(InputStream is) {
        // ...
    }
}
  • No JAX-RS annotations needed in implementation
  • Override metadata by reapplying annotations
    • All annotations must be respecified
  • When inheriting, subclass must have @Path annotations



References


RESTful Java with JAX-RS 2.0, Bill Burke

http://en.wikipedia.org/wiki/Representational_state_transfer


 

 

 

 

Thank you for your attention!

 

Made with Slides.com