Spring / Spring Boot 4 Basics Interview Questions
How do you build REST APIs with Spring Boot 4 using @RestController?
Building REST APIs in Spring Boot 4 uses the same @RestController + @RequestMapping model as previous versions, but with native API versioning, improved validation integration, and better null safety via JSpecify.
import jakarta.validation.Valid; import jakarta.validation.constraints.*; import org.jspecify.annotations.Nullable; @RestController @RequestMapping("/api/orders") @Validated public class OrderController { private final OrderService service; public OrderController(OrderService service) { this.service = service; } // GET all with pagination @GetMapping public Page<OrderDto> listOrders( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) { return service.findAll(PageRequest.of(page, size)); } // GET by ID @GetMapping("/{id}") public ResponseEntity<OrderDto> getOrder(@PathVariable String id) { return service.findById(id) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } // POST: create new order @PostMapping @ResponseStatus(HttpStatus.CREATED) public OrderDto createOrder(@Valid @RequestBody CreateOrderRequest request) { return service.create(request); } // PUT: full update @PutMapping("/{id}") public OrderDto updateOrder( @PathVariable String id, @Valid @RequestBody UpdateOrderRequest request) { return service.update(id, request); } // DELETE @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteOrder(@PathVariable String id) { service.delete(id); } // Native API versioning (Spring Boot 4): @GetMapping(path = "/{id}", version = "2.0") public OrderDtoV2 getOrderV2(@PathVariable String id) { return service.findByIdV2(id); } // Global exception handler: @ExceptionHandler(OrderNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ErrorResponse handleNotFound(OrderNotFoundException ex) { return new ErrorResponse("ORDER_NOT_FOUND", ex.getMessage()); } }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
