SlideShare a Scribd company logo
Restful
  web
services
    By
  Angelin
Widely Well-known “Words”
 Internet
    Massive network of networks, connecting millions of computers
     together globally.
    Information communication using protocols like HTTP, SMTP,
     FTP etc


 World Wide Web, or simply Web
    A way of accessing information over the Internet using HTTP.
World Wide Web
 The Web as defined by Tim Berners-Lee consists of three elements:
    URI (Uniform Resource Identifier) - The way of uniquely
     identifying resources on the network.
    HTML (HyperText Markup Language) - The content format of
     resources to be returned.
    HTTP (HyperText Transfer Protocol) - The protocol used to
     request a resource from the network and respond to requests.


 HTTP methods
     All client server communication on the World Wide Web are
        done using the following simple HTTP methods:
    GET = "give me some info" (Retrieve)
    POST = "here's some info to update” (Update)
    PUT = "here's some new info" (Create)
    DELETE = "delete some info" (Delete)
Retrieving Information using HTTP GET
                                      Client Request
                    HTTP          GET / HTTP/1.1
                    Header        Host: http://www.amazon.com


                                                                      Amazon
                             HTTP/1.1 200 OK
                             Server: Microsoft-IIS/5.1
                                                                        Web
                             Content-Type: text/html; charset=utf-8    Server
                             Content-Length: 8307
                             <html>
                               <head>
                             ...

                                    Server Response
 The user types http://www.amazon.com in his browser.
 The browser software creates and sends a HTTP request with a
  header that holds:
       The desired action: GET ("get me resource")
       The target machine (www.amazon.com)
 The server responds with the requested resource which is rendered
  on the browser
Updating Information using HTTP POST
                                         Client Request
                       HTTP         POST / HTTP/1.1
                       Header       Host: http://www.amazon.com

                       Payload   Book: Da Vince Code
                     (Form Data) Credit Card: Visa
                                    Number: 123-45-6789
                                    Expiry: 12-04-06                           Amazon
                       HTTP/1.1 200 OK
                                                                                 Web
                       Server: Microsoft-IIS/5.1                                Server
                       Content-Type: text/html; charset=utf-8
                       Content-Length: 8307
                       <html>
                       <body>Your order has been placed successfully!</body>
                       </html>

                                   Server Response
 The user fills in a form on the Web page and submits it.
 The browser software creates and send a HTTP request with a header and a
    payload comprising of the form data.
     The HTTP header identifies:
        • The desired action: POST
        • The target machine (amazon.com)
     The payload contains:
        • The data being POSTed (the form data)
 The server responds with the requested resource which is rendered on the
browser
Widely Well-known “Words” (Contd..)
 Web Application
      Usually a collection of dynamic web pages
      Usually restricted to the intranet
      Can be implemented as desktop application
      Information accessible using front end user interfaces
      Accessed by authorised users only
 Web Site
      Collection of static and dynamic web pages
      Available on the internet, or an organization's intranet
      Cannot be implemented as desktop application
      Information accessible using front end user interfaces
      Accessed by anybody
Widely Well-known “Words” (Contd..)
 Web Service
     Application run by a web server, performing tasks and
      returning structured data to a calling program, rather
      than html for a browser.
     Only “provides” information; does not “present”
      information
     Publicly available and standardized for use by all
      programmers
 Web Server
     Software designed to serve web pages/web sites/web
      services. Examples are IIS, Apache, etc.
Web Services
 Services (usually some combination of program and data) that
 are made available from a Web server for access by Web users
 or other Web-connected programs.

 Specific business functionality exposed by a company, usually
 through an Internet connection, for the purpose of providing a
 way for another company or software program to use the
 service.

 Types of Web Services:
Types of Web services
 Service-Oriented Web Services

   Based on “services”

   One service offers multiple functionalities

   “Big” Web Services

   JAX-WS = JAVA-API for XML-based Web Services, mainly using
    WSDL/SOAP

 Resource-Oriented Web Services

   Based on “resources”

   Resource - any directly accessible and distinguishable distributed
    component available on the network.

   RESTful Web Services

   JAX-RS = JAVA-API for RESTful Web Services, using only HTTP
Service Oriented Web Services - Architecture




   SOAP (Simple Object Access Protocol)
   WSDL (Web Services Definition Language)
   UDDI (Universal Discovery, Description and Integration)
Resource Oriented Web Services - Architecture


                                                                     Videos

                                                                     Images

                                                                        Text


 Resources

       Every distinguishable entity is a resource.

       A resource may be a Web site, an HTML page, an XML document, a
        Web service, an image, a video etc.
                                                      CRUD     HTTP Method
 URIs - Every resource is uniquely identified by a   Create   PUT or POST
  URI.                                                Read     GET, HEAD or OPTIONS

                                                      Update   PUT
 Resource lifecycle management using HTTP
  methods                                             Delete   DELETE
SOAP Web Service Vs RESTful Web Service
 SOAP


                                                                                  IBM




                                                                                1234.5




SOAP Request                                         SOAP Response
<?xml version="1.0"?>                                <?xml version="1.0"?>
<soap:Envelope                                       <soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-          xmlns:soap="http://www.w3.org/2001/12/soap-
envelope"                                            envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap   soap:encodingStyle="http://www.w3.org/2001/12/soap
-encoding">                                          -encoding">
  <soap:Body                                           <soap:Body
xmlns:m="http://www.example.org/stock">              xmlns:m="http://www.example.org/stock">
     <m:GetStockPrice>                                    <m:GetStockPriceResponse>
      <m:StockName>IBM</m:StockName>                        <m:Price>1234.5</m:Price>
    </m:GetStockPrice>                                    </m:GetStockPriceResponse>
  </soap:Body>                                         </soap:Body>
</soap:Envelope>                                     </soap:Envelope>
SOAP Web Service Vs RESTful Web Service
    REST



                                                                                 IBM




http://www.example.org/stock?name=IBM

                                <?xml version="1.0"?>                           1234.5
                                <stock>
                                 <name>IBM</name>
                                 <price>1234.5</price>
                                </stock>




 REST – HTTP Request                                 REST – XML Response
 http://www.example.org/stock?name=IBM               <?xml version="1.0"?> <stock>
                                                      <name>IBM</name>
                                                      <price>1234.5</price>
                                                     </stock>
SOAP Vs REST




                            Vs


 SOAP based web services
      Verbose => heavy payload
      Suitable for enterprise web services where you need
       interoperability, transactions, message delivery and reliability.
 RESTful web services
      Not verbose => needs less bandwidth
      Good to use for the mobile applications.
REST
 REST = REpresentational State Transfer

 Architectural style in which clients and servers
 exchange representations of resources by using a
 standardized interface and protocol.

 Principles of REST:

    Addressability (URI)
    Interface Uniformity (HTTP)
    Statelessness (HTTP)
    Connectedness (Hypermedia)
Why is it called "Representational State Transfer?"



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




                      <?xml version="1.0"?>
                      <aircraft>
                       <model>747</model>
                       <mfgYr>2000</mfgYr>
                      </aircraft>
Why is it called "Representational State Transfer?"



               http://www.boeing.com/aircraft/747/maintenanceSchedule




                            <?xml version="1.0"?>
                            <aircraft>
                             <model>747</model>
                             <mfgYr>2000</mfgYr>
                             <lastMntc>02-02-02<lastMntc>
                             <nextMntc>12-12-12<nextMntc>
                            </aircraft>
Why is it called "Representational State Transfer?"
1. The Client references a Web resource using a URL.

2. A representation of the resource is returned.

3. The representation (e.g., Boeing747.html) places the client in a new
   state.

4. When the client selects a hyperlink in Boeing747.html, it accesses
   another resource.

5. The new representation places the client application into yet
   another state.

6. Thus, the client application transfers state with each resource
   representation.


                           Roy T. Fielding     http://roy.gbiv.com
Building a Web Service
Building a Web Service
 Building blocks of a web service:
  Input(s)

  Data retrieval and processing function

  Output(s)

  Access path

  Access method
RESTful Web Services
 Web Services (data, functionality on server side) implemented using
  HTTP + REST principles

 Key elements of RESTful Web service are:

     The URI (path) of the Web Service
     The HTTP method supported by the web service.
     The MIME type of the request and response data supported by it.
JAX-RS
 Java API for RESTful Web Services

 Maintained through Java Specification Request –
  JSR311

 Has a set of annotations and associated classes and
  interfaces which simplify development of RESTful Web
  Services.

 Supports multiple data formats (JSON / XML / HTML /
  TEXT)
JAX-RS Implementations
 Jersey

 Restlet

 JBoss RESTEasy

 Apache CXF

 Triaxrs

 Apache Wink

 eXo
Important JAX-RS Annotations
Aspect                 Annotation      Scope    Description
                                                Sets the path to base URL + /resource_path.
                       @PATH
                                       Class,   The base URL is based on your application name,
URI                    (resource_pa
                                       Method   the servlet and the URL pattern from the
                       th)
                                                web.xml" configuration file.
Resource Method                                 Indicates that the method annotated with it will
                       @POST           Method
Designators                                     answer to a HTTP POST request
                                                Indicates that the method annotated with it will
 Rules:                @GET            Method
                                                answer to a HTTP GET request
1) Only one JAX-RS                              Indicates that the method annotated with it will
 method designation    @PUT            Method
                                                answer to a HTTP PUT request
 annotation is allowed
 per method in a Java
 class resource.                                Indicates that the method annotated with it will
2) Only public methods @DELETE         Method
                                                answer to a HTTP DELETE request
 may be exposed as
 resource methods
                       @Produces(
                                       Class,   @Produces defines which MIME type is returned
                       MediaType [,
                                       Method   by the resource.
                       more-types ])
 MIME type
                       @Consumes(
                                       Class,   @Consumes defines which MIME type is
                       MediaType [,
                                       Method   consumed by this resource.
                       more-types ])
Configuring Jersey
1. Include the following Jar files in the web project's library:
     jersey-core.jar, jersey-server.jar, jsr311-api.jar, asm.jar and jersey-
client.jar


2. Register Jersey as the servlet dispatcher for REST requests in the project’s
web.xml.


    <servlet>
       <servlet-name>ServletAdaptor</servlet-name>
       <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer
       </servlet-class>
       <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
       <servlet-name>ServletAdaptor</servlet-name>
       <url-pattern>/rs/*</url-pattern>
    </servlet-mapping>
RESTful - Resources
 With JAX-RS,

    Annotated POJOs = RESTful Web Services a.k.a
      Resources.

 Root Resource = POJO (Plain Old Java Object)
 annotated with @Path.

 Sub Resources = Methods within the Root POJO
 Resource
Sample RESTful Web Service
package com.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MultivaluedMap;

@Path("/customers")
public class Customers {
                                                                      Client Request
     // Get all customer details
                                                     GET / HTTP/1.1
     @GET                                            Host:
     public String getAllCustomers() {               http://localhost:8081/TestRestfulService/rs/
            return "list of customers";              customers
     }

     // Manage customer details
     @POST
     public void manageCustomers(@QueryParam("method") String method, MultivaluedMap<String,
     String> formParams) {
           if (method.equals("create")) {                         Client Request
                  //create new customer
                                                   POST / HTTP/1.1
           } else if (method.equals("update")) {   Host:
                  // update an existing customer   http://localhost:8081/TestRestfulService/rs/
           } else if (method.equals("delete")) {   customers?method=create
                  // delete a customer
           }                                       Id: 12345
                                                   Name: John
     }
}
Accessing resources using @Path
 Root Resource
      import javax.ws.rs.Path;

      @Path("/employeeinfo")
      public class EmployeeInfo {
        …….
      }


 Root Resource Path

 Syntax:
     http://your_domain:port/display-name/url-
 pattern/path_from_rest_class
 Example:
     http://localhost:8081/TestRestfulService/rs/employeeInfo
Accessing resources using @Path
 An @Path value is not required to have leading or trailing slashes (/)

      @Path(”/product/") = @Path(”/product”) = @Path("product”) =
                            @Path(”product/”)

 Automatic encoding

      @Path("product list") = @Path("product%20list”)

 URL Pattern and path template

      @Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
RESTful – Resources (Optional @Path sample)
 package com.example;

 import javax.ws.rs.GET;
 import javax.ws.rs.Path;
 import javax.ws.rs.POST;
 import javax.ws.rs.FormParam;

 @Path("/customers")
 public class Customers {
                                                                 Client Request
      // Get all customer details               GET / HTTP/1.1
      @GET                                      Host:
      public String getAllCustomers() {         http://localhost:8081/TestRestfulService/rs/
             return "list of customers";        customers
      }



      // Create a customer                                       Client Request
      @POST                                     POST / HTTP/1.1
      public void createCustomer(               Host:
            @FormParam("Id") int id,            http://localhost:8081/TestRestfulService/rs/
            @FormParam("Name") String name) {   customers
                  //create new customer         Id: 12345
      }                                         Name: John
 }
RESTful–Resources(Mandatory @Path sample)
 package com.example;

 import javax.ws.rs.GET;
 import javax.ws.rs.Path;
 import javax.ws.rs.POST;
 import javax.ws.rs.PathParam;

 @Path("/customers")
 public class Customers {                                           Client Request
                                                   GET / HTTP/1.1
      // Get all customer details                  Host:
      @GET                                         http://localhost:8081/TestRestfulService/rs/
      public String getAllCustomers() {            customers
             return "list of customers";
      }


                                                                    Client Request
      // Get specific customer details             GET / HTTP/1.1
      @GET                                         Host:
      @Path("{id}")                                http://localhost:8081/TestRestfulService/rs/
      public String getCustomer(@PathParam("id”)   customers/1234
             String id) {
             return "particular customer";
      }

 }
Hierarchical matching using @Path
package com.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import com.thoughtworks.xstream.XStream;

@Path("/customers")
public class Customers{                                                      Client Request
                                                            GET / HTTP/1.1
     @GET                                                   Host:
     public String getAllCustomers() {                      http://localhost:8081/TestRestfulService/rs/
           return "list of customers";                      customers
     }

     @GET
                                                                             Client Request
     @Path("/{id}")
     public String getCustomer(@PathParam("id") int id) {   GET / HTTP/1.1
                                                            Host:
           XStream xstream = new XStream();
                                                            http://localhost:8081/TestRestfulService/rs/
           Customer customer = new Customer(id);
                                                            customers/1234
           return xstream.toXml(customer);
     }

     @GET                                                                    Client Request
     @Path("/{id}/address")                                 GET / HTTP/1.1
     public String getAddress(@PathParam("id") int id) {    Host:
           Customer customer = new Customer(id);            http://localhost:8081/TestRestfulService/rs/
           return customer.getAddress();                    customers/1234/address
     }
}
RESTful – Sub Resources
 Sub Resource Methods
    POJO Methods annotated with a “resource method designator”
     annotation and with @Path annotation.
    Handles the HTTP request directly.
    @Path is optional for a sub resource method under the following
     conditions:
        If no. of methods per HTTP action = 1, then @Path is optional
        If no. of methods per HTTP action > 1, then all methods or all but
         one method should have @Path
 Sub Resource Locators
    POJO Methods annotated ONLY with @Path but NOT with any
     “resource method designator” annotation.
    Returns an object of the Sub Resource Class that will handle the
     HTTP request.
Examples of Sub Resources
package com.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/employeeinfo")
public class EmployeeInfo {

     // Subresource locator: obtains the subresource Employee from
     // the path /employeeinfo/employees/{fullName}
     @Path("/employees /{fullName}")
     public Employee getEmployee(@PathParam("fullName") String fullName) {
            Employee emp = new Employee(fullName);
            return emp;
     }

     // Subresource Method
     @GET
     @Path("/employees")
     public String getAllEmployees() {
           return "List of employees from sub resource method";
     }
}
Examples of Sub Resources (contd..)
package com.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

// Subresource class
public class Employee {

      private String fullName;

      public Employee(String fullName){
             this.fullName = fullName;
      }

      // Subresource method: returns the employee's first name
      @GET
      @Path("/firstname")
      public String getEmployeeFirstName() {
           return fullName.substring(0, fullName.indexOf(" ")==-1? fullName.length(): fullName.indexOf(" "));
      }

      // Subresource method: returns the employee's last name
      @GET
      @Path("/lastname")
      public String getEmployeeLastName() {
           if(fullName.indexOf(" ")==-1){
               return "No Last Name found";
           } else {
               return fullName.substring(fullName.indexOf(" ")+1);
           }
      }
}
Examples of Sub Resources (contd..)
 Request URL:
  http://localhost:8080/TestRestfulService/rs/employeeinfo/employees

    Output:
    List of employees from sub resource method
 Request URL:
  http://localhost:8080/TestRestfulService/rs/employeeinfo/employees/John/firstname

    Output:
    John
 Request URL:
  http://localhost:8080/TestRestfulService/rs/employeeinfo/employees/John Doe/lastname

    Output:
    Doe
 Request URL:
  http://localhost:8080/TestRestfulService/rs/employeeinfo/employees/John/lastname

    Output:
    No Last Name found
Extracting Request Parameters
                  Client Request                Path Param:
            POST / HTTP/1.1                     http://localhost:8080/TestRestfulService/rs/customer/12345
  HTTP      Host: http://www.amazon.com
            Cookie: x=56
  Header                                        Query Param:
            User-Agent: Mozilla
                                                http://localhost:8080/TestRestfulService/rs/employees?id=543
            Book: Da Vince Code
  Payload   Credit Card: Visa
(Form Data) Number: 123-45-6789                 Matrix Param:
                                                http://localhost:8080/TestRestfulService/rs/employees;role=ITA

                                                                                          Supported HTTP
   Annotation                         Description                        Data Source
                                                                                              Method
  @QueryParam      Extracts the value of a URI query parameter.         URI               GET, POST, PUT, or
                                                                                          DELETE
  @PathParam       Extracts the value of a URI template parameter.      URI               GET, POST, PUT, or
                                                                                          DELETE
  @MatrixParam     Extracts the value of a URI matrix parameter.        URI               GET, POST, PUT, or
                                                                                          DELETE
  @HeaderParam     Extracts the value of a HTTP header.                 Header of HTTP    GET, POST, PUT, or
                                                                        Request           DELETE
  @CookieParam     Extracts information from cookies declared in the    Header of HTTP    GET, POST, PUT, or
                   cookie request header.                               Request           DELETE

  @FormParam       Extracts information from a request representation   Payload of HTTP   Limited only to HTTP
                   whose content type is application/x-www-form-        Request           POST
                   urlencoded.
Extracting Request Parameters - Example

Annotation             HTTP Request & URL Sample                                   JAX-RS sample

@QueryParam    URL with query params:                                     public void foo(@QueryParam("x") int
               http://<host_name>:<port>/<context_root>/<servlet_path>/   numberX)
               MyService/URL?x=56

               GET /MyService/URL?x=56 HTTP/1.1
@PathParam     http://<host_name>:<port>/<context_root>/<servlet_path>/   @Path("URLPattern/{x}")
               MyService/URLPattern/56                                    public void foo(@PathParam("x") int
                                                                          numberX)
               GET /MyService/URLPattern/56 HTTP/1.1
@MatrixParam   URL with matrix params:                                    public void foo(@MatrixParam("x") int
               http://<host_name>:<port>/<context_root>/<servlet_path>/   numberX)
               MyService/URL;x=56

               GET /MyService/URL;x=56 HTTP/1.1
@HeaderParam   GET /MyService/URL HTTP/1.1                                public void foo(@HeaderParam("x") int
               x: 56                                                      numberX)
@CookieParam   GET /MyService/URL HTTP/1.1                                public void foo(@CookieParam("x") int
               Cookie: x=56                                               numberX)
Extracting Request Parameters - Example

 Annotation      HTTP Request                                      JAX-RS sample
                   Sample
@FormParam    The form parameters and     @POST
              values are encoded in the
              request message body        @Consumes("application/x-www-form-urlencoded")
              like the following:
                                          public void post(@FormParam(“x") int numberX) {
              POST /MyService/URL
              HTTP/1.1                    }
              x=56
                                                                   OR

                                          @POST

                                          @Consumes("application/x-www-form-urlencoded")

                                          public void post(MultivaluedMap<String, String> formParams) {

                                          }
Extracting Context Information - @Context
 To extract ServletConfig, ServletContext, HttpServletRequest and
HttpServletResponse from a Web application context

 Examples:
    @GET
    public String get(@Context UriInfo ui) {
         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();

        MultivaluedMap<String, String> pathParams = ui.getPathParameters();

    }


    @GET
    public String get(@Context HttpHeaders hh) {
         MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();

        Map<String, Cookie> pathParams = hh.getCookies();

    }
@DefaultValue
 Any failure to parse an input will result in the parameter being given whatever is
the default value for its type: false for boolean, zero for numbers, etc.

 This can be overridden by using @DefaultValue annotation and setting preferred
default value.

 This default value will be used whenever the expected input is missing – or when
it is present but parsing fails.

 The default value should be given as a String. It will be parsed to the appropriate
type of the method parameter.

Example:
         public void foo(@DefaultValue(“123”) @QueryParam(“id") int id)

         http://localhost:8081/TestRestfulService/rs/customer?id=56
          id = 56

         http://localhost:8081/TestRestfulService/rs/customer
          id = 123

         http://localhost:8081/TestRestfulService/rs/customer?id=ABC
          id = 123
Request Parameter – Data Types
 Both @QueryParam and @PathParam can be used only on the following
Java types:

     All primitive types except char

     All wrapper classes of primitive types except Character

     Any class with a constructor that accepts a single String argument

     Any class with the static method named valueOf(String) that accepts
      a single String argument

     List<T>, Set<T>, or SortedSet<T>, where T matches the already
      listed criteria.

 If @DefaultValue is not used in conjunction with @QueryParam, and the
query parameter is not present in the request, the value will be an empty
collection for List, Set, or SortedSet; null for other object types; and the
default for primitive types.
Entity Parameters
 A JAX-RS service method can define any number of parameters.

 All, or all but one, of those parameters must be annotated to inform
JAX-RS as to how to provide a value for it.

 The one not annotated, if present, is known as an entity, and is
implicitly bound to the request body. In other words, a non-annotated
parameter extracted from the request body is known as an entity.

 The JAX-RS specification does not permit more than one entity
parameter per method.
Entity Provider
 JAX-RS maps Java types to and from resource representations using entity
providers.

 JAX-RS entity providers help in the mapping between entities and
associated Java types.

 The two types of entity providers supported by JAX-RS are:

     MessageBodyReader: a class that is used to map an HTTP request
      entity body to method parameters
     MessageBodyWriter: a class that is used to map the return value to
      the HTTP response entity body.

 If a String value is used as the request entity parameter, the
MessageBodyReader entity provider deserializes the request body into a new
String.

 If a JAXB type is used as the return type on a resource method, the
MessageBodyWriter serializes the Java Architecture for XML Binding
(JAXB) object into the response body.
Entity Provider - Example
 For a resource method to return XML content, return an instance of a
JAXB class directly or return a javax.ws.rs.core.Response object with a JAXB
object as the response entity.

 Suppose that BookList is a JAXB class; for example:
    @GET
    @Produces("application/xml", "text/xml")
    public BookList getBookList() {
      BookList list = /* get a book list */
      return list;
    }

    Or

    @GET
    @Produces("application/xml", "text/xml")
    public javax.ws.rs.core.Response getBookList() {
      BookList list = /* get a book list */
      return Response.ok(list).build();
    }
JAX-RS Method Return Types
 void, resulting in an HTTP 204 (no content) response
 String
 Response, a JAX-RS class that allows the programmer to provide response
content and other metadata, including HTTP headers
 GenericEntity, another JAX-RS type whose job it is to represent type-
parameter information for a generic entity type (think List<MyClass>) at
runtime
 A valid entity type – that is to say, any other Java class will be perceived as
an entity by JAX-RS and converted by the same mechanism used for entity
parameters
 A sub-resource method may return any of the following types – these then
have entity providers pre-registered for them:
       byte[]
       java.io.InputStream
       java.io.Reader
       java.io.File
       javax.ws.rs.ext.StreamingOutput
       javax.activation.DataSource
Summary
 Web Services
 Web Service types
 REST
 JAX-RS
 JAX-RS annotations
 Jersey
 Restful Web Services
     Root Resource
     Sub Resources
     Accessing resources
     HTTP methods
     Extracting request (input) parameters
     Response types (output)
Quiz
1. REST in RESTful Web Services stands for
    a. Repetitive State Transfer
    b. Representational State Transfer
    c. Representational State Transformation
    d. Representational Scope Transfer

2. Which of the following annotation indicates a method’s return data type?
    a. @Accept
    b. @Produces
    c. @Consumes
    d. @POST

3. Which of the following is true about the annotation @FormParam?
    a. It can be used only for a POST Method’s
    b. It can be used only for GET Method’s
    c. It is used to retrieve the Query String in the URL of the HTTP
        Service
    d. Both B & C
Quiz
4. How do you specify a default value for a Query Param?
    a. It is not possible to specify a default value for a Query param. It’s
       always null.
    b. @QueryParam("version") String version = “1”
    c. @QueryParam("version") int version @DefaultValue("1")
    d. @DefaultValue("1") @QueryParam("version") String version

5.
@XXX
@Path("/update")
@Produces("application/xml")
public String updateCustomer(@FormParam("data") String data)
{
...
}
Which method call will be replaced with XXX in the above code?
    a. GET
    b. POST
    c. Both
    d. None
Quiz
6.

@Path("/customers")
public class Customers {

     @GET
     @Path("{id}")
     public String getCustomer(@PathParam("id”) String id) { …… }

     @POST
     @Path("{id}")
     public void deleteCustomer(@PathParam("id”) String id) { ….. }
}

Is this code correct? Will it compile and run?
Quiz - Answers
1. a
2. b
3. a
4. d
5. b
6. The code is correct and will compile. Though the paths of the sub
   resource methods are same, their HTTP method differ and hence this
   is a valid code.
Thank You!
Ad

More Related Content

What's hot (20)

What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
OECLIB Odisha Electronics Control Library
 
REST API
REST APIREST API
REST API
Tofazzal Ahmed
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
srividhyau
 
Rest API
Rest APIRest API
Rest API
Rohana K Amarakoon
 
Express js
Express jsExpress js
Express js
Manav Prasad
 
Rest web services
Rest web servicesRest web services
Rest web services
Paulo Gandra de Sousa
 
Expressjs
ExpressjsExpressjs
Expressjs
Yauheni Nikanovich
 
Integrating Microservices with Apache Camel
Integrating Microservices with Apache CamelIntegrating Microservices with Apache Camel
Integrating Microservices with Apache Camel
Christian Posta
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
Christopher Bartling
 
Postman
PostmanPostman
Postman
Igor Shubovych
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
Dong Ngoc
 
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
sanjoysanyal
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Testing RESTful web services with REST Assured
Testing RESTful web services with REST AssuredTesting RESTful web services with REST Assured
Testing RESTful web services with REST Assured
Bas Dijkstra
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST API
AmilaSilva13
 
Express node js
Express node jsExpress node js
Express node js
Yashprit Singh
 

Viewers also liked (20)

Web Service Presentation
Web Service PresentationWeb Service Presentation
Web Service Presentation
guest0df6b0
 
Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)
Peter R. Egli
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Testing web services
Testing web servicesTesting web services
Testing web services
Taras Lytvyn
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
Madhaiyan Muthu
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
Lorna Mitchell
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
Apigee | Google Cloud
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
Imran M Yousuf
 
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Shreeraj Shah
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA
psrpatnaik
 
Web services
Web servicesWeb services
Web services
Michael Weiss
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
Jussi Pohjolainen
 
Java Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesJava Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web Services
IMC Institute
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
 
Java web services using JAX-WS
Java web services using JAX-WSJava web services using JAX-WS
Java web services using JAX-WS
IndicThreads
 
SOAP-based Web Services
SOAP-based Web ServicesSOAP-based Web Services
SOAP-based Web Services
Katrien Verbert
 
Web Services - A brief overview
Web Services -  A brief overviewWeb Services -  A brief overview
Web Services - A brief overview
Raveendra Bhat
 
Restful web services by Sreeni Inturi
Restful web services by Sreeni InturiRestful web services by Sreeni Inturi
Restful web services by Sreeni Inturi
Sreeni I
 
REST to RESTful Web Service
REST to RESTful Web ServiceREST to RESTful Web Service
REST to RESTful Web Service
家弘 周
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
Prateek Tandon
 
Web Service Presentation
Web Service PresentationWeb Service Presentation
Web Service Presentation
guest0df6b0
 
Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)
Peter R. Egli
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Testing web services
Testing web servicesTesting web services
Testing web services
Taras Lytvyn
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
Madhaiyan Muthu
 
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Shreeraj Shah
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA
psrpatnaik
 
Java Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web ServicesJava Web Services [4/5]: Java API for XML Web Services
Java Web Services [4/5]: Java API for XML Web Services
IMC Institute
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
 
Java web services using JAX-WS
Java web services using JAX-WSJava web services using JAX-WS
Java web services using JAX-WS
IndicThreads
 
Web Services - A brief overview
Web Services -  A brief overviewWeb Services -  A brief overview
Web Services - A brief overview
Raveendra Bhat
 
Restful web services by Sreeni Inturi
Restful web services by Sreeni InturiRestful web services by Sreeni Inturi
Restful web services by Sreeni Inturi
Sreeni I
 
REST to RESTful Web Service
REST to RESTful Web ServiceREST to RESTful Web Service
REST to RESTful Web Service
家弘 周
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
Prateek Tandon
 
Ad

Similar to Restful Web Services (20)

5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
webhostingguy
 
Web servers
Web serversWeb servers
Web servers
webhostingguy
 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
webhostingguy
 
Web server
Web serverWeb server
Web server
Nirav Daraniya
 
Web architecture
Web architectureWeb architecture
Web architecture
Program in Interdisciplinary Computing
 
Introduction server Construction
Introduction server ConstructionIntroduction server Construction
Introduction server Construction
Jisu Park
 
RESTful services
RESTful servicesRESTful services
RESTful services
gouthamrv
 
Progressive web apps
Progressive web appsProgressive web apps
Progressive web apps
Fastly
 
The Evolving Security Environment For Web Services
The Evolving Security Environment For Web ServicesThe Evolving Security Environment For Web Services
The Evolving Security Environment For Web Services
Qanita Ahmad
 
CSG 2012
CSG 2012CSG 2012
CSG 2012
Scotty Logan
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
20521742
 
Introduction to WebServices
Introduction to WebServicesIntroduction to WebServices
Introduction to WebServices
AbdulImrankhan7
 
Web service- Guest Lecture at National Wokshop
Web service- Guest Lecture at National WokshopWeb service- Guest Lecture at National Wokshop
Web service- Guest Lecture at National Wokshop
Nishikant Taksande
 
Spider Course Day 1
Spider Course Day 1Spider Course Day 1
Spider Course Day 1
Harishankaran K
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Esri Web Applications February11 2011
Esri Web Applications February11 2011Esri Web Applications February11 2011
Esri Web Applications February11 2011
delmelle
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
Chalermpon Areepong
 
W-JAX Performance Workshop - Web and AJAX
W-JAX Performance Workshop - Web and AJAXW-JAX Performance Workshop - Web and AJAX
W-JAX Performance Workshop - Web and AJAX
Alois Reitbauer
 
Jsp & Ajax
Jsp & AjaxJsp & Ajax
Jsp & Ajax
Ang Chen
 
Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5
Charlin Agramonte
 
Introduction server Construction
Introduction server ConstructionIntroduction server Construction
Introduction server Construction
Jisu Park
 
RESTful services
RESTful servicesRESTful services
RESTful services
gouthamrv
 
Progressive web apps
Progressive web appsProgressive web apps
Progressive web apps
Fastly
 
The Evolving Security Environment For Web Services
The Evolving Security Environment For Web ServicesThe Evolving Security Environment For Web Services
The Evolving Security Environment For Web Services
Qanita Ahmad
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
20521742
 
Introduction to WebServices
Introduction to WebServicesIntroduction to WebServices
Introduction to WebServices
AbdulImrankhan7
 
Web service- Guest Lecture at National Wokshop
Web service- Guest Lecture at National WokshopWeb service- Guest Lecture at National Wokshop
Web service- Guest Lecture at National Wokshop
Nishikant Taksande
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Esri Web Applications February11 2011
Esri Web Applications February11 2011Esri Web Applications February11 2011
Esri Web Applications February11 2011
delmelle
 
W-JAX Performance Workshop - Web and AJAX
W-JAX Performance Workshop - Web and AJAXW-JAX Performance Workshop - Web and AJAX
W-JAX Performance Workshop - Web and AJAX
Alois Reitbauer
 
Jsp & Ajax
Jsp & AjaxJsp & Ajax
Jsp & Ajax
Ang Chen
 
Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5
Charlin Agramonte
 
Ad

More from Angelin R (17)

Comparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application Frameworks
Angelin R
 
[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube
Angelin R
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQube
Angelin R
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programming
Angelin R
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
A Slice of Me
A Slice of MeA Slice of Me
A Slice of Me
Angelin R
 
Team Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsTeam Leader - 30 Essential Traits
Team Leader - 30 Essential Traits
Angelin R
 
Action Script
Action ScriptAction Script
Action Script
Angelin R
 
Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM Methodology
Angelin R
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
Angelin R
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship Songs
Angelin R
 
Flex MXML Programming
Flex MXML ProgrammingFlex MXML Programming
Flex MXML Programming
Angelin R
 
Introduction to Adobe Flex
Introduction to Adobe FlexIntroduction to Adobe Flex
Introduction to Adobe Flex
Angelin R
 
Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)
Angelin R
 
Effective Team Work Model
Effective Team Work ModelEffective Team Work Model
Effective Team Work Model
Angelin R
 
Team Building Activities
Team Building ActivitiesTeam Building Activities
Team Building Activities
Angelin R
 
XStream
XStreamXStream
XStream
Angelin R
 
Comparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application Frameworks
Angelin R
 
[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube
Angelin R
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQube
Angelin R
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programming
Angelin R
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
A Slice of Me
A Slice of MeA Slice of Me
A Slice of Me
Angelin R
 
Team Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsTeam Leader - 30 Essential Traits
Team Leader - 30 Essential Traits
Angelin R
 
Action Script
Action ScriptAction Script
Action Script
Angelin R
 
Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM Methodology
Angelin R
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
Angelin R
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship Songs
Angelin R
 
Flex MXML Programming
Flex MXML ProgrammingFlex MXML Programming
Flex MXML Programming
Angelin R
 
Introduction to Adobe Flex
Introduction to Adobe FlexIntroduction to Adobe Flex
Introduction to Adobe Flex
Angelin R
 
Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)
Angelin R
 
Effective Team Work Model
Effective Team Work ModelEffective Team Work Model
Effective Team Work Model
Angelin R
 
Team Building Activities
Team Building ActivitiesTeam Building Activities
Team Building Activities
Angelin R
 

Recently uploaded (20)

How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 

Restful Web Services

  • 1. Restful web services By Angelin
  • 2. Widely Well-known “Words”  Internet  Massive network of networks, connecting millions of computers together globally.  Information communication using protocols like HTTP, SMTP, FTP etc  World Wide Web, or simply Web  A way of accessing information over the Internet using HTTP.
  • 3. World Wide Web  The Web as defined by Tim Berners-Lee consists of three elements:  URI (Uniform Resource Identifier) - The way of uniquely identifying resources on the network.  HTML (HyperText Markup Language) - The content format of resources to be returned.  HTTP (HyperText Transfer Protocol) - The protocol used to request a resource from the network and respond to requests.  HTTP methods All client server communication on the World Wide Web are done using the following simple HTTP methods:  GET = "give me some info" (Retrieve)  POST = "here's some info to update” (Update)  PUT = "here's some new info" (Create)  DELETE = "delete some info" (Delete)
  • 4. Retrieving Information using HTTP GET Client Request HTTP GET / HTTP/1.1 Header Host: http://www.amazon.com Amazon HTTP/1.1 200 OK Server: Microsoft-IIS/5.1 Web Content-Type: text/html; charset=utf-8 Server Content-Length: 8307 <html> <head> ... Server Response  The user types http://www.amazon.com in his browser.  The browser software creates and sends a HTTP request with a header that holds:  The desired action: GET ("get me resource")  The target machine (www.amazon.com)  The server responds with the requested resource which is rendered on the browser
  • 5. Updating Information using HTTP POST Client Request HTTP POST / HTTP/1.1 Header Host: http://www.amazon.com Payload Book: Da Vince Code (Form Data) Credit Card: Visa Number: 123-45-6789 Expiry: 12-04-06 Amazon HTTP/1.1 200 OK Web Server: Microsoft-IIS/5.1 Server Content-Type: text/html; charset=utf-8 Content-Length: 8307 <html> <body>Your order has been placed successfully!</body> </html> Server Response  The user fills in a form on the Web page and submits it.  The browser software creates and send a HTTP request with a header and a payload comprising of the form data.  The HTTP header identifies: • The desired action: POST • The target machine (amazon.com)  The payload contains: • The data being POSTed (the form data)  The server responds with the requested resource which is rendered on the browser
  • 6. Widely Well-known “Words” (Contd..)  Web Application  Usually a collection of dynamic web pages  Usually restricted to the intranet  Can be implemented as desktop application  Information accessible using front end user interfaces  Accessed by authorised users only  Web Site  Collection of static and dynamic web pages  Available on the internet, or an organization's intranet  Cannot be implemented as desktop application  Information accessible using front end user interfaces  Accessed by anybody
  • 7. Widely Well-known “Words” (Contd..)  Web Service  Application run by a web server, performing tasks and returning structured data to a calling program, rather than html for a browser.  Only “provides” information; does not “present” information  Publicly available and standardized for use by all programmers  Web Server  Software designed to serve web pages/web sites/web services. Examples are IIS, Apache, etc.
  • 8. Web Services  Services (usually some combination of program and data) that are made available from a Web server for access by Web users or other Web-connected programs.  Specific business functionality exposed by a company, usually through an Internet connection, for the purpose of providing a way for another company or software program to use the service.  Types of Web Services:
  • 9. Types of Web services  Service-Oriented Web Services  Based on “services”  One service offers multiple functionalities  “Big” Web Services  JAX-WS = JAVA-API for XML-based Web Services, mainly using WSDL/SOAP  Resource-Oriented Web Services  Based on “resources”  Resource - any directly accessible and distinguishable distributed component available on the network.  RESTful Web Services  JAX-RS = JAVA-API for RESTful Web Services, using only HTTP
  • 10. Service Oriented Web Services - Architecture  SOAP (Simple Object Access Protocol)  WSDL (Web Services Definition Language)  UDDI (Universal Discovery, Description and Integration)
  • 11. Resource Oriented Web Services - Architecture Videos Images Text  Resources  Every distinguishable entity is a resource.  A resource may be a Web site, an HTML page, an XML document, a Web service, an image, a video etc. CRUD HTTP Method  URIs - Every resource is uniquely identified by a Create PUT or POST URI. Read GET, HEAD or OPTIONS Update PUT  Resource lifecycle management using HTTP methods Delete DELETE
  • 12. SOAP Web Service Vs RESTful Web Service SOAP IBM 1234.5 SOAP Request SOAP Response <?xml version="1.0"?> <?xml version="1.0"?> <soap:Envelope <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap- xmlns:soap="http://www.w3.org/2001/12/soap- envelope" envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap soap:encodingStyle="http://www.w3.org/2001/12/soap -encoding"> -encoding"> <soap:Body <soap:Body xmlns:m="http://www.example.org/stock"> xmlns:m="http://www.example.org/stock"> <m:GetStockPrice> <m:GetStockPriceResponse> <m:StockName>IBM</m:StockName> <m:Price>1234.5</m:Price> </m:GetStockPrice> </m:GetStockPriceResponse> </soap:Body> </soap:Body> </soap:Envelope> </soap:Envelope>
  • 13. SOAP Web Service Vs RESTful Web Service REST IBM http://www.example.org/stock?name=IBM <?xml version="1.0"?> 1234.5 <stock> <name>IBM</name> <price>1234.5</price> </stock> REST – HTTP Request REST – XML Response http://www.example.org/stock?name=IBM <?xml version="1.0"?> <stock> <name>IBM</name> <price>1234.5</price> </stock>
  • 14. SOAP Vs REST Vs  SOAP based web services  Verbose => heavy payload  Suitable for enterprise web services where you need interoperability, transactions, message delivery and reliability.  RESTful web services  Not verbose => needs less bandwidth  Good to use for the mobile applications.
  • 15. REST  REST = REpresentational State Transfer  Architectural style in which clients and servers exchange representations of resources by using a standardized interface and protocol.  Principles of REST:  Addressability (URI)  Interface Uniformity (HTTP)  Statelessness (HTTP)  Connectedness (Hypermedia)
  • 16. Why is it called "Representational State Transfer?" http://www.boeing.com/aircraft/747 <?xml version="1.0"?> <aircraft> <model>747</model> <mfgYr>2000</mfgYr> </aircraft>
  • 17. Why is it called "Representational State Transfer?" http://www.boeing.com/aircraft/747/maintenanceSchedule <?xml version="1.0"?> <aircraft> <model>747</model> <mfgYr>2000</mfgYr> <lastMntc>02-02-02<lastMntc> <nextMntc>12-12-12<nextMntc> </aircraft>
  • 18. Why is it called "Representational State Transfer?" 1. The Client references a Web resource using a URL. 2. A representation of the resource is returned. 3. The representation (e.g., Boeing747.html) places the client in a new state. 4. When the client selects a hyperlink in Boeing747.html, it accesses another resource. 5. The new representation places the client application into yet another state. 6. Thus, the client application transfers state with each resource representation. Roy T. Fielding http://roy.gbiv.com
  • 19. Building a Web Service
  • 20. Building a Web Service  Building blocks of a web service: Input(s) Data retrieval and processing function Output(s) Access path Access method
  • 21. RESTful Web Services  Web Services (data, functionality on server side) implemented using HTTP + REST principles  Key elements of RESTful Web service are:  The URI (path) of the Web Service  The HTTP method supported by the web service.  The MIME type of the request and response data supported by it.
  • 22. JAX-RS  Java API for RESTful Web Services  Maintained through Java Specification Request – JSR311  Has a set of annotations and associated classes and interfaces which simplify development of RESTful Web Services.  Supports multiple data formats (JSON / XML / HTML / TEXT)
  • 23. JAX-RS Implementations  Jersey  Restlet  JBoss RESTEasy  Apache CXF  Triaxrs  Apache Wink  eXo
  • 24. Important JAX-RS Annotations Aspect Annotation Scope Description Sets the path to base URL + /resource_path. @PATH Class, The base URL is based on your application name, URI (resource_pa Method the servlet and the URL pattern from the th) web.xml" configuration file. Resource Method Indicates that the method annotated with it will @POST Method Designators answer to a HTTP POST request Indicates that the method annotated with it will Rules: @GET Method answer to a HTTP GET request 1) Only one JAX-RS Indicates that the method annotated with it will method designation @PUT Method answer to a HTTP PUT request annotation is allowed per method in a Java class resource. Indicates that the method annotated with it will 2) Only public methods @DELETE Method answer to a HTTP DELETE request may be exposed as resource methods @Produces( Class, @Produces defines which MIME type is returned MediaType [, Method by the resource. more-types ]) MIME type @Consumes( Class, @Consumes defines which MIME type is MediaType [, Method consumed by this resource. more-types ])
  • 25. Configuring Jersey 1. Include the following Jar files in the web project's library: jersey-core.jar, jersey-server.jar, jsr311-api.jar, asm.jar and jersey- client.jar 2. Register Jersey as the servlet dispatcher for REST requests in the project’s web.xml. <servlet> <servlet-name>ServletAdaptor</servlet-name> <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ServletAdaptor</servlet-name> <url-pattern>/rs/*</url-pattern> </servlet-mapping>
  • 26. RESTful - Resources  With JAX-RS, Annotated POJOs = RESTful Web Services a.k.a Resources.  Root Resource = POJO (Plain Old Java Object) annotated with @Path.  Sub Resources = Methods within the Root POJO Resource
  • 27. Sample RESTful Web Service package com.example; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.POST; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MultivaluedMap; @Path("/customers") public class Customers { Client Request // Get all customer details GET / HTTP/1.1 @GET Host: public String getAllCustomers() { http://localhost:8081/TestRestfulService/rs/ return "list of customers"; customers } // Manage customer details @POST public void manageCustomers(@QueryParam("method") String method, MultivaluedMap<String, String> formParams) { if (method.equals("create")) { Client Request //create new customer POST / HTTP/1.1 } else if (method.equals("update")) { Host: // update an existing customer http://localhost:8081/TestRestfulService/rs/ } else if (method.equals("delete")) { customers?method=create // delete a customer } Id: 12345 Name: John } }
  • 28. Accessing resources using @Path  Root Resource import javax.ws.rs.Path; @Path("/employeeinfo") public class EmployeeInfo { ……. }  Root Resource Path Syntax: http://your_domain:port/display-name/url- pattern/path_from_rest_class Example: http://localhost:8081/TestRestfulService/rs/employeeInfo
  • 29. Accessing resources using @Path  An @Path value is not required to have leading or trailing slashes (/) @Path(”/product/") = @Path(”/product”) = @Path("product”) = @Path(”product/”)  Automatic encoding @Path("product list") = @Path("product%20list”)  URL Pattern and path template @Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
  • 30. RESTful – Resources (Optional @Path sample) package com.example; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.POST; import javax.ws.rs.FormParam; @Path("/customers") public class Customers { Client Request // Get all customer details GET / HTTP/1.1 @GET Host: public String getAllCustomers() { http://localhost:8081/TestRestfulService/rs/ return "list of customers"; customers } // Create a customer Client Request @POST POST / HTTP/1.1 public void createCustomer( Host: @FormParam("Id") int id, http://localhost:8081/TestRestfulService/rs/ @FormParam("Name") String name) { customers //create new customer Id: 12345 } Name: John }
  • 31. RESTful–Resources(Mandatory @Path sample) package com.example; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.POST; import javax.ws.rs.PathParam; @Path("/customers") public class Customers { Client Request GET / HTTP/1.1 // Get all customer details Host: @GET http://localhost:8081/TestRestfulService/rs/ public String getAllCustomers() { customers return "list of customers"; } Client Request // Get specific customer details GET / HTTP/1.1 @GET Host: @Path("{id}") http://localhost:8081/TestRestfulService/rs/ public String getCustomer(@PathParam("id”) customers/1234 String id) { return "particular customer"; } }
  • 32. Hierarchical matching using @Path package com.example; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import com.thoughtworks.xstream.XStream; @Path("/customers") public class Customers{ Client Request GET / HTTP/1.1 @GET Host: public String getAllCustomers() { http://localhost:8081/TestRestfulService/rs/ return "list of customers"; customers } @GET Client Request @Path("/{id}") public String getCustomer(@PathParam("id") int id) { GET / HTTP/1.1 Host: XStream xstream = new XStream(); http://localhost:8081/TestRestfulService/rs/ Customer customer = new Customer(id); customers/1234 return xstream.toXml(customer); } @GET Client Request @Path("/{id}/address") GET / HTTP/1.1 public String getAddress(@PathParam("id") int id) { Host: Customer customer = new Customer(id); http://localhost:8081/TestRestfulService/rs/ return customer.getAddress(); customers/1234/address } }
  • 33. RESTful – Sub Resources  Sub Resource Methods  POJO Methods annotated with a “resource method designator” annotation and with @Path annotation.  Handles the HTTP request directly.  @Path is optional for a sub resource method under the following conditions:  If no. of methods per HTTP action = 1, then @Path is optional  If no. of methods per HTTP action > 1, then all methods or all but one method should have @Path  Sub Resource Locators  POJO Methods annotated ONLY with @Path but NOT with any “resource method designator” annotation.  Returns an object of the Sub Resource Class that will handle the HTTP request.
  • 34. Examples of Sub Resources package com.example; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; @Path("/employeeinfo") public class EmployeeInfo { // Subresource locator: obtains the subresource Employee from // the path /employeeinfo/employees/{fullName} @Path("/employees /{fullName}") public Employee getEmployee(@PathParam("fullName") String fullName) { Employee emp = new Employee(fullName); return emp; } // Subresource Method @GET @Path("/employees") public String getAllEmployees() { return "List of employees from sub resource method"; } }
  • 35. Examples of Sub Resources (contd..) package com.example; import javax.ws.rs.GET; import javax.ws.rs.Path; // Subresource class public class Employee { private String fullName; public Employee(String fullName){ this.fullName = fullName; } // Subresource method: returns the employee's first name @GET @Path("/firstname") public String getEmployeeFirstName() { return fullName.substring(0, fullName.indexOf(" ")==-1? fullName.length(): fullName.indexOf(" ")); } // Subresource method: returns the employee's last name @GET @Path("/lastname") public String getEmployeeLastName() { if(fullName.indexOf(" ")==-1){ return "No Last Name found"; } else { return fullName.substring(fullName.indexOf(" ")+1); } } }
  • 36. Examples of Sub Resources (contd..)  Request URL: http://localhost:8080/TestRestfulService/rs/employeeinfo/employees Output: List of employees from sub resource method  Request URL: http://localhost:8080/TestRestfulService/rs/employeeinfo/employees/John/firstname Output: John  Request URL: http://localhost:8080/TestRestfulService/rs/employeeinfo/employees/John Doe/lastname Output: Doe  Request URL: http://localhost:8080/TestRestfulService/rs/employeeinfo/employees/John/lastname Output: No Last Name found
  • 37. Extracting Request Parameters Client Request Path Param: POST / HTTP/1.1 http://localhost:8080/TestRestfulService/rs/customer/12345 HTTP Host: http://www.amazon.com Cookie: x=56 Header Query Param: User-Agent: Mozilla http://localhost:8080/TestRestfulService/rs/employees?id=543 Book: Da Vince Code Payload Credit Card: Visa (Form Data) Number: 123-45-6789 Matrix Param: http://localhost:8080/TestRestfulService/rs/employees;role=ITA Supported HTTP Annotation Description Data Source Method @QueryParam Extracts the value of a URI query parameter. URI GET, POST, PUT, or DELETE @PathParam Extracts the value of a URI template parameter. URI GET, POST, PUT, or DELETE @MatrixParam Extracts the value of a URI matrix parameter. URI GET, POST, PUT, or DELETE @HeaderParam Extracts the value of a HTTP header. Header of HTTP GET, POST, PUT, or Request DELETE @CookieParam Extracts information from cookies declared in the Header of HTTP GET, POST, PUT, or cookie request header. Request DELETE @FormParam Extracts information from a request representation Payload of HTTP Limited only to HTTP whose content type is application/x-www-form- Request POST urlencoded.
  • 38. Extracting Request Parameters - Example Annotation HTTP Request & URL Sample JAX-RS sample @QueryParam URL with query params: public void foo(@QueryParam("x") int http://<host_name>:<port>/<context_root>/<servlet_path>/ numberX) MyService/URL?x=56 GET /MyService/URL?x=56 HTTP/1.1 @PathParam http://<host_name>:<port>/<context_root>/<servlet_path>/ @Path("URLPattern/{x}") MyService/URLPattern/56 public void foo(@PathParam("x") int numberX) GET /MyService/URLPattern/56 HTTP/1.1 @MatrixParam URL with matrix params: public void foo(@MatrixParam("x") int http://<host_name>:<port>/<context_root>/<servlet_path>/ numberX) MyService/URL;x=56 GET /MyService/URL;x=56 HTTP/1.1 @HeaderParam GET /MyService/URL HTTP/1.1 public void foo(@HeaderParam("x") int x: 56 numberX) @CookieParam GET /MyService/URL HTTP/1.1 public void foo(@CookieParam("x") int Cookie: x=56 numberX)
  • 39. Extracting Request Parameters - Example Annotation HTTP Request JAX-RS sample Sample @FormParam The form parameters and @POST values are encoded in the request message body @Consumes("application/x-www-form-urlencoded") like the following: public void post(@FormParam(“x") int numberX) { POST /MyService/URL HTTP/1.1 } x=56 OR @POST @Consumes("application/x-www-form-urlencoded") public void post(MultivaluedMap<String, String> formParams) { }
  • 40. Extracting Context Information - @Context  To extract ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse from a Web application context  Examples: @GET public String get(@Context UriInfo ui) { MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); MultivaluedMap<String, String> pathParams = ui.getPathParameters(); } @GET public String get(@Context HttpHeaders hh) { MultivaluedMap<String, String> headerParams = hh.getRequestHeaders(); Map<String, Cookie> pathParams = hh.getCookies(); }
  • 41. @DefaultValue  Any failure to parse an input will result in the parameter being given whatever is the default value for its type: false for boolean, zero for numbers, etc.  This can be overridden by using @DefaultValue annotation and setting preferred default value.  This default value will be used whenever the expected input is missing – or when it is present but parsing fails.  The default value should be given as a String. It will be parsed to the appropriate type of the method parameter. Example: public void foo(@DefaultValue(“123”) @QueryParam(“id") int id) http://localhost:8081/TestRestfulService/rs/customer?id=56  id = 56 http://localhost:8081/TestRestfulService/rs/customer  id = 123 http://localhost:8081/TestRestfulService/rs/customer?id=ABC  id = 123
  • 42. Request Parameter – Data Types  Both @QueryParam and @PathParam can be used only on the following Java types:  All primitive types except char  All wrapper classes of primitive types except Character  Any class with a constructor that accepts a single String argument  Any class with the static method named valueOf(String) that accepts a single String argument  List<T>, Set<T>, or SortedSet<T>, where T matches the already listed criteria.  If @DefaultValue is not used in conjunction with @QueryParam, and the query parameter is not present in the request, the value will be an empty collection for List, Set, or SortedSet; null for other object types; and the default for primitive types.
  • 43. Entity Parameters  A JAX-RS service method can define any number of parameters.  All, or all but one, of those parameters must be annotated to inform JAX-RS as to how to provide a value for it.  The one not annotated, if present, is known as an entity, and is implicitly bound to the request body. In other words, a non-annotated parameter extracted from the request body is known as an entity.  The JAX-RS specification does not permit more than one entity parameter per method.
  • 44. Entity Provider  JAX-RS maps Java types to and from resource representations using entity providers.  JAX-RS entity providers help in the mapping between entities and associated Java types.  The two types of entity providers supported by JAX-RS are:  MessageBodyReader: a class that is used to map an HTTP request entity body to method parameters  MessageBodyWriter: a class that is used to map the return value to the HTTP response entity body.  If a String value is used as the request entity parameter, the MessageBodyReader entity provider deserializes the request body into a new String.  If a JAXB type is used as the return type on a resource method, the MessageBodyWriter serializes the Java Architecture for XML Binding (JAXB) object into the response body.
  • 45. Entity Provider - Example  For a resource method to return XML content, return an instance of a JAXB class directly or return a javax.ws.rs.core.Response object with a JAXB object as the response entity.  Suppose that BookList is a JAXB class; for example: @GET @Produces("application/xml", "text/xml") public BookList getBookList() { BookList list = /* get a book list */ return list; } Or @GET @Produces("application/xml", "text/xml") public javax.ws.rs.core.Response getBookList() { BookList list = /* get a book list */ return Response.ok(list).build(); }
  • 46. JAX-RS Method Return Types  void, resulting in an HTTP 204 (no content) response  String  Response, a JAX-RS class that allows the programmer to provide response content and other metadata, including HTTP headers  GenericEntity, another JAX-RS type whose job it is to represent type- parameter information for a generic entity type (think List<MyClass>) at runtime  A valid entity type – that is to say, any other Java class will be perceived as an entity by JAX-RS and converted by the same mechanism used for entity parameters  A sub-resource method may return any of the following types – these then have entity providers pre-registered for them:  byte[]  java.io.InputStream  java.io.Reader  java.io.File  javax.ws.rs.ext.StreamingOutput  javax.activation.DataSource
  • 47. Summary  Web Services  Web Service types  REST  JAX-RS  JAX-RS annotations  Jersey  Restful Web Services  Root Resource  Sub Resources  Accessing resources  HTTP methods  Extracting request (input) parameters  Response types (output)
  • 48. Quiz 1. REST in RESTful Web Services stands for a. Repetitive State Transfer b. Representational State Transfer c. Representational State Transformation d. Representational Scope Transfer 2. Which of the following annotation indicates a method’s return data type? a. @Accept b. @Produces c. @Consumes d. @POST 3. Which of the following is true about the annotation @FormParam? a. It can be used only for a POST Method’s b. It can be used only for GET Method’s c. It is used to retrieve the Query String in the URL of the HTTP Service d. Both B & C
  • 49. Quiz 4. How do you specify a default value for a Query Param? a. It is not possible to specify a default value for a Query param. It’s always null. b. @QueryParam("version") String version = “1” c. @QueryParam("version") int version @DefaultValue("1") d. @DefaultValue("1") @QueryParam("version") String version 5. @XXX @Path("/update") @Produces("application/xml") public String updateCustomer(@FormParam("data") String data) { ... } Which method call will be replaced with XXX in the above code? a. GET b. POST c. Both d. None
  • 50. Quiz 6. @Path("/customers") public class Customers { @GET @Path("{id}") public String getCustomer(@PathParam("id”) String id) { …… } @POST @Path("{id}") public void deleteCustomer(@PathParam("id”) String id) { ….. } } Is this code correct? Will it compile and run?
  • 51. Quiz - Answers 1. a 2. b 3. a 4. d 5. b 6. The code is correct and will compile. Though the paths of the sub resource methods are same, their HTTP method differ and hence this is a valid code.