REST - Basics
Srividhya Umashanker
We are talking about ……   1.   Introduction
                                 •   Webservices, SOAP,vs REST
                          2.   Spring – Rest, JSON
                                 •   REST using Spring
                                 •   Annotations
                                 •   REST example with Spring
Introduction
               1.   Webservices
               2.   SOAP
               3.   What is REST?
               4.   SOAP vs REST
               5.   REST in Detail
                    •   Frameworks,
                    •   HTTP Methods,
                    •   HTTP Headers
                    •   Status Code
Web Services!!
•   Exposing existing software over the web (HTTP)
•   Deployed independent of the OS and Programming Languages
•   Standardized Protocol
•   Easily connecting Different Applications i.e., Interoperability
•   Low Cost of communication

                                        Service request
                                       validateCreditCard
                                    Number-1828282828282828   Server
                                                                        ICICI Bank
                    ebay.com                                           Credit Card
                                                                       Web Service
                                      Service Response
                                    “Name does not match”
SOAP?
Simple Object Access Protocol




• A simple XML-based protocol to let applications exchange information
  over HTTP.
• WSDL defines endpoint, i/o format, security etc

• Example : getUser(userName);
What is REST? - Rest Triangle
• REST is a new and improved form of web             Nouns :
  services.                                          http://localhost/rest/user/123
• Introduced as SOAP is complex                      4

• There isn’t a standard for REST architectures
• Expose directory structure-like URIs
• Used to expose a public API over the internet
  to handle CRUD operations on data.
• Works on Nouns, Verbs, Content Types
                                                Content Types                 Verbs
                                                   JSON, XML, HTML….        GET, POST
                                                                            ….
GET /server/1234
POST /server?name=SERVER-1&id=1234
SOA vs REST – The right webservice




                GET /user/Robert
                GET /adduser?name=Robert   getUser(userName);
Rest Frameworks – List


 Apache CXF
 Jersey
 Rest Easy
 Restlet
 Spring MVC
HTTP METHODS – CRUD in REST

Methods   CRUD                Example
          Fetch all or any    GET /user/ - Fetch all
GET
          resource            GET /user/1 – Fetch User 1
POST      Create a Resource   POST /user?name=user1&age=20
                              PUT /user/1? name=changed-
PUT       Update a Resource
                              user1&age=22
DELETE    Delete a Resource   DELETE /user/1
          Fetch Metainfo as
HEAD                          HEAD /user
          header
          Fetch all VERBS
OPTIONS                       OPTIONS /user
          allowed
HTTP Headers - To remember


  Headers                Example
  Auth:<session-token>   Auth:1ajkdsdajsd922j-w8eis0-jssjss
                         Session token by logging in to Atlas
  Accept:<media Type>    accept: application/json – Default
  Content-Type           content-type:application/json
  Allow:                 Which method requests are allowed by the server
HTTP Status Codes    To Remember - Status
                           Codes

                    200 – OK                  Successful Return for sync call

                    307 – Temporarily Moved   Redirection

                    400 – Bad Request         Invalid URI, header, request param

                    401 – Un authorized       User not authorized for operation

                    403 – Forbidden           User not allowed to update

                    404 – Not Found           URI Path not available

                    405 – Method not
                                              Method not valid for the path
                    allowed
                    500 – Internal Server
                                              Server Errors
                    Error
                    503 – Service
                                              Server not accessible
                    unavailable
Spring 3 - REST

             •    Spring Framework - Introduction
             •    Dispatcher Servlet
             •    Flow - Rest calls in Spring
             •    Annotations for REST
             •    REST Example with Spring
Spring Framework

• The Spring Framework is an opensource, lightweight, Aspect based
  Inversion of Control container for the Java platform

• helps "wire" different components together.

• Spring's REST support is based upon Spring's annotation-based MVC
  framework

• configure your servlet container as you would for a Spring MVC application
  using Spring's DispatcherServlet.
http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch18.html
Dispatcher Servlet
                     <web-app>
                          <servlet>
                                  <servlet-name>rest</servlet-name>
                                  <servlet-class>
                                       org.springframework.web.servlet.DispatcherServlet
                                  </servlet-class>
                                  <load-on-startup>1</load-on-startup>
                          </servlet>
                          <servlet-mapping>
                                  <servlet-name>rest</servlet-name>
                                  <url-pattern>/rest/*</url-pattern>
                          </servlet-mapping>
                     </web-app>
Flow – REST calls in Spring
                    HTTP Request
    Rest Template
                                    Dispatcher
                                      Servlet
                                         @ResponseBody
     Client Calls   HTTP Response
                                                  Jackson
                                                  Converter
                                    @Controller




                                     @Service                 DB
Rest Template

     Spring Framework’s RestTemplate provides simple ways to make requests to
     RESTful services.

     Allows all REST METHODS – GET, POST, DELETE, PUT, HEAD, OPTIONS
Spring Annotations for REST
 Annotations     Usage
                                              Example showing Annotations

                 mark the class as a MVC
@Controller                                   @Controller
                 controller
                                              @RequestMapping(value = “/ilo”)
@RequestMappi
                 Maps the request with path   public class iLOController
ng
                                              {
                                                  @RequestMapping(value = “/server/{id}”, method = RequestMethod.GET)
@PathVariable    Map variable from the path
                                                  public @ResponseBody Book getServer(@PathVariable String id) {
                                                       System.out.println(“------Gettting Server ------”+id);
                 unmarshalls the HTTP
                 response body into a Java        }
@RequestBody
                 object injected in the               ……
                 method.                              ……..
                                              }
                 marshalls return value as
@ResponseBody
                 HTTP Response

@Configuration   Spring Config as a class
JSON
Javascript Object Notation

  •   Lightweight Data Interchange Format – No tags
  •   Easy to parse and create
  •   Supports objects and Arrays
  •   We use Jackson Framework for JSON conversions

                            JSON Example:
                                       {
                                         “servers": [
                                             { “name":“server1" , “category":“Blade" },




                                                               A
                               Array    A { “name":“Server2" , “category":“DL360" },
                                             { “name":“Server3" , “category":“DL480" }
                                          ]
                                       }                    Object
We are Done!

Rest presentation

  • 1.
  • 2.
    We are talkingabout …… 1. Introduction • Webservices, SOAP,vs REST 2. Spring – Rest, JSON • REST using Spring • Annotations • REST example with Spring
  • 3.
    Introduction 1. Webservices 2. SOAP 3. What is REST? 4. SOAP vs REST 5. REST in Detail • Frameworks, • HTTP Methods, • HTTP Headers • Status Code
  • 4.
    Web Services!! • Exposing existing software over the web (HTTP) • Deployed independent of the OS and Programming Languages • Standardized Protocol • Easily connecting Different Applications i.e., Interoperability • Low Cost of communication Service request validateCreditCard Number-1828282828282828 Server ICICI Bank ebay.com Credit Card Web Service Service Response “Name does not match”
  • 5.
    SOAP? Simple Object AccessProtocol • A simple XML-based protocol to let applications exchange information over HTTP. • WSDL defines endpoint, i/o format, security etc • Example : getUser(userName);
  • 6.
    What is REST?- Rest Triangle • REST is a new and improved form of web Nouns : services. http://localhost/rest/user/123 • Introduced as SOAP is complex 4 • There isn’t a standard for REST architectures • Expose directory structure-like URIs • Used to expose a public API over the internet to handle CRUD operations on data. • Works on Nouns, Verbs, Content Types Content Types Verbs JSON, XML, HTML…. GET, POST …. GET /server/1234 POST /server?name=SERVER-1&id=1234
  • 7.
    SOA vs REST– The right webservice GET /user/Robert GET /adduser?name=Robert getUser(userName);
  • 8.
    Rest Frameworks –List Apache CXF Jersey Rest Easy Restlet Spring MVC
  • 9.
    HTTP METHODS –CRUD in REST Methods CRUD Example Fetch all or any GET /user/ - Fetch all GET resource GET /user/1 – Fetch User 1 POST Create a Resource POST /user?name=user1&age=20 PUT /user/1? name=changed- PUT Update a Resource user1&age=22 DELETE Delete a Resource DELETE /user/1 Fetch Metainfo as HEAD HEAD /user header Fetch all VERBS OPTIONS OPTIONS /user allowed
  • 10.
    HTTP Headers -To remember Headers Example Auth:<session-token> Auth:1ajkdsdajsd922j-w8eis0-jssjss Session token by logging in to Atlas Accept:<media Type> accept: application/json – Default Content-Type content-type:application/json Allow: Which method requests are allowed by the server
  • 11.
    HTTP Status Codes To Remember - Status Codes 200 – OK Successful Return for sync call 307 – Temporarily Moved Redirection 400 – Bad Request Invalid URI, header, request param 401 – Un authorized User not authorized for operation 403 – Forbidden User not allowed to update 404 – Not Found URI Path not available 405 – Method not Method not valid for the path allowed 500 – Internal Server Server Errors Error 503 – Service Server not accessible unavailable
  • 12.
    Spring 3 -REST • Spring Framework - Introduction • Dispatcher Servlet • Flow - Rest calls in Spring • Annotations for REST • REST Example with Spring
  • 13.
    Spring Framework • TheSpring Framework is an opensource, lightweight, Aspect based Inversion of Control container for the Java platform • helps "wire" different components together. • Spring's REST support is based upon Spring's annotation-based MVC framework • configure your servlet container as you would for a Spring MVC application using Spring's DispatcherServlet. http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch18.html
  • 14.
    Dispatcher Servlet <web-app> <servlet> <servlet-name>rest</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
  • 15.
    Flow – RESTcalls in Spring HTTP Request Rest Template Dispatcher Servlet @ResponseBody Client Calls HTTP Response Jackson Converter @Controller @Service DB
  • 16.
    Rest Template Spring Framework’s RestTemplate provides simple ways to make requests to RESTful services. Allows all REST METHODS – GET, POST, DELETE, PUT, HEAD, OPTIONS
  • 17.
    Spring Annotations forREST Annotations Usage Example showing Annotations mark the class as a MVC @Controller @Controller controller @RequestMapping(value = “/ilo”) @RequestMappi Maps the request with path public class iLOController ng { @RequestMapping(value = “/server/{id}”, method = RequestMethod.GET) @PathVariable Map variable from the path public @ResponseBody Book getServer(@PathVariable String id) { System.out.println(“------Gettting Server ------”+id); unmarshalls the HTTP response body into a Java } @RequestBody object injected in the …… method. …….. } marshalls return value as @ResponseBody HTTP Response @Configuration Spring Config as a class
  • 18.
    JSON Javascript Object Notation • Lightweight Data Interchange Format – No tags • Easy to parse and create • Supports objects and Arrays • We use Jackson Framework for JSON conversions JSON Example: { “servers": [ { “name":“server1" , “category":“Blade" }, A Array A { “name":“Server2" , “category":“DL360" }, { “name":“Server3" , “category":“DL480" } ] } Object
  • 19.

Editor's Notes

  • #5 Webservices running on Linux and jbosscan be consumed from Windows .NET based applicationWebervices makes it easy to talk to each other
  • #9 Jersey is the JAX-RS Implementation
  • #10 A HEAD request is just like a GET request, except it asks the server to return the response headers only, The response to a HEAD request must never contain a message body, just the status line and headers.
  • #14 &quot;Dependency injection is where you design your classes so that they expect an outside actor to directly give them the sub-tools they need to do their jobs before anybody starts asking them to do something.“Annotations – adding metadata to the java elements like class, interfaces, methodsSpring uses annotations as an alternative to XML for declarative configuration
  • #15 The DispatcherServlet consults the HandleMapping component to dispatch a request to a Controller.The BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext interface builds on top of theBeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring&apos;s AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in web applications.
  • #16 What is Jackson,
  • #18 TODO - What are annotations?