Building REST APIs with Spring Boot
Design REST endpoints. Learn route mappings, request body mappings, JSON responses, status code configs, and controller validation.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is @RestController and how is it different from @Controller?
@RestController is a convenience annotation that combines @Controller and @ResponseBody. It marks a class as a request handler where every method's return value is written directly to the HTTP response body, serialized as JSON or XML, instead of being resolved to a view name.
@Controller alone is used for traditional MVC apps that return view names (e.g., Thymeleaf templates); to return data directly from a @Controller method you would need to add @ResponseBody on every method. @RestController applies that behavior class-wide, which is why it's the standard choice for building REST APIs.
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
Q2. What are the common HTTP mapping annotations in Spring Boot (@GetMapping, @PostMapping, etc.)?
Spring Boot provides shorthand annotations for each HTTP method, all specializations of @RequestMapping: @GetMapping for retrieving resources, @PostMapping for creating resources, @PutMapping for full updates, @PatchMapping for partial updates, and @DeleteMapping for removing resources.
Each maps a controller method to a URL path and restricts it to that HTTP verb, making the API's intent explicit and letting Spring route requests to the correct method automatically based on both path and method.
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping public List<Product> getAll() { ... }
@PostMapping public Product create(@RequestBody Product p) { ... }
@PutMapping("/{id}") public Product update(@PathVariable Long id, @RequestBody Product p) { ... }
@DeleteMapping("/{id}") public void delete(@PathVariable Long id) { ... }
}
Q3. What is the difference between @PathVariable and @RequestParam?
@PathVariable extracts a value from the URI path itself, used when the value identifies a specific resource, e.g. /users/{id}. @RequestParam extracts a value from the query string, used for optional filters, pagination, or sorting parameters, e.g. /users?page=2&size=10.
Both can be marked required or optional and support default values, but path variables are conventionally used for resource identity while request parameters are used for query-level options.
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
@GetMapping("/users")
public List<User> search(@RequestParam(defaultValue = "0") int page,
@RequestParam(required = false) String name) { ... }
Q4. How do you validate request bodies in Spring Boot?
Spring Boot integrates with Bean Validation (JSR-380 / Jakarta Validation) via spring-boot-starter-validation. Constraints like @NotNull, @NotBlank, @Size, and @Email are placed on a DTO's fields, and the controller method parameter is annotated with @Valid or @Validated so Spring runs the checks automatically before the method body executes.
If validation fails, Spring throws a MethodArgumentNotValidException, which is typically caught in a @ControllerAdvice to return a structured 400 Bad Request response with field-level error messages.
public class UserDto {
@NotBlank private String name;
@Email private String email;
}
@PostMapping
public User create(@Valid @RequestBody UserDto dto) { ... }
Q5. How do you handle exceptions globally in Spring Boot using @ControllerAdvice?
@ControllerAdvice defines a global exception-handling component that applies across all controllers, keeping error-handling logic out of individual controller methods. Inside it, methods annotated with @ExceptionHandler(SomeException.class) catch a specific exception type and return a consistent error response.
Combined with a ResponseEntity, this pattern centralizes error formatting — mapping exceptions like ResourceNotFoundException to 404, validation errors to 400, and unexpected exceptions to 500 — so every endpoint returns errors in the same shape.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(ex.getMessage()));
}
}
Q6. What is ResponseEntity and when should you use it?
ResponseEntity represents the entire HTTP response — status code, headers, and body — giving full control over what's returned, unlike a plain return type where Spring infers a 200 OK by default.
It is used whenever the response needs a specific status code (201 Created after a POST, 404 Not Found, 204 No Content for a delete), custom headers (like a Location header pointing to a newly created resource), or conditional responses based on business logic.
@PostMapping
public ResponseEntity<User> create(@Valid @RequestBody UserDto dto) {
User saved = userService.save(dto);
URI location = URI.create("/api/users/" + saved.getId());
return ResponseEntity.created(location).body(saved);
}
Q7. How does Jackson serialize and deserialize JSON in Spring Boot, and how do you customize it?
Spring Boot auto-configures Jackson's ObjectMapper as the default HTTP message converter, so any object returned from a @RestController method is automatically serialized to JSON, and any incoming JSON body annotated with @RequestBody is deserialized into a Java object using matching field names or getters/setters.
Customization is done with annotations like @JsonProperty to rename fields, @JsonIgnore to exclude a field, @JsonFormat for date formatting, or by defining a custom ObjectMapper bean to change global settings such as date serialization or null handling.
public class User {
@JsonProperty("full_name")
private String name;
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate createdAt;
@JsonIgnore
private String password;
}
Q8. What is Content Negotiation in Spring Boot REST APIs?
Content negotiation is the process by which Spring determines the representation format (JSON, XML, etc.) to return based on the client's Accept header, a URL path extension, or a query parameter. Spring Boot uses JSON by default when spring-boot-starter-web is present, since Jackson is on the classpath.
To support additional formats like XML, you add the corresponding converter dependency (e.g. Jackson's XML module) and Spring automatically negotiates based on the request's Accept header without any controller code changes, since the HttpMessageConverter mechanism handles the format selection.
// Client requests XML:
// GET /api/users/1
// Accept: application/xml
//
// Same controller method returns XML automatically
// once jackson-dataformat-xml is on the classpath.
Q9. How do you version a REST API in Spring Boot?
Common API versioning strategies in Spring Boot include URI versioning (/api/v1/users, /api/v2/users), request parameter versioning (/api/users?version=1), custom header versioning (X-API-Version: 1), and media-type versioning via the Accept header (application/vnd.company.v1+json).
URI versioning is the most common because it's explicit, cacheable, and easy to route with @RequestMapping("/api/v1/...") on separate controller classes; header and media-type versioning keep URLs stable but require more setup with custom request-mapping conditions.
@RestController
@RequestMapping("/api/v1/users")
public class UserControllerV1 { ... }
@RestController
@RequestMapping("/api/v2/users")
public class UserControllerV2 { ... }
Q10. How do you document a Spring Boot REST API with OpenAPI/Swagger?
Spring Boot REST APIs are documented using springdoc-openapi (the modern successor to SpringFox), which scans controllers and generates an OpenAPI 3 specification automatically, along with an interactive Swagger UI page for testing endpoints in the browser.
Adding the springdoc-openapi-starter-webmvc-ui dependency is enough to get a working /swagger-ui.html page with zero configuration; annotations like @Operation, @Parameter, and @ApiResponse are then added to controller methods to enrich the generated docs with descriptions and example responses.
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
@Operation(summary = "Get a user by ID")
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) { ... }
Building REST APIs with Spring Boot
Design REST endpoints. Learn route mappings, request body mappings, JSON responses, status code configs, and controller validation.
What is @RestController and how is it different from @Controller?
@RestController is a convenience annotation that combines @Controller and @ResponseBody. It marks a class as a...
What are the common HTTP mapping annotations in Spring Boot (@GetMapping, @PostMapping, etc.)?
Spring Boot provides shorthand annotations for each HTTP method, all specializations of @RequestMapping: @GetM...
What is the difference between @PathVariable and @RequestParam?
@PathVariable extracts a value from the URI path itself, used when the value identifies a specific resource, e...
How do you validate request bodies in Spring Boot?
Spring Boot integrates with Bean Validation (JSR-380 / Jakarta Validation) via spring-boot-starter-validation....
How do you handle exceptions globally in Spring Boot using @ControllerAdvice?
@ControllerAdvice defines a global exception-handling component that applies across all controllers, keeping e...
What is ResponseEntity and when should you use it?
ResponseEntity represents the entire HTTP response — status code, headers, and body — giving full control over...
How does Jackson serialize and deserialize JSON in Spring Boot, and how do you customize it?
Spring Boot auto-configures Jackson's ObjectMapper as the default HTTP message converter, so any object return...
What is Content Negotiation in Spring Boot REST APIs?
Content negotiation is the process by which Spring determines the representation format (JSON, XML, etc.) to r...
How do you version a REST API in Spring Boot?
Common API versioning strategies in Spring Boot include URI versioning (/api/v1/users, /api/v2/users), request...
How do you document a Spring Boot REST API with OpenAPI/Swagger?
Spring Boot REST APIs are documented using springdoc-openapi (the modern successor to SpringFox), which scans...