REST-ful API Design

33
© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission. REST-ful API Design with Spring Ben Hale, Pivotal https://github.com/nebhale/spring-one-2013

description

Speaker: Ben Hale As data-driven applications become more widespread, the services that provide the data are becoming more critical. Most commonly these data services are exposed via REST-ful APIs. This session describes what exactly makes a service REST-ful, how to implement a REST-ful API using Spring, and how to test that API.

Transcript of REST-ful API Design

Page 1: REST-ful API Design

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

REST-ful API Design with SpringBen Hale, Pivotal

https://github.com/nebhale/spring-one-2013

Page 2: REST-ful API Design

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

2

Page 3: REST-ful API Design

Uniform Interface• “... more what you’d call ‘guidelines’ than actual rules”

–Captain Barbossa

• Identification of resources• Manipulation of resources• Self-descriptive messages• Hypermedia as the engine of application state

3

Page 4: REST-ful API Design

HTTP’s Uniform Interface• URI’s identify resources• HTTP verbs describe a limited set of operations that can be

used to manipulate a resource–GET–DELETE–PUT–POST–less used other verbs

• Headers help describe the messages

4

Page 5: REST-ful API Design

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

5

GET /games/1

Page 6: REST-ful API Design

DELETE• Request that a resource be removed• The resource doesn’t have to be removed immediately

–Removal my be a long running task

6

DELETE /games/1

Page 7: REST-ful API Design

PUT• Requests that the entity passed by 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

7

PUT /games/1/doors/2{ “status”: “SELECTED” }

Page 8: REST-ful API Design

POST• Requests that the resource at a URI do something with the

enclosed entity• What that something is could be almost anything

–Create–Modify

• The major difference between POST and PUT are what resource the request URI identifies

8

POST /games

Page 9: REST-ful API Design

Let’s Make a Deal!

9

Page 10: REST-ful API Design

Interaction Model• Create Game• List the current state of all Doors• Select a Door• The Game will open one of the other non-bicycle Doors• Open one of the two remaining Doors• List the outcome of the Game• Delete the Game

10

Page 11: REST-ful API Design

Create a Game• Well-known entry point• Doesn’t require any input other than requesting that a game

be created• Needs to return us a resource identifier (URI) of the newly

created game

11

POST /games

Page 12: REST-ful API Design

List the current state of all Doors• Needs to return us a collection that represents the state of all

doors in the game• Design doesn’t have ‘Door 1’, ‘Door 2’, ‘Door 3’, just three

doors

12

GET /games/0/doors[{“status”: “CLOSED”}, {...}, {...}]

Page 13: REST-ful API Design

Select a Door• There is no HTTP verb ‘SELECT’, so how do we represent the

selection of a door?• Request a resource mutation that leaves the resource in

desired state

13

PUT /games/1/doors/2{“status”: “SELECTED”}

Page 14: REST-ful API Design

Open a Door• Like select, we want to request a mutation to the desired

state• Since the same (or same type of) resource is being modified,

we re-use the same payload

14

PUT /games/1/doors/3{“status”: “OPEN”}

Page 15: REST-ful API Design

List the final state of the Game• Needs to return an object that represents the state of the

game

15

GET /games/0{“status”: “WON”}

Page 16: REST-ful API Design

Destroy the Game• No input required• No output required

16

DELETE /games/0

Page 17: REST-ful API Design

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Spring MVCImplementation

Page 18: REST-ful API Design

Status Codes• Status codes are an indicator of the result 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

18

Page 19: REST-ful API Design

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 header19

Page 20: REST-ful API Design

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–Sever has understood, but refuses to honor the request–Should not be repeated without modification

20

Page 21: REST-ful API Design

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

21

Page 22: REST-ful API Design

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Spring MVCException Handling

Page 23: REST-ful API Design

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

23

Page 24: REST-ful API Design

Media Types• A resource can be represented in different ways

–JSON, XML, etc.• A client doesn’t know what a server is going to send it• A server doesn’t know what a client can handle• Content types are negotiated using headers

–Client describe what it wants with Accept header–Server (and client during POST and PUT) describes what it is

sending with Content-Type header

24

Page 25: REST-ful API Design

Link Relations• A client cannot be expected to know what a resource is

related to and where those relations are located• The server describes these relations as part of its payload• Link has two parts–rel–href

• rel values are “standardized” so client can recognize them–<link rel=”stylesheet” href=”...”/>–{“rel”: “doors”, “href”: “...”}

25

Page 26: REST-ful API Design

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Spring HATEOASImplementations

Page 27: REST-ful API Design

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

27

Page 28: REST-ful API Design

Spring MVC Testing• 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

28

Page 29: REST-ful API Design

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Spring MVCTesting

Page 30: REST-ful API Design

Using the API• Designed, implemented, and tested but can you actually use

this API?

• Goals–Single URL–Link Traversal–Content Negotiation

30

Page 31: REST-ful API Design

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Consuming the gamein Python

Page 32: REST-ful API Design

Round Up• 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

32

Page 33: REST-ful API Design

Learn More. Stay Connected.

https://github.com/nebhale/spring-one-2013

Talk to us on Twitter: @springcentralFind session replays on YouTube: spring.io/video