Tutorials Logic, IN info@tutorialslogic.com

Spring REST API @RestController, @RequestMapping, JSON: Tutorial, Examples, FAQs & Interview Tips

Spring REST API @RestController, @RequestMapping, JSON

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.

Building REST APIs with Spring

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.

Complete REST Controller

Complete REST Controller
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
    }
}

Exception Handling

@ControllerAdvice Global Exception Handler

@ControllerAdvice Global Exception Handler
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) {}
}

CORS Configuration

Global CORS Configuration

Global CORS Configuration
@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"})

Detailed Learning Notes for Spring REST API @RestController, @RequestMapping, JSON

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.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Spring REST API @RestController @RequestMapping JSON Java review example

Spring REST API @RestController @RequestMapping JSON Java review example
class SpringRESTAPIRestControllerRequestMappingJSONReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("Spring REST API @RestController @RequestMapping JSON: " + state);
    }
}

Spring REST API @RestController @RequestMapping JSON guard example

Spring REST API @RestController @RequestMapping JSON guard example
String value = null;
if (value == null) {
    System.out.println("Spring REST API @RestController @RequestMapping JSON: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of Spring REST API @RestController, @RequestMapping, JSON before memorizing syntax.
  • Run or trace one small Spring example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Spring REST API @RestController, @RequestMapping, JSON.
  • Write the rule in your own words after checking the example.
  • Connect Spring REST API @RestController, @RequestMapping, JSON to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Spring REST API @RestController @RequestMapping JSON without the situation where it is useful.
RIGHT Connect Spring REST API @RestController @RequestMapping JSON to a concrete Spring task.
Purpose makes syntax easier to recall.
WRONG Testing Spring REST API @RestController @RequestMapping JSON only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Spring REST API @RestController @RequestMapping JSON.
Evidence keeps debugging focused.
WRONG Memorizing Spring REST API @RestController @RequestMapping JSON without the situation where it is useful.
RIGHT Connect Spring REST API @RestController @RequestMapping JSON to a concrete Spring task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Spring REST API @RestController, @RequestMapping, JSON, then fix it and explain the fix.
  • Summarize when to use Spring REST API @RestController, @RequestMapping, JSON and when another approach is better.
  • Write a small example that uses Spring REST API @RestController @RequestMapping JSON in a realistic Spring scenario.
  • Change one important value in the Spring REST API @RestController @RequestMapping JSON example and predict the result first.

Frequently Asked Questions

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.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.