Spring Boot: Building REST APIs
Spring Boot simplifies the creation of robust, production-ready REST APIs with minimal configuration. As a modern Java framework, it eliminates boilerplate code and provides built-in support for dependency injection, auto-configuration, and embedded servers—making it the industry standard for enterprise-grade API development. Let’s build a practical REST API from scratch.
Why Spring Boot Excels for REST APIs
Spring Boot’s zero-configuration approach accelerates API development while ensuring scalability and maintainability. Unlike traditional Spring MVC setups, Spring Boot auto-configures beans for HTTP clients, database connections, and security without explicit XML declarations. This allows developers to focus on business logic rather than infrastructure. For example, adding spring-boot-starter-web to your pom.xml instantly enables REST endpoints without manual setup.
Creating Your First REST API
Start with a minimal project using Spring Initializr. Select Spring Web and Lombok to generate boilerplate-free code. Here’s a runnable example:
<code class="language-java">import org.springframework.web.bind.annotation.*;
<p>import java.util.*;</p>
<p>@RestController</p>
<p>@RequestMapping("/api/users")</p>
<p>public class UserController {</p>
<p> private final List<User> users = new ArrayList<>();</p>
<p> @GetMapping</p>
<p> public List<User> getAllUsers() {</p>
<p> return users;</p>
<p> }</p>
<p> @PostMapping</p>
<p> public User createUser(@RequestBody User newUser) {</p>
<p> users.add(newUser);</p>
<p> return newUser;</p>
<p> }</p>
<p> // Helper class (omitted for brevity)</p>
<p> static class User {</p>
<p> private String name;</p>
<p> private int age;</p>
<p> // Lombok @Data generates getters/setters</p>
<p> }</p>
<p>}</code>
This endpoint exposes two critical operations:
GET /api/users→ Returns all usersPOST /api/users→ Creates a new user
Key insight: Spring Boot automatically maps @RestController and @RequestMapping annotations to HTTP endpoints. The @RequestBody annotation binds JSON payloads to Java objects—no manual JSON parsing required.
Handling HTTP Methods and Request Mapping
Spring Boot supports all standard HTTP methods with intuitive annotations:
| Method | Annotation | Purpose |
|---|---|---|
| GET | @GetMapping |
Retrieve resources |
| POST | @PostMapping |
Create new resources |
| PUT | @PutMapping |
Update existing resources |
| DELETE | @DeleteMapping |
Remove resources |
Practical example: Update a user via PUT:
<code class="language-java">@PutMapping("/{id}")
<p>public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {</p>
<p> // Logic to update user by ID</p>
<p> return updatedUser;</p>
<p>}</code>
Pro tip: Use @PathVariable for route parameters (e.g., id) and @RequestBody for complex payloads. Spring Boot validates these automatically—no extra parsing logic needed.
Request and Response Mapping
Spring Boot handles JSON serialization and deserialization seamlessly using Jackson. Here’s how it works:
- Request mapping: JSON payloads are automatically converted to Java objects via
@RequestBody. - Response mapping: Java objects are converted to JSON responses by default.
Real-world example: A POST request with JSON payload:
<code class="language-json">{
<p> "name": "Alice",</p>
<p> 25</p>
<p>}</code>
Becomes a User object in Java. Spring Boot returns a 201 Created response with the same JSON structure.
Customization: Override default serialization with @JsonFormat:
<code class="language-java">@JsonFormat(pattern = "yyyy-MM-dd") <p>private Date birthDate;</code>
Monitoring with Spring Boot Actuator
Spring Boot Actuator provides built-in endpoints for API health checks, metrics, and configuration. Enable it with spring.actuator.enabled=true in application.properties:
<code class="language-yaml"># application.properties <p>management.endpoints.web.exposure.include=health,metrics,beans</code>
Critical endpoints:
GET /actuator/health→ Returns system health status (UP/DOWN)GET /actuator/metrics→ Shows response times, error rates, and throughputGET /actuator/beans→ Lists all Spring beans (useful for debugging)
Why this matters: Actuator helps you monitor API performance without external tools—critical for production environments.
Error Handling
Spring Boot includes automatic error handling via @ControllerAdvice. Handle exceptions globally:
<code class="language-java">@ControllerAdvice
<p>public class GlobalExceptionHandler {</p>
<p> @ExceptionHandler(ResourceNotFoundException.class)</p>
<p> public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {</p>
<p> return ResponseEntity.status(404).body(new ErrorResponse("Resource not found", ex.getMessage()));</p>
<p> }</p>
<p>}</code>
Key patterns:
- Create custom exceptions (e.g.,
ResourceNotFoundException) - Return consistent
4xx/5xxresponses with descriptive messages - Use
@ExceptionHandlerfor specific exception types
Example response:
<code class="language-json">{
<p> "error": "Resource not found",</p>
<p> "message": "User with ID 123 does not exist"</p>
<p>}</code>
Security for REST APIs
While beyond the scope of this section, Spring Boot integrates with Spring Security for API protection. A minimal setup:
<code class="language-java">@Configuration
<p>public class SecurityConfig extends WebSecurityConfigurerAdapter {</p>
<p> @Override</p>
<p> protected void configure(HttpSecurity http) throws Exception {</p>
<p> http</p>
<p> .authorizeRequests()</p>
<p> .antMatchers("/api/users/**").hasRole("ADMIN")</p>
<p> .anyRequest().permitAll()</p>
<p> .and()</p>
<p> .addFilterBefore(new JwtTokenFilter(), BasicFilterChain.class);</p>
<p> }</p>
<p>}</code>
This enforces role-based access control (RBAC) for /api/users endpoints—essential for enterprise applications.
Summary
Spring Boot streamlines REST API development with zero-configuration HTTP endpoints, automatic JSON serialization, and built-in monitoring via Actuator. By leveraging annotations like @RestController and @PostMapping, you create production-ready APIs that scale effortlessly. Remember: start small, use Spring Initializr for boilerplate-free setup, and always prioritize error handling and monitoring for robust enterprise applications. 🚀