Spring Boot Building RESTful Services Questions and Answers — Questions and Answers
Question 1: A developer needs to create a REST endpoint that returns a `201 Created` status code upon successful creation of a resource, and a response body containing the newly created object. Which approach is most appropriate for this scenario in a Spring Boot controller?
- Return a `ResponseEntity` object, explicitly setting the status to `HttpStatus.CREATED` and including the object in the body. (Correct answer)
- Annotate the controller method with `@ResponseStatus(HttpStatus.CREATED)` and return the created object directly.
- Return the created object directly and let Spring Boot default to a `200 OK` status, as the client can infer success.
- Throw a custom `ResourceCreatedException` annotated with `@ResponseStatus(HttpStatus.CREATED)`.
Correct answer: Return a `ResponseEntity` object, explicitly setting the status to `HttpStatus.CREATED` and including the object in the body.
Returning a `ResponseEntity` provides the most control over the HTTP response. It allows you to set the status code, headers, and the body all in one object. While `@ResponseStatus` can set the code, it's less flexible if you need to add custom headers. Throwing an exception is incorrect for a success scenario.
Question 2: What is the primary purpose of including the `spring-boot-starter-hateoas` dependency in a Spring Boot project?
- To enable automatic generation of OpenAPI (Swagger) documentation for the REST API.
- To provide a centralized mechanism for handling exceptions across all controllers.
- To add support for building hypermedia-driven RESTful services by easily creating links to related resources. (Correct answer)
- To configure content negotiation to support both JSON and XML response formats automatically.
Correct answer: To add support for building hypermedia-driven RESTful services by easily creating links to related resources.
The `spring-boot-starter-hateoas` dependency integrates Spring HATEOAS, a library for creating REST representations that follow the HATEOAS (Hypermedia as the Engine of Application State) principle. Its main feature is to make it easy to add hypermedia links to your API responses, guiding the client on what actions they can take next.
Question 3: A REST service needs to support different versions of its API. A decision is made to include the version number in the URL path (e.g., `/api/v1/products` and `/api/v2/products`). Which of the following API versioning strategies does this describe?
- Query Parameter Versioning
- Custom Header Versioning
- Content Negotiation Versioning
- URI Path Versioning (Correct answer)
Correct answer: URI Path Versioning
URI Path Versioning is a common strategy where the API version is embedded directly into the URL path. This makes the version explicit and easy for clients to see and use. Other methods include passing the version as a query parameter, in a custom HTTP header, or via the `Accept` header (content negotiation).
Question 4: In a Spring Boot REST application, what is the role of the `@RestControllerAdvice` annotation?
- To define a base controller from which all other `@RestController` classes must inherit.
- To provide global, cross-controller exception handling and other request/response modifications. (Correct answer)
- To automatically convert controller method return values into JSON or XML based on the `Accept` header.
- To enable Aspect-Oriented Programming (AOP) specifically for REST controllers.
Correct answer: To provide global, cross-controller exception handling and other request/response modifications.
`@RestControllerAdvice` is a specialized `@Component` that allows you to implement centralized exception handling across all `@RestController` classes. Methods within a `@RestControllerAdvice`-annotated class can be annotated with `@ExceptionHandler` to handle specific exceptions thrown by any controller, promoting clean, DRY (Don't Repeat Yourself) error handling logic.
Question 5: A client sends a GET request to a Spring Boot REST endpoint with an `Accept` header of `application/xml`. The corresponding controller method returns a POJO. For the application to correctly serialize the POJO into XML, which dependency is typically required on the classpath?
- spring-boot-starter-thymeleaf
- jackson-dataformat-xml (Correct answer)
- spring-boot-starter-security
- spring-boot-starter-aop
Correct answer: jackson-dataformat-xml
Spring Boot uses the Jackson library for JSON serialization by default. To enable XML serialization and deserialization, you need to add the `jackson-dataformat-xml` dependency. Once this is on the classpath, Spring Boot's auto-configuration will set up the necessary `XmlMapper` to handle content negotiation for XML.
Question 6: A developer creates a custom exception, `ResourceNotFoundException`, and wants any controller that throws it to automatically result in an HTTP `404 Not Found` response without using `@ExceptionHandler`. Which annotation should be placed on the `ResourceNotFoundException` class itself to achieve this?
- @ControllerAdvice
- @ResponseBody
- @ResponseStatus(HttpStatus.NOT_FOUND) (Correct answer)
- @RequestMapping("/error")
Correct answer: @ResponseStatus(HttpStatus.NOT_FOUND)
The `@ResponseStatus` annotation can be placed directly on an exception class. When that exception is thrown from a controller and not handled by any `@ExceptionHandler`, Spring will use the status code defined in the `@ResponseStatus` annotation to construct the HTTP response. This allows for a direct mapping between an exception type and an HTTP status.
A developer needs to create a REST endpoint that returns a `201 Created` status code upon successful creation of a resource, and a response body containing the newly created object.
Which approach is most appropriate for this scenario in a Spring Boot controller?