Building a REST API with Spring Boot
Building a REST API with Spring Boot
Spring Boot makes building REST APIs remarkably fast. With a few annotations you can have a fully functional API with JSON serialization, validation, and error handling.
Project Setup
Start with the Spring Initializr. Select Spring Web and Spring Data JPA. Spring Boot auto-configures Jackson for JSON conversion, an embedded Tomcat, and much more.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The Model
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
private String category;
// getters and setters
}
The Controller
The @RestController annotation combines @Controller and @ResponseBody. Every method return value is serialized to JSON automatically.
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
public List<Product> getAll() {
return productService.findAll();
}
@GetMapping("/{id}")
public Product getById(@PathVariable Long id) {
return productService.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product not found"));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product create(@Valid @RequestBody Product product) {
return productService.save(product);
}
@PutMapping("/{id}")
public Product update(@PathVariable Long id, @Valid @RequestBody Product product) {
return productService.update(id, product);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
productService.delete(id);
}
}
Auto-Configuration Magic
Spring Boot detects Jackson on the classpath and automatically configures message converters. Return a Java object from a controller method and it becomes JSON in the response. Send JSON in the request body with @RequestBody and Spring parses it into a Java object.
Running It
Run the main class. The API is live at http://localhost:8080/api/products. No XML configuration. No deployment descriptor. Just annotations and code.
Key Points
@RestControllermakes every method return JSON automatically.@GetMapping,@PostMapping,@PutMapping,@DeleteMappingmap HTTP methods.@RequestBodydeserializes JSON input; return values serialize to JSON.- Spring Boot auto-configures Jackson, Tomcat, and message converters.
- Use
@Validwith Bean Validation for automatic input validation.