Building Robust REST APIs with Java and Spring Boot
Spring Boot has become the de facto standard for building production-ready Java applications. By favoring convention over configuration, it lets developers focus on business logic instead of boilerplate setup. In this post, we'll explore how to build a clean, maintainable REST API.
Why Spring Boot?
Spring Boot offers several advantages that make it a compelling choice:
- Auto-configuration that wires up sensible defaults
- Embedded servers like Tomcat, so no external deployment is needed
- Production-ready features such as health checks and metrics via Actuator
- A vast ecosystem of starters for data, security, messaging, and more
Setting Up the Project
The quickest way to bootstrap a project is through start.spring.io. Once generated, your pom.xml will include the core web starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Defining a Model
Let's start with a simple domain object representing a product.
public class Product {
private Long id;
private String name;
private double price;
public Product(Long id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
// Getters and setters omitted for brevity
}
Creating a REST Controller
The @RestController annotation combines @Controller and @ResponseBody, so return values are serialized directly to JSON.
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final Map<Long, Product> store = new ConcurrentHashMap<>();
@GetMapping("/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
Product product = store.get(id);
if (product == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(product);
}
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
store.put(product.getId(), product);
return ResponseEntity.status(HttpStatus.CREATED).body(product);
}
}
Handling Errors Gracefully
A clean API should return consistent error responses. Use @RestControllerAdvice to centralize exception handling.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleBadRequest(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(ex.getMessage());
}
}
Conclusion
Spring Boot dramatically reduces the friction of building REST APIs in Java. With just a few annotations, you get a fully functional web service backed by a production-grade framework. From here, you can layer in persistence with Spring Data JPA, secure endpoints with Spring Security, and monitor your app with Actuator.
Happy coding!
Top comments (0)