SlideShare a Scribd company logo
1 of 49
Download to read offline
Spring MVC to iOS and the REST

Roy Clarkson, Senior Engineer, VMware
Twitter/GitHub: @royclarkson

Josh Long, Spring Developer Advocate
Twitter: @starbuxman GitHub: @joshlong


© 2013 SpringSource, by VMware
About Roy Clarkson


•   Georgia Tech Alum
•   SpringSource Engineer at VMware
•   Lead on Spring for Android and Spring Mobile
•   Twitter/GitHub: @royclarkson
•   rclarkson@vmware.com
•   http://www.slideshare.net/royclarkson




2
About Josh Long (⻰龙之春)
Spring Developer Advocate
twitter: @starbuxman
weibo: @springsource
josh.long@springsource.com




                             3
About Josh Long

Spring Developer Advocate
twitter: @starbuxman
josh.long@springsource.com

Contributor To:

•Spring Integration
•Spring Batch
•Spring Hadoop
•Activiti Workflow Engine




4
Agenda


•   REST
•   Spring MVC
•   iOS
•   Demos




5
The term Representational State Transfer was introduced and
      defined in 2000 by Roy Fielding in his doctoral dissertation.




6
What is REST?


• REpresentational State Transfer
• An architectural style for designing distributed systems
• Not a standard, but rather a set of constraints
    – Client/Server, Stateless, Uniform Interface, etc.
• Not tied to HTTP, but associated most commonly with it




7
The Principles of REST


• Resources
    – Expose directory structure-like URIs
    – URI’s should be easily understood
• Representations
    – Transfer XML, JavaScript Object Notation (JSON), or both
    – Use XML or JSON to represent data objects or attributes
• Messages
    – Use HTTP methods explicitly (i.e. POST, GET, PUT,
      DELETE)
    – CRUD operations can be mapped to these existing methods
• Stateless
    – State dependencies limit or restrict scalability

8
What is HATEOAS?


• Hypermedia As The Engine Of Application State
• The client doesn’t have a built in knowledge of how to
  navigate and manipulate the model
• Instead server provides that information dynamically to the
  user
• Implemented by using media types and link relations




9
HTTP GET


• Retrieve information
     – Must be safe and idempotent
• Can have side effects, but since the user doesn’t expect
  them, they shouldn’t be critical to the operation of the
  system
• GET can be conditional or partial
     – If-Modified-Since
     – Range



 GET /pizzas/1


10
HTTP DELETE


• Request that a resource be removed
• The resource doesn’t have to be removed immediately
     – Removal may be a long running task




 DELETE /pizzas/1


11
HTTP PUT


• Requests that the entity passed be stored at the URI
• Can be used to create a new entity or modify an existing
  one
     – Creation of new entities is uncommon as it allows the client
       to select the id of the new entity




 PUT /toppings/1
 { “name” : “Cheese” }


12
HTTP POST


• Requests that the resource at a URI do something with the
  enclosed entity
• The major difference between POST and PUT are what
  resource the request URI identifies
• For example, use PUT to create and POST to modify




 POST /toppings/1
 { “name” : “Cheddar Cheese” }


13
HTTP Status Codes


• Status codes are an indicator the result of the server’s
  attempt to satisfy the request
• Broadly divided in categories
     –   1XX: Informational
     –   2XX: Success
     –   3XX: Redirection
     –   4XX: Client Error
     –   5XX: Server Error




14
Success Status Codes


• 200 OK
     – Everything worked
• 201 Created
     – The server has successfully created a new resource
     – Newly created resource’s location returned in the Location
       header
• 202 Accepted
     – The server has accepted the request, but it is not yet
       complete
     – A location to determine the request’s current status can be
       returned in the Location header



15
Client Error Status Codes


• 400 Bad Request
     – Malformed Syntax
     – Should not be repeated without modification
• 401 Unauthorized
     – Authentication is required
     – Includes a WWW-Authenticate header
• 403 Forbidden
     – Server has understood, but refuses to honor the request
     – Should not be repeated without modification




16
Client Error Status Codes


• 404 Not Found
     – The server cannot find a resource matching a URI
• 406 Not Acceptable
     – The server can only return response entities that do not
       match the client’s Accept header
• 409 Conflict
     – The resource is in a state that is in conflict with the request
     – Client should attempt to rectify the conflict and then resubmit
       the request




17
Media Types


• Accept & Content-Type HTTP Headers
• Client or server describes the content




18
Spring Web MVC DispatcherServlet




20
Annotations of Spring MVC


•    @Controller
•    @RequestMapping
•    @RequestParam
•    @PathVariable
•    @ResponseBody
•    @RequestBody
•    @ResponseStatus




21
@Controller


@Controller
public class PizzaController {
...
}




22
@RequestMapping


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

     // POST /pizzas/bake
     @RequestMapping(value = "/bake", method = POST)
	    public void bake() {
        ...
	    }
}




23
@RequestParam


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

     // POST /pizzas/bake?temp=400
     @RequestMapping(value = "/bake", method = POST)
	    public void bake(@RequestParam Integer temp) {
	    	 ...
	    }
}




24
@PathVariable


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

	    // POST /pizzas/bake/400
	    @RequestMapping(value = "/bake/{temp}", method = POST)
	    public void bake(@PathVariable Integer temp) {
	    	 ...
	    }
}




25
@ResponseBody


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

	    // GET /pizzas
	    @RequestMapping(
	    	 	 	 method = GET, produces = "application/json")
	    public @ResponseBody List<Pizza> list() {
	    	 ...
	    }
}




26
@ResponseBody


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

	    // GET /pizzas
	    @RequestMapping(method = GET,
	    	 	 	 produces = MediaType.APPLICATION_JSON_VALUE )
	    public @ResponseBody List<Pizza> list() {
	    	 ...
	    }
}




27
@RequestBody


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

	    // PUT /pizzas
	    @RequestMapping(
	    	 	 	 method = PUT, consumes = "application/json")
	    public void create(@RequestBody Pizza pizza) {
	    	 ...
	    }
}




28
@ResponseStatus


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

	    // PUT /pizzas
	    @ResponseStatus(HttpStatus.CREATED)
	    @RequestMapping(
	    	 	 	 method = PUT, consumes = "application/json")
	    public void create(@RequestBody Pizza pizza) {
	    	 ...
	    }
}




29
Async MVC Processing: Callable


@Controller
@RequestMapping("/pizzas")
public class PizzaController {

	    @RequestMapping(value = "/orders", method = POST)
	    @ResponseBody
     public Callable<String> upload(MultipartFile file) {
	    	 return new Callable<Pizza>() {
	    	 	 public Pizza call() throws Exception
	    	 	 // ...
	    	 	 return pizza;
	    	 }
	    }
}


30
Async MVC Processing: DeferredResult




 @RequestMapping("/quotes")
 @ResponseBody
 public DeferredResult quotes() {
   DeferredResult deferredResult = new DeferredResult();
   // Add deferredResult to a Queue or a Map...
   return deferredResult;
}

// In some other thread:
// Set the return value on the DeferredResult
deferredResult.set(data);


     - thread managed outside of Spring MVC
     - JMS or AMQP message listener, another HTTP request, etc.




                                                                  31
Async MVC Processing: AsyncTask


@RequestMapping(name =“/upload”,
method=RequestMethod.POST)
 public AsyncTask<Foo> processUpload(MultipartFile file) {

    TaskExecutor asyncTaskExecutor = new AsyncTaskExecutor(...);

    return new AsyncTask<Foo>(
        1000L,                   // timeout
        asyncTaskExecutor,       // thread pool
        new Callable<Foo>(){ ..} // thread
     );

}
     - same as Callable, with extra features
     - override timeout value for async processing
     - lets you specify a specific AsyncTaskExecutor


                                                               32
Message Converters


•    RSS/ATOM
•    java.awt.BufferedImage
•    JSON
•    JAXB

• Write your own!
     – iCal
     – GSON


• Third Party:
        • https://github.com/joshlong/spring-advanced-marhshallers-and-service-exporters
             – supports Google PB, Avro, Thrift, MessagePack, Google Snappy


33
Spring MVC Demo
Testing


• Testing of web APIs isn’t easy
     – In container, end-to-end, string comparison, etc.
     – Out of container, Java objects, bypassing much of Spring’s
       magic


• What we want is out of container, but with as much of
  Spring as we can get




35
Spring MVC Testing


• Available in Spring 3.2
• Bootstraps most of Spring’s MVC infrastructure so that
  you unit and integration test your web application end-to-
  end
• Provides APIs for testing interesting parts of requests and
  responses




36
REST on iOS


• HTTP Client
     – NSURLConnection


• JSON Processor (iOS 5)
     – NSJSONSerialization


• Data
     – NSData
     – NSDictionary
     – NSArray




38
NSURLConnection


• Loading Data Synchronously

     + sendSynchronousRequest:returningResponse:error:

• Loading Data Asynchronously

     + sendAsynchronousRequest:queue:completionHandler:




39
Basic HTTP Request


NSURL *url = [NSURL URLWithString:@"http://localhost"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];


NSData *data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:nil
                                                 error:nil];




40
Basic HTTP Request... Improved


NSURL *url = [NSURL URLWithString:@"http://localhost"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&response
                                                 error:&error];
NSInteger status = [(NSHTTPURLResponse *)response statusCode];
if (status == 200 && data.length > 0 && error == nil)
{
    // do something with data
}




41
Asynchronous HTTP Request


NSURL *url = [NSURL URLWithString:@"http://localhost"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[NSURLConnection
         sendAsynchronousRequest:request
                           queue:[NSOperationQueue mainQueue]
               completionHandler:^(NSURLResponse *response,
                                   NSData *data, NSError *error)
{
    NSInteger status = [(NSHTTPURLResponse *)response statusCode];
    if (status == 200 && data.length > 0 && error == nil)
    {
        // do something with data
    }
}




42
HTTP Headers


NSURL *url = [NSURL URLWithString:@"http://localhost"];
NSMutableURLRequest *request =
               [[NSMutableURLRequest alloc] initWithURL:url];

[request setHTTPMethod:@"PUT"];

[request setValue:@"application/json"
               forHTTPHeaderField:@"Accept"];

[request setValue:@"application/json"
               forHTTPHeaderField:@"Content-Type"];

[request setValue:contentLength
               forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody:postData];




43
JSON Serialization


// deserialize JSON data
NSError *error;
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data
                                                  options:0
                                                    error:&error];

// serialize JSON data
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
                                               options:0
                                                 error:&error];




44
iOS Demo
Conclusion


• API Design Matters
     – URIs represent resources, not actions
     – HTTP verbs are general, but can be used in ways that make
       anything possible
• Implementation isn’t rocket science
     – Spring MVC
     – Spring HATEOAS
• Easy testing
     – Out-of-container, but full Spring stack




46
More Information


• Roy Fielding’s Dissertation
  http://www.ics.uci.edu/~fielding/pubs/dissertation/
  evaluation.htm#sec_6_1%7C

• Spring MVC Reference
  http://static.springsource.org/spring-framework/docs/
  current/spring-framework-reference/html/mvc.html

• URL Loading System Programming Guide
  http://developer.apple.com/library/ios/#documentation/
  Cocoa/Conceptual/URLLoadingSystem/
  URLLoadingSystem.html


47
Related Spring Projects


• REST Shell
  https://github.com/SpringSource/rest-shell

• Spring HATEOAS
  https://github.com/SpringSource/spring-hateoas

• Spring MVC Test
  https://github.com/SpringSource/spring-test-mvc




48
Questions?


• All Sample Code:
  https://github.com/royclarkson/rest-demo
  https://github.com/joshlong/the-spring-tutorial

• Presentation:
  http://www.slideshare.net/royclarkson




49

More Related Content

What's hot

ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewShahed Chowdhuri
 
Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Navaneethan Naveen
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training sessionHrichi Mohamed
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
API Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNGAPI Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNGSiddharth Sharma
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servletvikram singh
 
ASP.NET 07 - Site Navigation
ASP.NET 07 - Site NavigationASP.NET 07 - Site Navigation
ASP.NET 07 - Site NavigationRandy Connolly
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Michal Balinski
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentationengcs2008
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafLAY Leangsros
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/OSimone Bordet
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 

What's hot (20)

ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training session
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Css lecture notes
Css lecture notesCss lecture notes
Css lecture notes
 
API Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNGAPI Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNG
 
Javascript
JavascriptJavascript
Javascript
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
 
ASP.NET 07 - Site Navigation
ASP.NET 07 - Site NavigationASP.NET 07 - Site Navigation
ASP.NET 07 - Site Navigation
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
Postman.ppt
Postman.pptPostman.ppt
Postman.ppt
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/O
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 

Viewers also liked

Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Ryan Cuprak
 
Azure Mobile Services (MBaaS) back-end-as-a-service
Azure Mobile Services (MBaaS) back-end-as-a-serviceAzure Mobile Services (MBaaS) back-end-as-a-service
Azure Mobile Services (MBaaS) back-end-as-a-serviceSandeep Joshi
 
Cross Platform Development with Spring
Cross Platform Development with SpringCross Platform Development with Spring
Cross Platform Development with SpringCygnet Infotech
 
Consuming web services asynchronously with Futures and Rx Observables (svcc, ...
Consuming web services asynchronously with Futures and Rx Observables (svcc, ...Consuming web services asynchronously with Futures and Rx Observables (svcc, ...
Consuming web services asynchronously with Futures and Rx Observables (svcc, ...Chris Richardson
 
Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightGiuseppe Arici
 
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...Ahmed Ali
 
Thinking in swift ppt
Thinking in swift pptThinking in swift ppt
Thinking in swift pptKeith Moon
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03) iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03) Jonathan Engelsma
 
iOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. SwiftiOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. SwiftAlex Cristea
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOSgillygize
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSJinkyu Kim
 
Spring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthySpring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthyRossen Stoyanchev
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresVisual Engineering
 
Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Ryan Cuprak
 

Viewers also liked (20)

Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
 
Azure Mobile Services (MBaaS) back-end-as-a-service
Azure Mobile Services (MBaaS) back-end-as-a-serviceAzure Mobile Services (MBaaS) back-end-as-a-service
Azure Mobile Services (MBaaS) back-end-as-a-service
 
Cross Platform Development with Spring
Cross Platform Development with SpringCross Platform Development with Spring
Cross Platform Development with Spring
 
Consuming web services asynchronously with Futures and Rx Observables (svcc, ...
Consuming web services asynchronously with Futures and Rx Observables (svcc, ...Consuming web services asynchronously with Futures and Rx Observables (svcc, ...
Consuming web services asynchronously with Futures and Rx Observables (svcc, ...
 
Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma Night
 
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
 
Ios - Intorduction to view controller
Ios - Intorduction to view controllerIos - Intorduction to view controller
Ios - Intorduction to view controller
 
Thinking in swift ppt
Thinking in swift pptThinking in swift ppt
Thinking in swift ppt
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
iOS (7) Workshop
iOS (7) WorkshopiOS (7) Workshop
iOS (7) Workshop
 
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03) iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
 
iOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. SwiftiOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. Swift
 
iOS: Table Views
iOS: Table ViewsiOS: Table Views
iOS: Table Views
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
 
Spring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and NoteworthySpring MVC 4.2: New and Noteworthy
Spring MVC 4.2: New and Noteworthy
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - Structures
 
Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]
 

Similar to Spring MVC to iOS and the REST

Introduction to SoapUI day 3
Introduction to SoapUI day 3Introduction to SoapUI day 3
Introduction to SoapUI day 3Qualitest
 
(ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service (ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service BIOVIA
 
Spring Framework 3.2 - What's New
Spring Framework 3.2 - What's NewSpring Framework 3.2 - What's New
Spring Framework 3.2 - What's NewSam Brannen
 
So you think you know REST - DPC11
So you think you know REST - DPC11So you think you know REST - DPC11
So you think you know REST - DPC11Evert Pot
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.Andrey Oleynik
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTPradeep Kumar
 
Ajug - The Spring Update
Ajug - The Spring UpdateAjug - The Spring Update
Ajug - The Spring UpdateGunnar Hillert
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Joe Keeley
 
RESTful web
RESTful webRESTful web
RESTful webAlvin Qi
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Mario Cardinal
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Soap UI - Lesson3
Soap UI - Lesson3Soap UI - Lesson3
Soap UI - Lesson3Qualitest
 
API-Testing-SOAPUI-1.pptx
API-Testing-SOAPUI-1.pptxAPI-Testing-SOAPUI-1.pptx
API-Testing-SOAPUI-1.pptxamarnathdeo
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackChiradeep Vittal
 

Similar to Spring MVC to iOS and the REST (20)

Introduction to SoapUI day 3
Introduction to SoapUI day 3Introduction to SoapUI day 3
Introduction to SoapUI day 3
 
(ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service (ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service
 
Spring Framework 3.2 - What's New
Spring Framework 3.2 - What's NewSpring Framework 3.2 - What's New
Spring Framework 3.2 - What's New
 
So you think you know REST - DPC11
So you think you know REST - DPC11So you think you know REST - DPC11
So you think you know REST - DPC11
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and REST
 
Ajug - The Spring Update
Ajug - The Spring UpdateAjug - The Spring Update
Ajug - The Spring Update
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019
 
RESTful web
RESTful webRESTful web
RESTful web
 
The Spring Update
The Spring UpdateThe Spring Update
The Spring Update
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Soap UI - Lesson3
Soap UI - Lesson3Soap UI - Lesson3
Soap UI - Lesson3
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
API-Testing-SOAPUI-1.pptx
API-Testing-SOAPUI-1.pptxAPI-Testing-SOAPUI-1.pptx
API-Testing-SOAPUI-1.pptx
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStack
 

More from Roy Clarkson

Native Android Development Practices
Native Android Development PracticesNative Android Development Practices
Native Android Development PracticesRoy Clarkson
 
Making the Mobile Web Native with PhoneGap
Making the Mobile Web Native with PhoneGapMaking the Mobile Web Native with PhoneGap
Making the Mobile Web Native with PhoneGapRoy Clarkson
 
Mobile Web Development with HTML5
Mobile Web Development with HTML5Mobile Web Development with HTML5
Mobile Web Development with HTML5Roy Clarkson
 
Spring Projects Infrastructure
Spring Projects InfrastructureSpring Projects Infrastructure
Spring Projects InfrastructureRoy Clarkson
 
Native Android Development with Spring
Native Android Development with SpringNative Android Development with Spring
Native Android Development with SpringRoy Clarkson
 
Extending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScriptExtending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScriptRoy Clarkson
 
Spring Projects Infrastructure
Spring Projects InfrastructureSpring Projects Infrastructure
Spring Projects InfrastructureRoy Clarkson
 

More from Roy Clarkson (7)

Native Android Development Practices
Native Android Development PracticesNative Android Development Practices
Native Android Development Practices
 
Making the Mobile Web Native with PhoneGap
Making the Mobile Web Native with PhoneGapMaking the Mobile Web Native with PhoneGap
Making the Mobile Web Native with PhoneGap
 
Mobile Web Development with HTML5
Mobile Web Development with HTML5Mobile Web Development with HTML5
Mobile Web Development with HTML5
 
Spring Projects Infrastructure
Spring Projects InfrastructureSpring Projects Infrastructure
Spring Projects Infrastructure
 
Native Android Development with Spring
Native Android Development with SpringNative Android Development with Spring
Native Android Development with Spring
 
Extending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScriptExtending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScript
 
Spring Projects Infrastructure
Spring Projects InfrastructureSpring Projects Infrastructure
Spring Projects Infrastructure
 

Recently uploaded

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Recently uploaded (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Spring MVC to iOS and the REST

  • 1. Spring MVC to iOS and the REST Roy Clarkson, Senior Engineer, VMware Twitter/GitHub: @royclarkson Josh Long, Spring Developer Advocate Twitter: @starbuxman GitHub: @joshlong © 2013 SpringSource, by VMware
  • 2. About Roy Clarkson • Georgia Tech Alum • SpringSource Engineer at VMware • Lead on Spring for Android and Spring Mobile • Twitter/GitHub: @royclarkson • rclarkson@vmware.com • http://www.slideshare.net/royclarkson 2
  • 3. About Josh Long (⻰龙之春) Spring Developer Advocate twitter: @starbuxman weibo: @springsource josh.long@springsource.com 3
  • 4. About Josh Long Spring Developer Advocate twitter: @starbuxman josh.long@springsource.com Contributor To: •Spring Integration •Spring Batch •Spring Hadoop •Activiti Workflow Engine 4
  • 5. Agenda • REST • Spring MVC • iOS • Demos 5
  • 6. The term Representational State Transfer was introduced and defined in 2000 by Roy Fielding in his doctoral dissertation. 6
  • 7. What is REST? • REpresentational State Transfer • An architectural style for designing distributed systems • Not a standard, but rather a set of constraints – Client/Server, Stateless, Uniform Interface, etc. • Not tied to HTTP, but associated most commonly with it 7
  • 8. The Principles of REST • Resources – Expose directory structure-like URIs – URI’s should be easily understood • Representations – Transfer XML, JavaScript Object Notation (JSON), or both – Use XML or JSON to represent data objects or attributes • Messages – Use HTTP methods explicitly (i.e. POST, GET, PUT, DELETE) – CRUD operations can be mapped to these existing methods • Stateless – State dependencies limit or restrict scalability 8
  • 9. What is HATEOAS? • Hypermedia As The Engine Of Application State • The client doesn’t have a built in knowledge of how to navigate and manipulate the model • Instead server provides that information dynamically to the user • Implemented by using media types and link relations 9
  • 10. HTTP GET • Retrieve information – Must be safe and idempotent • Can have side effects, but since the user doesn’t expect them, they shouldn’t be critical to the operation of the system • GET can be conditional or partial – If-Modified-Since – Range GET /pizzas/1 10
  • 11. HTTP DELETE • Request that a resource be removed • The resource doesn’t have to be removed immediately – Removal may be a long running task DELETE /pizzas/1 11
  • 12. HTTP PUT • Requests that the entity passed be stored at the URI • Can be used to create a new entity or modify an existing one – Creation of new entities is uncommon as it allows the client to select the id of the new entity PUT /toppings/1 { “name” : “Cheese” } 12
  • 13. HTTP POST • Requests that the resource at a URI do something with the enclosed entity • The major difference between POST and PUT are what resource the request URI identifies • For example, use PUT to create and POST to modify POST /toppings/1 { “name” : “Cheddar Cheese” } 13
  • 14. HTTP Status Codes • Status codes are an indicator the result of the server’s attempt to satisfy the request • Broadly divided in categories – 1XX: Informational – 2XX: Success – 3XX: Redirection – 4XX: Client Error – 5XX: Server Error 14
  • 15. Success Status Codes • 200 OK – Everything worked • 201 Created – The server has successfully created a new resource – Newly created resource’s location returned in the Location header • 202 Accepted – The server has accepted the request, but it is not yet complete – A location to determine the request’s current status can be returned in the Location header 15
  • 16. Client Error Status Codes • 400 Bad Request – Malformed Syntax – Should not be repeated without modification • 401 Unauthorized – Authentication is required – Includes a WWW-Authenticate header • 403 Forbidden – Server has understood, but refuses to honor the request – Should not be repeated without modification 16
  • 17. Client Error Status Codes • 404 Not Found – The server cannot find a resource matching a URI • 406 Not Acceptable – The server can only return response entities that do not match the client’s Accept header • 409 Conflict – The resource is in a state that is in conflict with the request – Client should attempt to rectify the conflict and then resubmit the request 17
  • 18. Media Types • Accept & Content-Type HTTP Headers • Client or server describes the content 18
  • 19.
  • 20. Spring Web MVC DispatcherServlet 20
  • 21. Annotations of Spring MVC • @Controller • @RequestMapping • @RequestParam • @PathVariable • @ResponseBody • @RequestBody • @ResponseStatus 21
  • 23. @RequestMapping @Controller @RequestMapping("/pizzas") public class PizzaController { // POST /pizzas/bake @RequestMapping(value = "/bake", method = POST) public void bake() { ... } } 23
  • 24. @RequestParam @Controller @RequestMapping("/pizzas") public class PizzaController { // POST /pizzas/bake?temp=400 @RequestMapping(value = "/bake", method = POST) public void bake(@RequestParam Integer temp) { ... } } 24
  • 25. @PathVariable @Controller @RequestMapping("/pizzas") public class PizzaController { // POST /pizzas/bake/400 @RequestMapping(value = "/bake/{temp}", method = POST) public void bake(@PathVariable Integer temp) { ... } } 25
  • 26. @ResponseBody @Controller @RequestMapping("/pizzas") public class PizzaController { // GET /pizzas @RequestMapping( method = GET, produces = "application/json") public @ResponseBody List<Pizza> list() { ... } } 26
  • 27. @ResponseBody @Controller @RequestMapping("/pizzas") public class PizzaController { // GET /pizzas @RequestMapping(method = GET, produces = MediaType.APPLICATION_JSON_VALUE ) public @ResponseBody List<Pizza> list() { ... } } 27
  • 28. @RequestBody @Controller @RequestMapping("/pizzas") public class PizzaController { // PUT /pizzas @RequestMapping( method = PUT, consumes = "application/json") public void create(@RequestBody Pizza pizza) { ... } } 28
  • 29. @ResponseStatus @Controller @RequestMapping("/pizzas") public class PizzaController { // PUT /pizzas @ResponseStatus(HttpStatus.CREATED) @RequestMapping( method = PUT, consumes = "application/json") public void create(@RequestBody Pizza pizza) { ... } } 29
  • 30. Async MVC Processing: Callable @Controller @RequestMapping("/pizzas") public class PizzaController { @RequestMapping(value = "/orders", method = POST) @ResponseBody public Callable<String> upload(MultipartFile file) { return new Callable<Pizza>() { public Pizza call() throws Exception // ... return pizza; } } } 30
  • 31. Async MVC Processing: DeferredResult @RequestMapping("/quotes") @ResponseBody public DeferredResult quotes() { DeferredResult deferredResult = new DeferredResult(); // Add deferredResult to a Queue or a Map... return deferredResult; } // In some other thread: // Set the return value on the DeferredResult deferredResult.set(data); - thread managed outside of Spring MVC - JMS or AMQP message listener, another HTTP request, etc. 31
  • 32. Async MVC Processing: AsyncTask @RequestMapping(name =“/upload”, method=RequestMethod.POST) public AsyncTask<Foo> processUpload(MultipartFile file) { TaskExecutor asyncTaskExecutor = new AsyncTaskExecutor(...); return new AsyncTask<Foo>( 1000L, // timeout asyncTaskExecutor, // thread pool new Callable<Foo>(){ ..} // thread ); } - same as Callable, with extra features - override timeout value for async processing - lets you specify a specific AsyncTaskExecutor 32
  • 33. Message Converters • RSS/ATOM • java.awt.BufferedImage • JSON • JAXB • Write your own! – iCal – GSON • Third Party: • https://github.com/joshlong/spring-advanced-marhshallers-and-service-exporters – supports Google PB, Avro, Thrift, MessagePack, Google Snappy 33
  • 35. Testing • Testing of web APIs isn’t easy – In container, end-to-end, string comparison, etc. – Out of container, Java objects, bypassing much of Spring’s magic • What we want is out of container, but with as much of Spring as we can get 35
  • 36. Spring MVC Testing • Available in Spring 3.2 • Bootstraps most of Spring’s MVC infrastructure so that you unit and integration test your web application end-to- end • Provides APIs for testing interesting parts of requests and responses 36
  • 37.
  • 38. REST on iOS • HTTP Client – NSURLConnection • JSON Processor (iOS 5) – NSJSONSerialization • Data – NSData – NSDictionary – NSArray 38
  • 39. NSURLConnection • Loading Data Synchronously + sendSynchronousRequest:returningResponse:error: • Loading Data Asynchronously + sendAsynchronousRequest:queue:completionHandler: 39
  • 40. Basic HTTP Request NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 40
  • 41. Basic HTTP Request... Improved NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSURLResponse *response; NSError *error; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSInteger status = [(NSHTTPURLResponse *)response statusCode]; if (status == 200 && data.length > 0 && error == nil) { // do something with data } 41
  • 42. Asynchronous HTTP Request NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSInteger status = [(NSHTTPURLResponse *)response statusCode]; if (status == 200 && data.length > 0 && error == nil) { // do something with data } } 42
  • 43. HTTP Headers NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setHTTPMethod:@"PUT"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:contentLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData]; 43
  • 44. JSON Serialization // deserialize JSON data NSError *error; NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // serialize JSON data NSError *error; NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error]; 44
  • 46. Conclusion • API Design Matters – URIs represent resources, not actions – HTTP verbs are general, but can be used in ways that make anything possible • Implementation isn’t rocket science – Spring MVC – Spring HATEOAS • Easy testing – Out-of-container, but full Spring stack 46
  • 47. More Information • Roy Fielding’s Dissertation http://www.ics.uci.edu/~fielding/pubs/dissertation/ evaluation.htm#sec_6_1%7C • Spring MVC Reference http://static.springsource.org/spring-framework/docs/ current/spring-framework-reference/html/mvc.html • URL Loading System Programming Guide http://developer.apple.com/library/ios/#documentation/ Cocoa/Conceptual/URLLoadingSystem/ URLLoadingSystem.html 47
  • 48. Related Spring Projects • REST Shell https://github.com/SpringSource/rest-shell • Spring HATEOAS https://github.com/SpringSource/spring-hateoas • Spring MVC Test https://github.com/SpringSource/spring-test-mvc 48
  • 49. Questions? • All Sample Code: https://github.com/royclarkson/rest-demo https://github.com/joshlong/the-spring-tutorial • Presentation: http://www.slideshare.net/royclarkson 49