Designing REST services with Spring MVC

37
Designing REST services with Spring MVC Serhii Kartashov December 2015 Softjourn Internship

Transcript of Designing REST services with Spring MVC

Page 1: Designing REST services with Spring MVC

Designing REST services with Spring MVC

Serhii KartashovDecember 2015SoftjournInternship

Page 2: Designing REST services with Spring MVC

Agenda

What is REST?

CRUD operations

Status codes

Media types

SpringMVC instruments

Page 3: Designing REST services with Spring MVC

Agenda

What is REST?

CRUD operations

Status codes

Media types

SpringMVC instruments

Page 4: Designing REST services with Spring MVC

What is REST?

• REpresentational State Transfer

• Client/Server, Stateless, Uniform Interface

• Hightly-Cohesive, loosely coupled services

Page 5: Designing REST services with Spring MVC

Uniform Interface

• Identification of resources

• Manipulation of resources

• Self-describing of resources

Page 6: Designing REST services with Spring MVC

Representations of the resource over a network

• URI - Uniform Resource Identifier• URL - Uniform Resource Locator• URN - Uniform Resource Name

Page 7: Designing REST services with Spring MVC

HTTP's uniform interface

• URI's identify resources/accounts/0

• HTTP verbs descried a limited set of operations that can be used to manipulate a resourcePOST, GET, PUT, DELETE, ...

• Headers describes the messagesContent-Type: application/json

Page 8: Designing REST services with Spring MVC

GET

• Retrieve Information• Must be save and idempotent• Get can be conditional or partial

If-Modified-SinceRange

Page 9: Designing REST services with Spring MVC

DELETE

• Requests that a resource be removed• The resource doesn't have to be removed

immediately• Removal may be a long running task

DELETE /accounts/0

Page 10: Designing REST services with Spring MVC

PUT

• Requests that the entity passed, be stored at the URI

• Can be used to modify an existing onePUT /accounts/0/creditcards/1

Page 11: Designing REST services with Spring MVC

POST

• Requests that the resource at the URI do something with the enclosed entityCreate, ModifyPOST /accounts

Page 12: Designing REST services with Spring MVC

Agenda

What is REST?

CRUD operations

Status codes

Media types

SpringMVC instruments

Page 13: Designing REST services with Spring MVC

Interaction Model

• List the current accounts in bank• Create new account• Create new credit card• List the current credit cards of account• Make transaction between two credit cards• Lock credit card• Delete account

Page 14: Designing REST services with Spring MVC

List the current accounts in bank

• Need to return to us a collection that represents

• Design doesn't have Account1, Account2, Account..., just accounts

GET: /accountsResponse: [{"id":0,"name":"Mike"}, {...}, {...}]

Page 15: Designing REST services with Spring MVC

Create new account

• Need to create new account in bank with providing name of person

• Good practice is returning already created account

POST: /accounts json: {"name":"Matt"}Response: {"id":2,"name":"Matt"}

Page 16: Designing REST services with Spring MVC

Create new credit card

• That just a request for creation credit card automatically

POST: /accounts/2/creditcardsjson: {"pin":1111, "cardNumber":2, "cardStatus":"ACTIVE", "remnant":0.0}

Page 17: Designing REST services with Spring MVC

List the current credit cards of account

• Need to return to us a collection of all available credit cards

GET: /accounts/2/creditcardsResponse: [ {"pin":1111, "cardNumber":2, "cardStatus":"ACTIVE", "remnant":0.0} ]

Page 18: Designing REST services with Spring MVC

Make transaction between two credit cards

• Transaction be running during some time• Possible situation when you created just a

request for transaction and receive just info when this will be precessed

POST: /accounts/2/creditcards json: {"fromCreditCard": "1", "toCreditCard": "2", "amount": "20"}Transaction successfully processed

Page 19: Designing REST services with Spring MVC

Lock Credit Card

• Changed status of credit card

PUT: /accounts/2/creditcards/2{"pin":1111, "cardNumber":2, "cardStatus":"LOCKED", "remnant":20.0}

Page 20: Designing REST services with Spring MVC

Delete account

• No input required• No output required

DELETE /accounts/2

Page 21: Designing REST services with Spring MVC
Page 22: Designing REST services with Spring MVC

Agenda

What is REST?

CRUD operations

Status codes

Media types

SpringMVC instruments

Page 23: Designing REST services with Spring MVC

Status codes

• Status codes indicates the results of the server's attempt to satisfy the request

• Broadly divided into categories– 1XX: Informational– 2XX: Success– 3XX: Redirection– 4XX: Client Error– 5XX: Server Error

Page 24: Designing REST services with Spring MVC

Success Status Codes• 200 OKEverything worked• 201 CreatedThe server has successfully created a new resourceNewly created resource’s location returned in the Location header• 202 AcceptedThe server has accepted the request, but it is not yet completeA location to determine the request’s current status can be returned in the Location header

Page 25: Designing REST services with Spring MVC

Client Error Status Codes

• 400 Bad RequestMalformed syntaxShould not be repeated without modification• 401 UnauthorizedAuthentication is requiredIncludes a WWW- Authenticate header‐• 403 ForbiddenServer has understood but refuses to honor the requestShould not be repeated without modification

Page 26: Designing REST services with Spring MVC

Client Error Status Codes

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

Page 27: Designing REST services with Spring MVC
Page 28: Designing REST services with Spring MVC

Agenda

What is REST?

CRUD operations

Status codes

Media types

SpringMVC instruments

Page 29: Designing REST services with Spring MVC

Communication between client and server

Content types are negotiated using headers:• Client describes what it wants with the Accept

header• Server (and client during POST and PUT)

describes what it is sending with Content-Type header

Page 30: Designing REST services with Spring MVC

Common Media Types

• Application– JSON: application/json– XML: application/xml– PDF: application/pdf

• Text– HTML: text/html– PLAIN: text/plain

Page 31: Designing REST services with Spring MVC

Addition Media Types• Image

– JPEG: image/jpeg• Audio

– MP4: audio/mp4– WEBM: audio/webm

• Video– MP4: video/mp4– WEBM: video/webm

• Prefix vnd (vendor specific files)– application/vnd.android.package-archive - for apk files– application/vnd.ms-excel

Page 32: Designing REST services with Spring MVC

Agenda

What is REST?

CRUD operations

Status codes

Media types

SpringMVC instruments

Page 33: Designing REST services with Spring MVC

What other instruments Spring MVC can provide?

• @RestControllerUnion of @Controller and @RequestBody

annotations• @RequestBody• @RequestMapping

value; method; consumes; produces• @PathVariable• @RequestParam

Page 34: Designing REST services with Spring MVC

What other instruments Spring MVC can provide?

• @RequestHeader• @MatrixVariable

/owners/{ownerId}/pets/{petId}GET /owners/42;q=11;r=12/pets/21;q=22;s=23@MatrixVariable(pathVar="petId") Map<String, String> petMatrixVars<mvc:annotation-driven enable-matrix-variables="true"/>

• @SessionAttributes• @ModelAttribute• @CookieValue

Page 35: Designing REST services with Spring MVC

What more?

• Testing REST with MockMvc• REST Client• Caching• Version handling• Scaling: CDN (Content Delivery Network)

Page 36: Designing REST services with Spring MVC

Useful links• Tutorials

– http://www.restapitutorial.com/ • Video & Articles

– https://www.youtube.com/watch?v=5WXYw4J4QOU – ETags: http://www.infoq.com/articles/etags – Manage REST API versions:

http://stackoverflow.com/questions/20198275/how-to-manage-rest-api-versioning-with-spring?answertab=votes#tab-tophttp://stackoverflow.com/questions/20198275/how-to-manage-rest-api-versioning-with-spring?answertab=votes#tab-top

– Steps towards the glory of REST: http://martinfowler.com/articles/richardsonMaturityModel.html

• Examples from presentation: https://github.com/searhiy/REST-examples • Instruments & Tools

– https://github.com/spring-projects/spring-data-rest – http://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate

Page 37: Designing REST services with Spring MVC