Spring REST API @RestController, @RequestMapping, JSON is an important Spring topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Spring REST API @RestController, @RequestMapping, JSON solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Spring REST API @RestController, @RequestMapping, JSON should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Spring REST API @RestController @RequestMapping JSON should be studied as a practical Spring lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the spring > rest-api page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
Spring makes it easy to build RESTful web services. The key annotations are @RestController (combines @Controller and @ResponseBody), @RequestBody for reading JSON input, and ResponseEntity for full control over the HTTP response.
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.data.domain.*;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
@RestController
@RequestMapping("/api/v1/users")
@CrossOrigin(origins = "http://localhost:3000") // Allow CORS from React app
public class UserRestController {
private final UserService userService;
public UserRestController(UserService userService) {
this.userService = userService;
}
// GET /api/v1/users?page=0&size=10&sort=username
@GetMapping
public ResponseEntity<Page<User>> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String sort) {
Page<User> users = userService.getUsers(page, size, sort);
return ResponseEntity.ok(users);
}
// GET /api/v1/users/42
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
}
// POST /api/v1/users
@PostMapping
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User created = userService.createUser(user);
URI location = URI.create("/api/v1/users/" + created.getId());
return ResponseEntity.created(location).body(created); // 201 Created
}
// PUT /api/v1/users/42
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id,
@Valid @RequestBody User user) {
User updated = userService.updateUser(id, user);
return ResponseEntity.ok(updated);
}
// DELETE /api/v1/users/42
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build(); // 204 No Content
}
}
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import java.util.*;
@RestControllerAdvice // Handles exceptions for all @RestController classes
public class GlobalExceptionHandler {
// Handle resource not found
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse(404, ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}
// Handle validation errors
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidation(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach(error -> {
String field = ((FieldError) error).getField();
String message = error.getDefaultMessage();
errors.put(field, message);
});
return ResponseEntity.badRequest().body(errors);
}
// Handle all other exceptions
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
ErrorResponse error = new ErrorResponse(500, "Internal server error");
return ResponseEntity.internalServerError().body(error);
}
record ErrorResponse(int status, String message) {}
}
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000", "https://myapp.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600); // Cache preflight for 1 hour
}
}
// Or use @CrossOrigin on individual controllers/methods:
// @CrossOrigin(origins = "*", maxAge = 3600)
// @CrossOrigin(origins = {"http://localhost:3000", "https://myapp.com"})
When studying Spring REST API @RestController, @RequestMapping, JSON, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Spring, Spring REST API @RestController, @RequestMapping, JSON becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
class SpringRESTAPIRestControllerRequestMappingJSONReview {
public static void main(String[] args) {
String state = "ready";
System.out.println("Spring REST API @RestController @RequestMapping JSON: " + state);
}
}
String value = null;
if (value == null) {
System.out.println("Spring REST API @RestController @RequestMapping JSON: handle the missing value before continuing");
}
Memorizing Spring REST API @RestController @RequestMapping JSON without the situation where it is useful.
Connect Spring REST API @RestController @RequestMapping JSON to a concrete Spring task.
Testing Spring REST API @RestController @RequestMapping JSON only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Spring REST API @RestController @RequestMapping JSON.
Memorizing Spring REST API @RestController @RequestMapping JSON without the situation where it is useful.
Connect Spring REST API @RestController @RequestMapping JSON to a concrete Spring task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Spring, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.