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:
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.
Not Safe:
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:
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.
Statelessness ensures that requests can be processed by any node in a cluster of services without having to consider server-side state
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.
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.
8. Which HTTP methods does REST use?
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.
HttpMessageConverter
interface.
HttpInputMessage
to an object of specified type.HttpOutputMessage
.consumes
and produces
annotation attributes of the @RequestMapping
the consumable media types of the mapped request (defined on the server)
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.
@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.
Annotate both for class and handler methods.
@RequestMapping
mehtods are handler method, it provides information regarding when method should be called.
Has various attributes to match by:
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.
@Component
.@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.
on class: the controller becomes restcontroller.
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
HTTP method
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
@RequestBody
to have the web request body read and deserialized into an Object through an HttpMessageConverter
to method parameter.@RequestBody
can be combined with @Validated
.@ResponseBody
HttpMessageConverter
.@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.
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:
So it is very convenient for REST calls.
RestTemplate
implements a synchronous HTTP client that simplifies sending requests and also enforces RESTful principles.
%20
using percent-encoding.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();