Spring Study Guide – Rest

 

1. What does REST stand for?

REpresentational State Transfer. It is for stateless communication between a client(Web, Mobile, Server, etc) and a server.

2. What is a resource?

An entity, model, or data that you interact with. It is basically any information, like data, Json, xml, html, file, image, etc.

Resource can be identified by a Uniform Resource Identifier (URI).

3. What does CRUD mean?

C – create
R – read
U – update
D – delete

4. Is REST secure? What can you do to secure it?

REST is not secure by default.

To secure it, can use:

  • HTTPS
  • Basic Authentication
  • JSON Web Tokens (JWT)
  • OAuth2

We also use Spring Security to secure our REST API.

5. What are safe REST operations?

Safe methods are HTTP methods that do not modify resources. Spring Security implements CSRF protection with a synchronizer token. Statechanging requests(not safe methods) will be intercepted and checked for a CSRF token.

  • GET
  • HEAD
  • OPTIONS
  • TRACE

Not Safe:

  • POST: Two identical POST requests will result in two identical resources being created or errors at application level.
  • PUT: it modifies the state on the server
  • DELETE

6. What are idempotent operations? Why is idempotency important?

Idempotent means you can repeat these operations over and over again, but the end result should be the same.

Idempotency operations:

  • GET
  • PUT
  • DELETE

Idempotency is important for understanding the limits of effect some operation has on resources.

7. Is REST scalable and/or interoperable?

Because of the stateless nature of REST, it is easily scalable and due to its HTTP usage, it is highly interoperable because many systems support HTTP.

Scalability

REST is scalable, because it is stateless, its Cacheability and layered system.

  1. Statelessness ensures that requests can be processed by any node in a cluster of services without having to consider server-side state

  2. Cacheability allows for creating responses from cached information without the request having to proceed to the actual service, which improves network efficiency and reduces the load on the service.

  3. A layered system allows for introducing intermediaries such as a load balancer without clients having to modify their behavior as far as sending requests to the service is concerned. The load balancer can then distribute the requests between multiple instances of the service in order to increase the request-processing capacity of the service.

Interoperability

The ability to exchange and make use of information.

  1. REST service supports all formats of data: xml, json, file html
  2. Resource can be identified by a Uniform Resource Identifier (URI). No special language needed
  3. CRUD standard operation

8. Which HTTP methods does REST use?

  1. GET – for read
  2. PUT – for update/replace 
  3. POST – for create
  4. PATCH – for update/modify
  5. DELETE – for delete

9. What is an HttpMessageConverter?

HttpMessageConverters convert HTTP requests to objects and back from objects to HTTP responses. Spring has a list of converters that is registered by default but it is customizable – additional implementations may be plugged in.

  1. The resource representation can have different formats: XML, JSON, HTML, etc.
  2. The client must know the format to use, or request a resource with a representation it understands form the server.
  3. Representations are converted to HTTP requests and from HTTP responses by implementations HttpMessageConverter interface.
    • Convert a HttpInputMessage to an object of specified type.
    • Convert an object to a HttpOutputMessage.
  4. Message converters are automatically detected and used by Spring
  5. JSON format, so MappingJackson2HttpMessageConverter is used.
  6. the consumes and produces annotation attributes of the @RequestMapping
    • The consumes attribute defines
      1. the consumable media types of the mapped request (defined on the server)

      2. the value of the Content-Type header (defined on the client side) must match at least one of the values of this property in order for a method to handle a specific REST request.

    • The produces attribute defines the producible media types of the mapped request, narrowing the primary mapping, and the value of the Accept header (on the client side) must match at least one of the values of this property in order for a method to handle a specific REST request.
@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = {"com.ps.web", "com.ps.exs"}) 
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override 
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);
    converters.add(mappingJackson2HttpMessageConverter()); 
  }
  
  @Bean
  public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); // when client is a browser JSON response is displayed indented 
    mappingJackson2HttpMessageConverter.setPrettyPrint(true); //set encoding of the response 
    mappingJackson2HttpMessageConverter.setDefaultCharset (StandardCharsets.UTF_8); 
    mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper()); 
    return mappingJackson2HttpMessageConverter;
  }
}

 

10. Is REST normally stateless?

REST is stateless because according to its definition it HAS to be stateless; meaning each request must contain all the required information to interact with the server without the server needing to store some context between requests. The same can be said about authentication – each request holds the authentication info required for interacting with the server.

11. What does @RequestMapping do?

@RequestMapping defines a handler method or class to process HTTP calls. 

  1. Annotate both for class and handler methods.

  2. @RequestMapping mehtods are handler method, it provides information regarding when method should be called.

  3. Has various attributes to match by:

    • URL,
    • HTTP method,
    • request parameters,
    • headers,
    • produces: media types,
    • consumes: media type

12. Is @Controller a stereotype? Is @RestController a stereotype?

@Controller is a stereotype whilst @RestController is not and is declared in a different package.

What is a stereotype annotation? What does that mean?

Stereotype annotations are annotations that are applied to classes that fulfills a certain, distinct, role.

  • The main stereotype annotation is @Component.
  • Both @Controller and @RestController are stereotypes
  • @Controller + @ResponseBody = @RestController

13. What is the difference between @Controller and @RestController?

@Controller result is passed to a view.

@RestController result is processed by a HttpMessageConverter.

For a @Controller to act as a @RestController it has to be combined with @ResponseBody.

14. When do you need @ResponseBody?

@ResponseBody is required when you want a controller result to pass to a message converter rather than to a view resolver. For example, you want a JSON object instead of a view.

With Spring 4.0, the @ResponseBody annotation has been moved to the type level, so it can be added to interfaces, classes, or other annotations.

  1. on class: the controller becomes restcontroller.

  2. on method: return serialized data througth HttpMessageConverter to response body, rather than passing the model and view.

@RequestMapping(value="/test", 
  produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) 
public @ResponseBody List<Journal> getJournal(){ 
  return repo.findAll(); 
}
   
@ResponseStatus(HttpStatus.OK) 
@RequestMapping(value = "/listdata", method = RequestMethod.GET) 
@ResponseBody 
public Singers listData() { 
  return new Singers(singerService.findAll()); 
}

 

15. What does @PathVariable do?

@PathVariable maps a part of the URL, an URI template variable, to a handler method argument. 

@GetMapping("/api/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) {
    return "ID: " + id + ", name: " + name;
}
@GetMapping(value = { "/api/employeeswithrequired", "/api/employeeswithrequired/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequired(@PathVariable String id) {
    return "ID: " + id;
}
@GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" })
@ResponseBody
public String getEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
    if (id.isPresent()) {
        return "ID: " + id.get();
    } else {
        return "ID missing";
    }
}

 

16. What are the HTTP status return codes for a successful GET, POST, PUT or DELETE operation?

200 for success

400 for error

HTTP response codes

  1. 1XX: information. Request hs been received and processing of it continues.
  2. 2XX: Successful. Successfully received, understood and accepted.
  3. 3XX: Redirection. Further action is needed to complete the request.
  4. 4XX: Client error. Request is invalid.
  5. 5XX: Server error. Server is unavailable for a valid request.

HTTP method

  1. GET: 200 OK
  2. POST: 200 OK, 201 Created, 204 No Content
  3. PUT: 200 OK, 201 Created, 204 No Content
  4. DELETE: 204 No Content, 202 Accepted, 205 Reset Content (not performed)

17. When do you need @ResponseStatus?

@ResponseStatus will prevent DispatcherServlet from trying to find a view for the result and will set a status for the response. So when you need another form of response instead of a view you use @ResponseStatus.

It’s always a good idea to use @ResponseStatus where appropriate to communicate the most descriptive and accurate HTTP status code to the client.

 

18. Where do you need @ResponseBody? What about @RequestBody? Try not to get these muddled up!

@ResponseBody is required when you want a controller result to be passed to a message converter rather than to a view resolver.

@RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object.

@PostMapping("/signup")
public ResponseEntity<SessionDTO> signUp(@Valid @RequestBody MemberSignupCreateDTO memberCreateDTO){
		...
}

@RequestBody

  1. @RequestBody to have the web request body read and deserialized into an Object through an HttpMessageConverter to method parameter.
  2. @RequestBody can be combined with @Validated.

@ResponseBody

  1. To have the return serialized to the response body through an HttpMessageConverter.
  2. @ResponseStatus can be combined to specify response status.

If you saw example Controller code, would you understand what it is doing? Could you tell if it was annotated correctly?

yes

@RestController 
@RequestMapping(value = "/singer") 
public class SingerController { 

  final Logger logger = LoggerFactory.getLogger(SingerController.class);
  
  @Autowired 
  private SingerService singerService;

  @ResponseStatus(HttpStatus.OK) 
  @GetMapping(value = "/listdata") 
  public List<Singer> listData() { 
    return singerService.findAll(); 
  }
  
  @ResponseStatus(HttpStatus.OK) 
  @GetMapping(value = "/{id}") 
  public Singer findSingerById(@PathVariable Long id) { 
    return singerService.findById(id); 
  }
  
  @ResponseStatus(HttpStatus.CREATED) 
  @PostMapping(value="/") 
  public Singer create(@RequestBody Singer singer) {
  
    logger.info("Creating singer: " + singer);
    singerService.save(singer);
    logger.info("Singer created successfully with info: " + singer);
    return singer; 
  }
  
  @PostMapping 
  public Book create(@RequestBody Book book, UriComponentsBuilder uriBuilder) {
  
    Book created = bookService.create(book);
    URI newBookUri = uriBuilder
      .path("/books/{isbn}")
      .build(created.getIsbn());
    
    return ResponseEntity
      .created(newBookUri)
      .body(created); 
  }
}

 

19. Do you need Spring MVC in your classpath?

Yes. Spring MVC is the core component of REST.

  • The spring-mvc.jar is not part of spring-core.
  • spring-web module must be present on the classpath.

20. What Spring Boot starter would you use for a Spring REST application?

spring-boot-starter-web: “Starter for building web, including RESTful, applications using Spring MVC.”

21. What are the advantages of the RestTemplate?

RestTemplate is used to make HTTP Rest Calls (REST Client).
Without RestTemplate, If we want to make an HTTP call, we need to create an HttpClient, pass request and form parameters, setup accept headers and perform unmarshalling of response, all by yourself. Spring RestTemplate tries to take that pain away by abstracting all these details from you.

RestTemplate has methods specific to HTTP methods:

  1. DELETE
  2. GET
  3. HEAD
  4. OPTIONS
  5. POST
  6. PUT

So it is very convenient for REST calls.

 

RestTemplate implements a synchronous HTTP client that simplifies sending requests and also enforces RESTful principles.

  • Provides a higher-level API to perform HTTP requests compared to traditional HTTP client libraries.
  • Supports URI templates
  • Automatically encodes URI templates. For example, a space character in an URI will be replaced with %20 using percent-encoding.
  • Supports automatic detection of content type
  • Supports automatic conversion between objects and HTTP messages.
  • Allows for easy customization of response errors. A custom ResponseErrorHandler can be registered on the RestTemplate.
  • Provides methods for conveniently sending common HTTP request types and also provides methods that allow for increased detail when sending requests. Examples of the former method type are: delete, getForObject, getForEntity, headForHeaders, postForObject and put.

22. If you saw an example using RestTemplate would you understand what it is doing?

yes.

String uriTemplate = "http://example.com/hotels/{hotel}";
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).build(42);

RequestEntity<Void> requestEntity = RequestEntity.get(uri)
        .header(("MyRequestHeader", "MyValue")
        .build();

ResponseEntity<String> response = template.exchange(requestEntity, String.class);

String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
String body = response.getBody();

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.