Chap-5. Les Frameworks REST

Embed Size (px)

DESCRIPTION

framework rest

Citation preview

  • 1Chapitre 5. Les frameworks REST

    Chapitre 5

    Les Frameworks REST

    Les frameworks REST

    2M.Romdhani, INSAT, Dcembre 2015

    Sommaire

    Qu'est ce que REST ?

    Le format JSON

    Mise en uvre de REST avec JAX-RS et Jersey

    Mise en uvre de REST avec Apache-CXF

    Mise en uvre de REST avec REST-Easy de JBoss

    Mise en uvre de REST avec Spring MVC

  • 2Chapitre 5. Les frameworks REST

    Qu'est ce que REST ?

    Les frameworks REST

    4M.Romdhani, INSAT, Dcembre 2015

    Qu'est ce que REST?

    "The motivation for developing REST was to createan architectural model for how the Web should work,

    such that it could serve as the guiding framework for the Web protocol standards

    Roy Fielding

    REST (Representational state transfer) est une manire de construire une application pour les systmes distribus comme le Web. Le terme a t inventpar Roy Fielding en 2000.

    REST n'est ni un protocole ni un format, c'est un style darchitecture, bti sur quelques principes simples : L'URI est fondamentale : connatre l'URI doit suffire pour accder la ressource ; HTTP fournit toutes les oprations ncessaires (GET, POST, PUT et DELETE,

    essentiellement) ; Chaque opration est auto-suffisante : il n'y a pas d'tat ; Utilisation des standards hypermedia : HTML ou XML qui permettent de faire des

    liens vers d'autres ressources et d'assurer ainsi la navigation dans l'application REST.

  • 3Chapitre 5. Les frameworks REST

    Les frameworks REST

    5M.Romdhani, INSAT, Dcembre 2015

    Architecture oriente ressource

    Linformation de base, dans une architecture REST, est appele ressource. Dans un systme hypermedia, une ressource est tout ce qui peut tre rfrenc par un lien.

    Une ressource est identifie par un identificateur de ressource. Sur le web ces identificateurs sont les URI (Uniform Resource Identifier).

    Enfin, les composants de larchitecture manipulent ces ressources en transfrant des reprsentations de ces ressources ( format HTML ou XML).

    Les frameworks REST

    6M.Romdhani, INSAT, Dcembre 2015

    Architecture oriente ressource

  • 4Chapitre 5. Les frameworks REST

    Les frameworks REST

    7M.Romdhani, INSAT, Dcembre 2015

    REST et le Web

    REST est le style architectural original du Web !

    Tous les services Web que nous utilisons depuis des annes ,services de commande des livres , services de recherche ,dictionnaire en lignesont des Web services bass sur REST.

    Donc, vous tes entrain dutiliser REST sans le savoir !

    Les frameworks REST

    8M.Romdhani, INSAT, Dcembre 2015

    Pourquoi lappellation Representational state transfer?

    Le client rfrencie une ressource Web grace une URL.Il reoit unereprsentation de la ressource(ici un doc HTML).

    La nouvelle reprsentation (Boeing747.html) place lapplication clientedans un autre tat(state).

    Ainsi, lapplication cliente change(transfers) dtat avec chaquereprsentation

    ResourceClienthttp://www.boeing.com/aircraft/747

    Boeing747.html

    Fuel ncessaireMaintenance prvue.

  • 5Chapitre 5. Les frameworks REST

    Les frameworks REST

    9M.Romdhani, INSAT, Dcembre 2015

    Caractristiques du modle REST

    Client-Server: La sparation des concepts amliore la portabilit de l'interface

    utilisateur travers les diverses plates-formes. Permettre aux composants d'voluer indpendamment.

    Stateless: (sans tat) L'tat de la session est entirement dtenu par le client. La fiabilit est amliore car il est plus simple de faire face des checs

    partiels (restauration) La possibilit de monte en charge est meilleure.

    Cache: Offre la possibilit dliminer tout ou une partie de certaines interactions Amliore l'efficacit, la monte en charge et rduit la latence moyenne

    dans une srie d'interactions.

    Les frameworks REST

    10M.Romdhani, INSAT, Dcembre 2015

    Caractristiques du modle REST

    Uniform interface: Toutes les ressouces sont manipules par une interface gnrique

    (HTTP GET, POST, PUT, DELETE).

    Code la demande: REST permet lextension des fonctionnalits dun client en tlchargeant et excutant

    du code sous forme d'applet ou de scripts. Amliore l'extensibilit du systme grce la possibilit de tlcharger des

    fonctionnalits aprs le dploiement.

  • 6Chapitre 5. Les frameworks REST

    Les frameworks REST

    11M.Romdhani, INSAT, Dcembre 2015

    REST et les web services

    Un web service qui suit larchitecture REST est dit RESTful

    Le web doit son succs ce style darchitecture oriente ressource. Il na pas t conu comme un BUS XML pour transfrer des messages entre applications (cas du SOAP).

    Les qualits recherches pour le web rejoignent celles des web services : sparation des tches, simplicit, interoprabilit, performances rseaux, ...

    Les frameworks REST

    12M.Romdhani, INSAT, Dcembre 2015

    REST Web-services

    HTTP methods GET defines a reading access of the resource without side-effects. The

    resource is never changed via a GET request, e.g. the request has no side effects (idempotent).

    PUT creates a new resource, must also be idempotent.

    DELETE removes the resources. The operations are idempotent, they can get repeated without leading to different results.

    POST updates an existing resource or creates a new resource.

  • 7Chapitre 5. Les frameworks REST

    Les frameworks REST

    13M.Romdhani, INSAT, Dcembre 2015

    REST Web-services

    Example base URI for the web service: http://example.com/resources/

    Resource GET PUT POST DELETE

    Collection URI, such ashttp://example.com/resourc

    es/

    List the URIs and perhaps other details of the collection's members.

    Replace the entire collection with another collection.

    Create a new entry in the collection. The new entry's URL is assigned automatically and is usually returned by the operation.

    Delete the entirecollection.

    Element URI, such ashttp://example.com/resourc

    es/item17

    Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type.

    Replace the addressed member of the collection, or if it doesn't exist, create it.

    Not generally used. Treat the addressed member as a collection in its own right and create a new entry in it.

    Delete the addressed member of the collection.

    Le format JSON

  • 8Chapitre 5. Les frameworks REST

    Les frameworks REST

    15M.Romdhani, INSAT, Dcembre 2015

    JSON Notation

    A lightweight data-interchange format

    A subset of the object literal notation of JavaScript (or ECMA-262). A JSON string must be enclosed by double quotes.

    Comparison of JSON and XML Similarities:

    Both are human readable/Both have very simple syntax Both are hierarchical/Both are language independent Both can be used by Ajax

    Differences: Syntax is different JSON is less verbose JSON includes arrays Names in JSON must not be JavaScript reserved words XML can be validated JavaScript is not typically used on the server side

    Les frameworks REST

    16M.Romdhani, INSAT, Dcembre 2015

    JSON example

    JSON stands for JavaScript Object Notation Despite the name, JSON is a (mostly) language-independent way of specifying

    objects as name-value pairs

    Example (http://secretgeek.net/json_3mins.asp):{"skillz": {

    "web":[{ "name": "html", "years": 5

    },{ "name": "css", "years": 3

    }]"database":[

    { "name": "sql", "years": 7

    }]}}

  • 9Chapitre 5. Les frameworks REST

    Les frameworks REST

    17M.Romdhani, INSAT, Dcembre 2015

    JSON syntax, I

    An object is an unordered set of name/value pairs The pairs are enclosed within braces, { } There is a colon between the name and the value Pairs are separated by commas Example: { "name": "html", "years": 5 }

    An array is an ordered collection of values The values are enclosed within brackets, [ ] Values are separated by commas Example: [ "html", xml", "css" ]

    Les frameworks REST

    18M.Romdhani, INSAT, Dcembre 2015

    JSON syntax, II

    A value can be: A string, a number, true, false, null, an object, or an array Values can be nested

    Strings are enclosed in double quotes, and can contain the usual assortment of escaped characters

    Numbers have the usual C/C++/Java syntax, including exponential (E) notation All numbers are decimal--no octal or hexadecimal

    Whitespace can be used between any pair of tokens

  • 10

    Chapitre 5. Les frameworks REST

    Les frameworks REST

    19M.Romdhani, INSAT, Dcembre 2015

    Using JSON in JavaScript

    JSON encoded data JavaScript object var myObject = Eval('(' + myJSONtext + ')'); var myObject = JSON.Parse(myJSONtext);

    JavaScript value JSON encoded data var myJSONText = JSON.stringify(myObject);

    Les frameworks REST

    20M.Romdhani, INSAT, Dcembre 2015

    Using JSON with XmlHttpRequest

    Sending JSON encoded data to the server Use HTTP POST method and send the JSON encoded data in the body of

    the request// xmlhttp is an XmlHttpRequest objectxmlhttp.setRequestHeader(

    'Content-type','application/x-www-form-urlencoded;charset=UTF-8;'

    );xmlhttp.send('jsondata=' + escape(myJSONText));

    Handling JSON encoded data from the server Server should set the content type to "text/plain" In the handler function of xmlhttp object, read xmlhttp.responseText

  • 11

    Chapitre 5. Les frameworks REST

    Mise en uvre de REST avec JAX-RS et Jersey

    Les frameworks REST

    22M.Romdhani, INSAT, Dcembre 2015

    JAX-RS

    JSR-311: JAX-RS: The Java API for RESTful Web Services

    Introduced in Java SE 5: annotation-based

    Objective: simplify the development and deployment of web service clients and endpoints.

    Part of Java EE 6

    No configuration is necessary to start using JAX-RS

  • 12

    Chapitre 5. Les frameworks REST

    Les frameworks REST

    23M.Romdhani, INSAT, Dcembre 2015

    JAX-RS API

    Specifications Annotations to aid in mapping a resource class (a Plain Old

    Java Object) as a web resource. @Path specifies the relative path for a resource class or method. @GET, @PUT, @POST, @DELETE and @HEAD specify the HTTP request type of a

    resource.

    @Produces specifies the response MIME media types. @Consumes specifies the accepted request media types.

    Annotations to method parameters to pull information out of the request. All the @*Param annotations take a key of some form which is used to look up the value required.

    @PathParam binds the parameter to a path segment. @QueryParam binds the parameter to the value of an HTTP query parameter. @MatrixParam binds the parameter to the value of an HTTP matrix parameter. @HeaderParam binds the parameter to an HTTP header value. @CookieParam binds the parameter to a cookie value. @FormParam binds the parameter to a form value. @DefaultValue specifies a default value for the above bindings when the key is not

    found. @Context returns the entire context of the object. Ex.(@Context HttpServletRequest

    request)

    Les frameworks REST

    24M.Romdhani, INSAT, Dcembre 2015

    JAX-RS API

  • 13

    Chapitre 5. Les frameworks REST

    Les frameworks REST

    25M.Romdhani, INSAT, Dcembre 2015

    JAX-RS implementations

    Implementations Jersey, from Sun/Oracle (Java EE 6 reference implementation) Apache, CFX from Apache RESTeasy, from JBoss Restlet, created by Jerome Louvel, a pioneer in REST frameworks.

    Les frameworks REST

    26M.Romdhani, INSAT, Dcembre 2015

    Jersey

    Jersey is the reference implementation for the JSR 311 specification. The Jersey implementation provides a library to implement Restful

    webservices in a Java servlet container. On the server side Jersey provides a servlet implementation which

    scans predefined classes to identify RESTful resources. In your web.xml configuration file your register this servlet for your web

    application. The Jersey implementation also provides a client library to communicate

    with a RESTful webservice. JAX-RS supports the creation of XML and JSON via the Java

    Architecture for XML Binding (JAXB).

  • 14

    Chapitre 5. Les frameworks REST

    Les frameworks REST

    27M.Romdhani, INSAT, Dcembre 2015

    Mise en uvre de REST avec Jersey

    Steps Setup of Jersey libraries either manually or using a depedency

    management tools like Maven or Gradle Create a web application and register the Jersey Servlet dispatcher

    in web.xml

    Jersey REST Serviceorg.glassfish.jersey.servlet.ServletContainer

  • 15

    Chapitre 5. Les frameworks REST

    Les frameworks REST

    29M.Romdhani, INSAT, Dcembre 2015

    Mise en uvre de REST Apache-CXF

    Steps Create the Web App using Maven and download the Apache CXF

    dependencies Configure Apache CXF in the Web App

  • 16

    Chapitre 5. Les frameworks REST

    Mise en uvre de REST avec REST-Easy

    Les frameworks REST

    32M.Romdhani, INSAT, Dcembre 2015

    Mise en uvre de REST Easy

    Steps Create the Web App using Maven and download the Apache CXF

    dependencies

    org.jboss.resteasyresteasy-jaxrs2.2.1.GA

    Configure Apache CXF in the Web App

    org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

    resteasy-servlet

    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher

    resteasy-servlet/rest/*

    Contd

  • 17

    Chapitre 5. Les frameworks REST

    Les frameworks REST

    33M.Romdhani, INSAT, Dcembre 2015

    Mise en uvre de REST Easy

    Steps (Contd) Create the Web App using Maven and download the Apache CXF

    dependencies

    org.jboss.resteasyresteasy-jaxrs2.2.1.GA

    Configure Apache CXF in the Web App

    org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

    resteasy-servlet org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher

    resteasy-servlet/rest/*

    Create the Service Implementation on the App Test out the service

    Mise en uvre de REST avec Spring MVC

  • 18

    Chapitre 5. Les frameworks REST

    Les frameworks REST

    35M.Romdhani, INSAT, Dcembre 2015

    Mise en uvre de REST avec Spring MVC

    Spring MVC 4 annotations supporting REST @RestController : Spring 4s new @RestController annotation. This annotation eliminates the

    need of annotating each method with @ResponseBody. Under the hood, @RestController isitself annotated with @ResponseBody, and can be considered as combination of @Controller and @ResponseBody.

    @RequestBody : If a method parameter is annotated with @RequestBody, Spring will bind the incoming HTTP request body(for the URL mentioned in @RequestMapping for that method) to that parameter. While doing that, Spring will [behind the scenes] use HTTP Message convertersto convert the HTTP request body into domain object [deserialize request body to domainobject], based on ACCEPT or Content-Type header present in request.

    @ResponseBody : If a method is annotated with @ResponseBody, Spring will bind the return value to outgoing HTTP response body. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type present in request HTTP header. As alreadymentioned, in Spring 4, you may stop using this annotation.

    ResponseEntity is a real deal. It represents the entire HTTP response. Good thing about it isthat you can control anything that goes into it. You can specify status code, headers, and body. It comes with several constructors to carry the information you want to sent in HTTP Response.

    @PathVariable This annotation indicates that a method parameter should be bound to a URI template variable [the one in '{}'].

    Basically, @RestController , @RequestBody, ResponseEntity & @PathVariable are all you need to know to implement a REST API in Spring 4. Additionally, spring provides several support classes to help you implement something customized.

    Les frameworks REST

    36M.Romdhani, INSAT, Dcembre 2015

    Mise en uvre de REST avec Spring MVC

    Steps Create the Web App using Maven and download the Spring mvc

    dependencies Configure the dispatcher servlet in the Web App Create the Service Implementation on the App Test out the service