Building REST APIs with Spring Boot
1. What is a REST API?
REST (Representational State Transfer) is an architectural style for designing networked
applications. RESTful APIs use HTTP methods to perform CRUD operations on resources
identified by URLs.
HTTP Method Operation Example URL
GET Read resource /api/users
POST Create resource /api/users
PUT Update resource /api/users/1
DELETE Delete resource /api/users/1
PATCH Partial update /api/users/1
2. Spring MVC Annotations
Annotation Purpose
@RestController Marks class as REST controller
@RequestMapping Maps URL patterns to class/method
@GetMapping Handles HTTP GET requests
@PostMapping Handles HTTP POST requests
@PutMapping Handles HTTP PUT requests
@DeleteMapping Handles HTTP DELETE requests
@PathVariable Extracts value from URL path
@RequestBody Binds HTTP request body to object
@RequestParam Extracts query parameters
3. Sample REST Controller
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List getAllUsers() {
return [Link]();
}
@GetMapping("/{id}")
public ResponseEntity getUserById(@PathVariable Long id) {
User user = [Link](id);
return [Link](user);
}
@PostMapping
public ResponseEntity createUser(@RequestBody User user) {
User saved = [Link](user);
return [Link](201).body(saved);
}
@DeleteMapping("/{id}")
public ResponseEntity deleteUser(@PathVariable Long id) {
[Link](id);
return [Link]().build();
}
}
4. Response Status Codes
Code Meaning When to Use
200 OK Success GET, PUT success
201 Created Resource created POST success
204 No Content Success, no body DELETE success
400 Bad Request Invalid input Validation failure
404 Not Found Resource missing ID not found
500 Internal Error Server failure Unhandled exception
5. [Link] Configuration
[Link]=8080
[Link]=my-rest-api
[Link]=jdbc:mysql://localhost:3306/mydb
[Link]=root
[Link]=secret
[Link]-auto=update