Slide 1

Slide 1 text

LIVE TRAINING The Basics of REST with Spring Eugen Paraschiv @baeldung [email protected]

Slide 2

Slide 2 text

. . . . . . . . . . . . . . REST With Spring HI • My name is Eugen Paraschiv (don’t try to pronounce it) • Created my first REST API with Spring in 2010 • Got excited and started obsessing about REST • Created about 100 separate APIs since then • Made a lot of mistakes and slowly learned from them • The last APIs I created for a client is well positioned to become the largest ElasticSearch installation in the world

Slide 3

Slide 3 text

. . . . . . . . . . . . . . REST With Spring • Help you build a solid, production ready RESTful API with Spring (and Spring Boot) PRESENTATION GOAL

Slide 4

Slide 4 text

. . . . . . . . . . . . . . REST With Spring • What makes a good API AGENDA

Slide 5

Slide 5 text

. . . . . . . . . . . . . . REST With Spring • What makes a good API • Basics of HTTP with REST AGENDA

Slide 6

Slide 6 text

. . . . . . . . . . . . . . REST With Spring • What makes a good API • Basics of HTTP with REST • HTTP Verbs, URLs and Status Codes AGENDA

Slide 7

Slide 7 text

. . . . . . . . . . . . . . REST With Spring • What makes a good API • Basics of HTTP with REST • HTTP Verbs, URLs and Status Codes • Focus on API Errors AGENDA

Slide 8

Slide 8 text

. . . . . . . . . . . . . . QUESTION FOR YOU HAVE YOU IMPLEMENTED A REST API BEFORE?

Slide 9

Slide 9 text

. . . . . . . . . . . . . . REST With Spring • We’re only working with Resources URL – NOUNS, NO VERBS?

Slide 10

Slide 10 text

. . . . . . . . . . . . . . REST With Spring • We’re only working with Resources • Operations on Resources are expressed via HTTP Verbs URL – NOUNS, NO VERBS?

Slide 11

Slide 11 text

. . . . . . . . . . . . . . REST With Spring • We’re only working with Resources • Operations on Resources are expressed via HTTP Verbs • A Verb in the URL is a sign of bad design URL – NOUNS, NO VERBS?

Slide 12

Slide 12 text

. . . . . . . . . . . . . . REST With Spring • Bad: /account/pay URL – NO VERBS – EXAMPLE

Slide 13

Slide 13 text

. . . . . . . . . . . . . . REST With Spring • Bad: /account/pay • Good: /account/payment URL – NO VERBS – EXAMPLE

Slide 14

Slide 14 text

. . . . . . . . . . . . . . REST With Spring • The Resource - is the actual object RESOURCE VS REPRESENTATION

Slide 15

Slide 15 text

. . . . . . . . . . . . . . REST With Spring • The Resource - is the actual object • The Representation - is the object serialized (+ metadata) RESOURCE VS REPRESENTATION

Slide 16

Slide 16 text

. . . . . . . . . . . . . . PAUSE BREETHE ASK QUESTIONS

Slide 17

Slide 17 text

. . . . . . . . . . . . . . REST With Spring • Resource Name: Foo • Base URL: /api/foos • Standard Operations: create, update, delete, get one, get all, get paginated • Constraints: Foos are unique by name EXAMPLE API

Slide 18

Slide 18 text

. . . . . . . . . . . . . . A CREATE OPERATION

Slide 19

Slide 19 text

. . . . . . . . . . . . . . REST With Spring • HTTP Verb: POST • URL: /foos – plural • Response: 201 Created CREATE @RequestMapping(value = "/foos", method = POST) @ResponseStatus(HttpStatus.CREATED) public void create(@Valid @RequestBody Foo resource) { service.create(resource); }

Slide 20

Slide 20 text

. . . . . . . . . . . . . . REST With Spring • Both designs are OK, neither is wrong URL – SINGULAR VS PLURAL

Slide 21

Slide 21 text

. . . . . . . . . . . . . . REST With Spring • Both designs are OK, neither is wrong • Plural indicates that we’re working with a Collections Resource – When we GET, we get back the entire collection URL – SINGULAR VS PLURAL

Slide 22

Slide 22 text

. . . . . . . . . . . . . . REST With Spring • Both designs are OK, neither is wrong • Plural indicates that we’re working with a Collections Resource – When we GET, we get back the entire collection – When we POST, we append / add a new Resource into the collection URL – SINGULAR VS PLURAL

Slide 23

Slide 23 text

. . . . . . . . . . . . . . REST With Spring • Both designs are OK, neither is wrong • Plural indicates that we’re working with a Collections Resource – When we GET, we get back the entire collection – When we POST, we append / add a new Resource into the collection – When we want a single Resource -> we drill into the Collection with a further unique identifier URL – SINGULAR VS PLURAL

Slide 24

Slide 24 text

. . . . . . . . . . . . . . AN UPDATE OPERATION

Slide 25

Slide 25 text

. . . . . . . . . . . . . . REST With Spring • HTTP Verb: PUT • URL: /foos/1 – plural + {id} • Response: 200 OK UPDATE @RequestMapping(value = "/foos/{id}", method = PUT) @ResponseStatus(HttpStatus.OK) public void create( @PathVariable("id") Long id, @Valid @RequestBody Foo resource) { service.update(resource); }

Slide 26

Slide 26 text

. . . . . . . . . . . . . . REST With Spring • A HTTP concern, not a REST concern CREATE VS UPDATE – POST VS PUT

Slide 27

Slide 27 text

. . . . . . . . . . . . . . REST With Spring • A HTTP concern, not a REST concern • PUT is idempotent, POST is not CREATE VS UPDATE – POST VS PUT

Slide 28

Slide 28 text

. . . . . . . . . . . . . . REST With Spring • A HTTP concern, not a REST concern • PUT is idempotent, POST is not • PUT is closer to the semantic of replace • POST is closer to the semantic of insert CREATE VS UPDATE – POST VS PUT

Slide 29

Slide 29 text

. . . . . . . . . . . . . . REST With Spring • => We are going to use: – POST for create (subordinate Resources) – PUT for full update (replace) CREATE VS UPDATE – POST VS PUT

Slide 30

Slide 30 text

. . . . . . . . . . . . . . REST With Spring • PUT has full update (replace) semantics WHAT ABOUT PARTIAL UPDATES?

Slide 31

Slide 31 text

. . . . . . . . . . . . . . REST With Spring • PUT has full update (replace) semantics • What about partial updates? WHAT ABOUT PARTIAL UPDATES?

Slide 32

Slide 32 text

. . . . . . . . . . . . . . REST With Spring • PUT has full update (replace) semantics • What about partial updates? • Use PATCH! WHAT ABOUT PARTIAL UPDATES?

Slide 33

Slide 33 text

. . . . . . . . . . . . . . A DELETE OPERATION

Slide 34

Slide 34 text

. . . . . . . . . . . . . . REST With Spring • HTTP Verb: DELETE • URL: /foos/1 – plural + {id} • Response: 204 No Content DELETE @RequestMapping(value = "/foos/{id}", method = DELETE) @ResponseStatus(HttpStatus.OK) public void create(@PathVariable("id") Long id) { service.delete(id); }

Slide 35

Slide 35 text

. . . . . . . . . . . . . . REST With Spring • The HTTP Spec says that DELETE is idempotent; but: – We send the first DELETE to a Resource – it gets deleted – We send a second DELETE to the same Resource - 404 IS DELETE IDEMPOTENT?

Slide 36

Slide 36 text

. . . . . . . . . . . . . . REST With Spring • The HTTP Spec says that DELETE is idempotent; but: – We send the first DELETE to a Resource – it gets deleted – We send a second DELETE to the same Resource - 404 • Idempotence refers to the state of the system after the request has completed IS DELETE IDEMPOTENT?

Slide 37

Slide 37 text

. . . . . . . . . . . . . . GET OPERATIONS

Slide 38

Slide 38 text

. . . . . . . . . . . . . . REST With Spring • HTTP Verb: GET (of course) • URL: /foos/1 – plural + {id} • Response: 200 OK GET ONE @RequestMapping(value = "/foos/{id}", method = GET) @ResponseBody public Foo findById(@PathVariable("id") Long id) { return service.findOne(id); }

Slide 39

Slide 39 text

. . . . . . . . . . . . . . REST With Spring • HTTP Verb: GET (of course) • URL: /foos – plural • Response: 200 OK GET ALL @RequestMapping(value = "/foos", method = GET) @ResponseBody public List findAll() { return service.findAll(); }

Slide 40

Slide 40 text

. . . . . . . . . . . . . . A “GET ALL PAGINATED” OPERATION

Slide 41

Slide 41 text

. . . . . . . . . . . . . . REST With Spring • HTTP Verb: GET • URL: /foos?page=1&size=5 • Response: 200 OK GET ALL - PAGINATED @RequestMapping( value = "/foos", params = { "page", "size" }, method = RequestMethod.GET) @ResponseBody public List findPaginated( @RequestParam("page") int page, @RequestParam("size") int size) { return service.findPaginated(page, size).getContent(); }

Slide 42

Slide 42 text

. . . . . . . . . . . . . . REST With Spring GET ALL – PAGINATED - EXAMPLE GET http://localhost:8080/api/foos?page=1&size=10 Link= ; rel="first", ; rel="last", ; rel="next", ; rel="prev"

Slide 43

Slide 43 text

. . . . . . . . . . . . . . PAUSE BREETHE ASK QUESTIONS

Slide 44

Slide 44 text

. . . . . . . . . . . . . . PROBLEMS, ERRORS, EXCEPTIONS

Slide 45

Slide 45 text

. . . . . . . . . . . . . . REST With Spring • 400 Bad Request • 401 Unauthenticated and 403 Forbidden • 404 Not Found • 405 Method Not Allowed • 409 Conflict • 415 Unsupported Media Type CLIENT ERRORS – 4XX

Slide 46

Slide 46 text

. . . . . . . . . . . . . . REST With Spring • The generic, catch-all for client side errors • Usually happens for PUT or POST requests • Usually means that the Representation of the Resource is in the right format but still doesn’t make sense 400 Bad Request

Slide 47

Slide 47 text

. . . . . . . . . . . . . . REST With Spring • Should have been named 401 Unauthenticated • The Client is trying to operate on a protected Resource without providing the proper authentication credentials 401 Unauthorized

Slide 48

Slide 48 text

. . . . . . . . . . . . . . REST With Spring • The Client is trying to work with a protected Resource, has provided correct authentication credentials, but simply does not have enough access to that Resource 403 Forbidden

Slide 49

Slide 49 text

. . . . . . . . . . . . . . REST With Spring • The Client tries to operate on a Resource that does not exist • 410 Gone – similar, but better semantics 404 Not Found

Slide 50

Slide 50 text

. . . . . . . . . . . . . . REST With Spring • The Method specified in the client request is not allowed for that Resource • The response should contain an Allow header 405 Method Not Allowed

Slide 51

Slide 51 text

. . . . . . . . . . . . . . REST With Spring • The request could not be completed due to a conflict with the current state of the resource • Ex: We try to create a Foo Resource with the same name as an existing one => 409 • Do NOT use 412 Precondition Failed instead! 409 Conflict

Slide 52

Slide 52 text

. . . . . . . . . . . . . . REST With Spring • The Representation provided by the Client is not supported • Example: The API only supports JSON • Content-Type: application/xml 415 Unsupported Media Type

Slide 53

Slide 53 text

. . . . . . . . . . . . . . LESS COMMON 4XX STATUS CODES

Slide 54

Slide 54 text

. . . . . . . . . . . . . . REST With Spring • 411 Length Required OTHER 4XX STATUS CODES

Slide 55

Slide 55 text

. . . . . . . . . . . . . . REST With Spring • 411 Length Required • 413 Request Entity Too Large • 414 Request URI Too Long OTHER 4XX STATUS CODES

Slide 56

Slide 56 text

. . . . . . . . . . . . . . REST With Spring • Use @ControllerAdvice to do global error handling SPRING GLOBAL EXCEPTION HANDLING

Slide 57

Slide 57 text

. . . . . . . . . . . . . . REST With Spring • Use @ControllerAdvice to do global error handling • It can handle exceptions individually or together SPRING GLOBAL EXCEPTION HANDLING

Slide 58

Slide 58 text

. . . . . . . . . . . . . . REST With Spring • Use @ControllerAdvice to do global error handling • It can handle exceptions individually or together • And It allows full control over the body of the Response SPRING GLOBAL EXCEPTION HANDLING

Slide 59

Slide 59 text

. . . . . . . . . . . . . . REST With Spring HANDLE A SINGLE EXCEPTION @ExceptionHandler({ InvalidDateException.class }) public ResponseEntity handleInvalidDate( InvalidDateException ex, WebRequest request) { … }

Slide 60

Slide 60 text

. . . . . . . . . . . . . . REST With Spring HANDLE TWO EXCEPTIONS @ExceptionHandler({ InvalidDateException.class, IllegalArgumentException.class }) public ResponseEntity handleInvalidDate( RuntimeException ex, WebRequest request) { … }

Slide 61

Slide 61 text

. . . . . . . . . . . . . . REST With Spring THE ERROR RESPONSE BODY @ExceptionHandler({ … }) public ResponseEntity handleInvalidDate( RuntimeException ex, WebRequest request) { … return handleExceptionInternal( ex, new ApiError(…), new HttpHeaders(), BAD_REQUEST, request); }

Slide 62

Slide 62 text

. . . . . . . . . . . . . . REST With Spring ERROR HANDLING ON THE CLIENT HTTP/1.1 400 Bad Request Content-Type: application/json;charset=UTF-8 ... { "ui-error": "There was a validation problem", "dev-error": "MethodArgumentNotValidException", "fieldErrors": [ { "field": "data[0].name", "message": "may not be null" } ] }

Slide 63

Slide 63 text

. . . . . . . . . . . . . . REST With Spring • The basics of REST terminology - Resource vs. Representation • Good URL practices: Nouns vs. Verbs, Plural vs. Singular • Create vs. Update - POST vs PUT (vs PATCH) • Is Delete Idempotent? • How to implement pagination in the API well • Deep dive into the 4xx class of Client Errors • Spring - Exception Handling WHAT WE LEARNED

Slide 64

Slide 64 text

LIVE TRAINING restwithspring.com “REST WITH SPRING” COURSE

Slide 65

Slide 65 text

LIVE TRAINING The Starter Class – 3 courses - went live on the 1st of October Course 1 - The Basics of REST with Spring (60 minutes) Course 2 - REST and HTTP Semantics (72 minutes) Course 3 - Simple Security for REST (40 minutes) REST With Spring http://restwithspring.com

Slide 66

Slide 66 text

LIVE TRAINING The Intermediate Class – 6 courses - went live on the 10th of November Course 4 - Consuming the API from AngularJS (42 minutes) Course 5 - Testing the API (56 minutes) Course 6 - Advanced Security: OAuth2 and JWT (48 minutes) REST With Spring http://restwithspring.com

Slide 67

Slide 67 text

LIVE TRAINING The Master Class – the full 9 courses - goes live on the 20th of December Course 7 - Document, Discover and Evolve the REST API Course 8 – Monitoring and Metrics of REST API Course 9 - CI and CD Pipelines for the API REST With Spring http://restwithspring.com

Slide 68

Slide 68 text

LIVE TRAINING The Starter Class – 3 courses – 49$ - went live on the 1st of October The Intermediate Class – 6 courses – 99$ 74$ - went live on the 10th of November The Master Class – 9 courses – 149$ 112$ - out on the 20th of December REST With Spring http://restwithspring.com

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

. . . . . . . . . . . . . . ANNOUNCING A NEW LIVE WORKSHOP February 10th

Slide 71

Slide 71 text

LIVE TRAINING “Advanced API Security” Workshop • How to set up OAuth2 for a public API • JSON Web Tokens (JWT) • Token storage on the front-end (AngularJS)

Slide 72

Slide 72 text

LIVE TRAINING “Advanced API Security” Workshop • How to do a proxy-server implementation • CSRF protection in-depth • A full project template for the implementation

Slide 73

Slide 73 text

LIVE TRAINING Webinar Bonus (next 24 hours) The Advanced API Security Live Workshop – 67$ With the Master Class of REST With Spring – 10 free seats 10th of February 2016

Slide 74

Slide 74 text

. . . . . . . . . . . . . . THANK YOU It’s Q&A Time