Spring REST Concepts: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 33: Line 33:
===Request Body===
===Request Body===
===Form Parameters===
===Form Parameters===
=Read a Resource Representation=
[[@RequestMapping]], [[@GetMapping]]
=Create a Resource=
[[@RequestMapping]], [[@PostMapping]]
=Update a Resource=
[[@RequestMapping]], [[@PutMapping]], [[@PatchMapping]]


=Send a Response to Client=
=Send a Response to Client=

Revision as of 01:23, 13 March 2019

Internal

Overview

The. Spring REST concepts page is an extension of the Spring MVC Concepts page. Spring MVC concepts are used and extended to provide REST support.

Playground

@RestController Example

Annotations

Receive Data from Client

TODO: REST and Hypermedia

Via Path

Query Parameters

Path Parameters

Via Request

Request Headers

Request Body

Form Parameters

Read a Resource Representation

@RequestMapping, @GetMapping

Create a Resource

@RequestMapping, @PostMapping

Update a Resource

@RequestMapping, @PutMapping, @PatchMapping

Send a Response to Client

The @RestController annotation implies @ResponseBody, which maps the result produced by the handler method onto the body of the HTTP response.

By default, if all goes well - no exceptions are thrown - the HTTP status code is 200, even if the method returns null.

If the method handler wants to control the HTTP status code, it has the option of wrapping the response in a ResponseEntity<>, which, along the body, allows specifying the response code:

import org.springframework.http.ResponseEntity;
...
public ResponseEntity<A> get(...) {

  // if found ...
  return new ResponseEntity<>(a, HttpStatus.OK);

  // ... else
  return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}

Another way of statically enforcing a response code is with @ResponseStatus.


It is always a good idea to send a specific response code, instead of 200, where appropriate to communicate the most descriptive and accurate HTTP status to the client.

REST Clients

RestTemplate

TO PROCESS: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#webmvc-resttemplate

POSTing Resource. Data

This overloaded version allows you to receive the newly created resource as a domain model object:

RestTemplate restTemplate = new RestTemplate();

MyResource model = new MyResource(...);

MyResource created = restTemplate.postForObject("http://localhost:8080/myresource", model, MyResource.class);