Spring Boot REST API with CRUD operations

David Kumar Jan 2026
3 tabs
package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        return ResponseEntity.ok(userService.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
        User created = userService.save(user);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(
        @PathVariable Long id,
        @Valid @RequestBody User user
    ) {
        return userService.findById(id)
            .map(existing -> {
                user.setId(id);
                User updated = userService.save(user);
                return ResponseEntity.ok(updated);
            })
            .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        if (userService.existsById(id)) {
            userService.deleteById(id);
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/search")
    public ResponseEntity<List<User>> searchUsers(@RequestParam String query) {
        return ResponseEntity.ok(userService.search(query));
    }
}
3 files · java Explain with highlit

Spring Boot simplifies building production-ready REST APIs with minimal configuration. I use @RestController to create RESTful endpoints and @RequestMapping to define routes. The @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping annotations handle HTTP methods. @PathVariable extracts URL parameters, while @RequestBody deserializes JSON to Java objects. @Valid enables bean validation. Spring's dependency injection with @Autowired or constructor injection manages dependencies. Exception handling uses @ControllerAdvice and @ExceptionHandler for consistent error responses. ResponseEntity controls HTTP status codes and headers. Spring Boot's auto-configuration eliminates boilerplate, letting me focus on business logic. The embedded Tomcat server runs apps standalone without external deployment.