38-Creating a Complete REST Application Flashcards
What does REST stand for?
REpresentational State Transfer
What does REST emphasize?
Scalability
What does HATEOAS stand for?
Hypermedia As The Engine of Application State
What is the REST specification in Java?
JAX-RS
Implementations of JAX-RS
- Jersey (RI)
- RESTEasy
- Restlet
- CXF
What JAX-RS implementations are supported by Spring?
- Jersey (RI)
- RESTEasy
- Restlet
- CXF
Does Spring MVC implement JAX-RS?
No
What combined request mapping annotations are supported?
- GetMapping
- PostMapping
- PutMapping
- PatchMapping
- DeleteMapping
What request methods must use @RequestMapping?
- HEAD
- OPTIONS
- TRACE
How to use @RequestMapping?
e.g. @RequestMapping(path=”hello”, method=RequestMethod.GET)
What request mappings are implemented automatically by Spring?
- HEAD
2. OPTIONS
What objects help to translate JSON to Java objects and vice versa?
Message converters
Which controller method do we need to return a ResponseEntity?
For POST as we need to return the location of the created object
e.g. return ResponseEntity.created(location).build()
What response should PUT return?
204 no content and empty body
What response should DELETE return?
204 no content and empty body
What response should POST return?
201 created with “Location” in the response header
HTTP status code of Unsupported Media Type
415 - might be due to the request’s indicated Content-Type or Content-Encoding
HTTP status code of cannot generate response body in the requested format
406 Not Acceptable
Due to Accept, Accept-Encoding or Accept-Language
HTTP status code of method not supported
405
By default, what is the result of controller methods?
view name
How to override HTTP status of void method?
@ResponseStatus(HttpStatus.OK) void controllerMethod() {}
How to build the location for POST requests?
Using ServletUriComponentsBuilder e.g. URI location = ServletUriComponentsBuilder .fromCurrentRequestUri() .path("/{resourceId}") .buildAndExpand(resourceId) .toUri(); return ResponseEntity.created(location).build();
What is the return type of a POST controller method?
ResponseEntity
UriComponentsBuilder vs. ServletUriComponentsBuilder
UriComponentsBuilder must hard-code URL
ServletUriComponentsBuilder extends UriComponentsBuilder but allows building from relative API path
What is the difference between RestTemplate.xxxForObject and RestTemplate.xxxForEntity?
- xxxForObject(String, Class, Object… urlVariables): T
return response object if any or null if not found - xxxForEntity(String, Class, Object… urlVariables): ResponseEntity
How to create a custom RestTemplate?
Inject RestTemplateBuilder and call .build()
Example of urlVariables in RestTemplate.xxxForObject
String uri = “/accounts/{id}”;
User user = restTemplate.xxxForObject(uri, User.class, “1”);
How to setup your custom API request?
Using RequestEntity
e.g.
request = RequestEntity.post(uri)
.getHeaders().add(HttpHeaders.Authorization, auth)
.contentType(MediaType.APPLICATION_JSON)
.body(newItem);
ResponseEntity response = restTemplate.exchange(request, Void.class);
What is WebClient?
- New client, Support streaming
2. Will Replace RestTemplate
How to customize response status for an exception?
e.g. @ResponseStatus(HttpStatus.NOT_FOUND) class OrderNotFound extends RuntimeException {} from now, when this exception thrown, client will receive 404 instead of 500
How to customize response status for existing exceptions (i.e. exceptions from third-party libs)?
Create method inside the controller e.g.
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler({DataIntegrityViolationException.class})
public void conflict() {
// could add the exception, response, etc. as method params
}
Example of calling a GET API to get a user by id using WebClient
e.g. client = WebClient.create(); Mono result = client.get() .uri("/users/{id}", 1) .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(User.class); return result.block();
Helper class to build a link for HATEOAS API?
Using ControllerLinkBuilder
What HypermediaType is supported by Spring HATEOAX API?
Only HAL for now
Example of building a method with HATEOAS response
- Enable HATEOAS
@Configuration
@EnableHypermediaSupport(type=HypermediaType.HAL)
public class MyConfig { } - Using @Controller for controller class (not @RestController)
- Return Resource
e.g.
public @ResponseBody Resource method() {
Links[] = …; // Some links (see previous slide)
return new Resource(order, links);
}
What links does Spring HATEOAS support?
ATOM and HAL
List out 10 arguments in a controller method
- WebRequest, NativeWebRequest
- ServletRequest, ServletResponse
- HttpSession
- Principal
- HttpMethod
- Locale
- InputStream, Reader, OutputStream, Writer
- @PathVariable, @RequestBody, @RequestParam, @MatrixVariable
- @ModelAttribute, @RequestAttribute, @SessionAttribute, @RedirectAttribytes
- HttpEntity
- @RequestHeader