Preparing for Spring Professional Certification. Spring rest

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.













Table of contents
  1. Dependency injection, container, IoC, beans
  2. AOP (aspect-oriented programming)
  3. JDBC, Transactions, JPA, Spring Data
  4. Spring boot
  5. Spring mvc
  6. Spring security
  7. REST
  8. Testing





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 .







What was REST created for?

To understand the concept of REST, you need to parse the acronym into its components:







  • Representational - resources in REST can be represented in any form - JSON, XML, text, or even HTML - depends on which data is more suitable for the consumer
  • State - when working with REST, you should be focused on the state of the resource, and not on actions with the resource
  • Transfer - REST includes the transfer of resource data, in any form presented, from one application to another.


REST is the transfer of resource states between a server and a client.







What is a resource?

A resource in REST is all that can be transferred between a client and a server.

Here are some examples of resources:







  • News
  • Temperature in St. Petersburg on Monday at 4 a.m.
  • Employee salary
  • Database selection
  • Search results


What does CRUD stand for?

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:







  • Create - POST



  • Read - GET



  • Update - PUT



  • Delete - DELETE





Is REST safe? How can you protect him?

By default, REST is not secure.







You can configure security with Basic Auth, JWT, OAuth2





.

What is save operations?

These are operations that do not modify resources. Here is a list of them:







  • Get
  • HEAD
  • OPTIONS


What is an idempotent operation? Why is idempotency important?

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.







Does REST scale well?

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:







  • Interoperable HTTP clients. Different clients must send the same http requests.
  • Interoperability at the level of media types. Different clients must correctly send and receive the same resources.


What is an HttpMessageConverter?

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.







How does the @RestController annotation work?

@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
      
      





Why @ResponseBody?

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



.







What does the @RequestMapping annotation do?

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.







What are annotations @GetMapping, @PostMapping, @DeleteMapping and others?

These are narrower annotations for mapping http methods.







  • @GetMapping



    - Handles get requests
  • @PostMapping



    - Handles post requests
  • @DeleteMapping



    - Handles delete requests
  • @PutMapping



    - Handles put requests
  • @PatchMapping



    - Handles patch requests


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



    - URI
  • headers



    - headers
  • name



    - handler name
  • params



    - parameters
  • produces



    - type of returned data (JSON, XML, text). Used in REST
  • consumes



    - type of data received. Used in REST







    By default, the annotation takes the path to the method.

    @GetMapping("managers") = @GetMapping(path = "managers")











Why use the @RequestParam annotation?

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 }
      
      





Why use the @PathVariable annotation?

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 }
      
      





What do the different codes for http responses mean?

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







Why do I need @ResponseStatus annotation?

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.







What is a ResponseEntity?

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); }
      
      





Why @RequestBody?

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.







What is a RestTemplate? What are its advantages?

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 .








All Articles