Today's article will cover the basic questions about REST in Spring. It will be especially useful for novice programmers.
The official guide from Pivotal, which says about topics for preparation.
Spring REST is part of Spring MVC. Therefore, much of Spring MVC will be used in REST and vice versa. To learn more about Spring MVC, read this article .
To understand the concept of REST, you need to parse the acronym into its components:
REST is the transfer of resource states between a server and a client.
A resource in REST is all that can be transferred between a client and a server.
Here are some examples of resources:
Actions in REST are determined by http methods.
Get
, Post
, Put
, Delete
, Patch
, and others.
The most commonly used are denoted by the acronym CRUD:
POST
GET
PUT
DELETE
By default, REST is not secure.
You can configure security with Basic Auth, JWT, OAuth2
These are operations that do not modify resources. Here is a list of them:
Idempotent methods are methods with each invocation of which the result will be the same.
That is, the result after 1 call of such a method will be the same as the result after 10 calls of this method.
This is important for a fault tolerant API. Suppose a client wants to update a resource using a POST request? If POST is not an idempotent method, then a multiple call will cause unexpected resource updates. Using idempotent methods, you protect yourself from many mistakes.
Yes. REST scales well because it does not store state.
This means that it does not store user session information on the server.
Client information should not be stored on the server side, but should be transmitted each time to where it is needed. This is what ST means in REST, State Transfer. You pass the state, not store it on the server.
REST is also interoperable - this means that different programs written in different languages ββcan interact on it. This comes from 2 factors:
HttpMessageConverter
converts the request into an object and vice versa.
Spring has several implementations of this interface, and you can create your own.
In this case, DispatcherServlet
does not use Model and View.
In REST, Model and View do not exist at all. There is only the data supplied by the controller and the representation of the resource when the message is converted from a media type (json, xml ...) into an object.
Converter List:
BufferedImageHttpMessageConverter
- Converts a BufferedImage
to (from) image code.
Jaxb2RootElementHttpMessageConverter
- converts xml to (from) an object marked with jaxb2 annotations. Register if jaxb2 is in classpath.
MappingJackson2HttpMessageConverter
- converts JSON to (from) an object. Register if Jackson 2 is in the classpath.
StringHttpMessageConverter
- converts all media files to text / plain.
@RestController
is placed on the controller class instead of @Controller
. She points out that this class does not operate on models, but on data. It consists of @Controller
and @RequestBody
.
@Controller @ResponseBody public interface RestController
The @ResponseBody
is put on methods that work with data, not models. It does not need to be explicitly specified if @RestController
used.
Regular methods return Model
, and annotated @ResponseBody
methods return objects that are converted to media files using the HttpMessageConverter
.
This annotation is used to map requests to controller classes and methods.
Previously, it was used for class methods to indicate the URI, http method, type of data sent, etc. In newer versions of Spring, it was replaced with @GetMapping
, @PostMapping
, etc. annotations.
Now it is used only to indicate the URI to the controller class.
These are narrower annotations for mapping http methods.
@GetMapping
@PostMapping
@DeleteMapping
@PutMapping
@PatchMapping
Everything written below is also characteristic of other annotations.
Annotation @GetMapping is simply an annotation that contains @RequestMapping (method = RequestMethod.GET) .
It also allows you to fine-tune the handler method.
Its parameters (they are converted to similar @RequestMapping parameters):
path
headers
name
params
produces
consumes
- type of data received. Used in REST
By default, the annotation takes the path to the method.
@GetMapping("managers") = @GetMapping(path = "managers")
This annotation is used so that handler methods can get parameters from an http request.
A request with parameters: http://localhost:8080/getByName/name=Ivan
.
The following code will put the string Ivan
in the variable name
.
@GetMapping("getByName") public User getUserByName(@RequestParam("name") String name) { //some logic }
This annotation gets a specific part from the URI.
URI: http://localhost:8080/getById/23
The following code will put 23
in the id
variable.
@GetMapping("getById/{id}") public User getUserById(@PathVariable("id") String id) { //some logic }
GET - 200 OK
POST - 200 OK, 201 Created, 204 No Content
PUT - 200 OK, 201 Created, 204 No Content
DELETE - 204 No Content, 202 Accepted
It allows you to set a response code. Typically, Spring itself sets the desired response code, but there are times when you need to override it.
@PostMapping @ResponseStatus(HttpStatus.CREATED) public void add(...) {...}
Instead of using annotations, you can return a ResponseEntity
and manually set the response code.
Using ResponseEntity
and @ReponseStatus
together is not recommended.
This is a special class that represents an http response. It contains the response body, status code, headers. We can use it to fine tune the http response.
It is a universal type, and any object can be used as a body:
@GetMapping("/hello") ResponseEntity hello() { return new ResponseEntity("Hello World!", HttpStatus.OK); }
You can use the @RequestBody
annotation on a method parameter so that the request body is converted to this parameter.
@PostMapping("accounts") //, JSON Account public void handle(@RequestBody Account account) {...}
You can use @Validated
together with @RequestBody
to check for a received request.
RestTemplate is a special client in Spring for sending http requests. It provides convenient APIs for easily calling REST endpoints on a single line.
RestTemplate restTemplate = new RestTemplate(); String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
You can learn more about usage in this article .