@RestController and @RequestMapping in Spring Boot

Spring Boot makes it easy to build RESTful APIs using powerful annotations. Two of the most fundamental annotations you’ll encounter when building web services are @RestController and @RequestMapping in Spring Boot.

In this post, we’ll cover:

  • ✅ What is @RestController?
  • ✅ What is @RequestMapping?
  • ✅ How they work together
  • ✅ HTTP method-specific alternatives
  • ✅ Code examples and common use cases
  • ✅ Best practices

Let’s break it all down with examples.

@RestController and @RequestMapping in Spring Boot

✅ What is @RestController?

The @RestController annotation is used to mark a class as a controller where every method returns a domain object instead of a view. It is a shortcut for:



@Controller
@ResponseBody

Purpose:

  • Makes the class ready for use by Spring MVC to handle web requests.
  • Eliminates the need to annotate each method with @ResponseBody.

🔸 When to use:

Use @RestController when you are building a RESTful API where the responses are JSON or XML rather than HTML pages.

🧪 Example:


@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello from REST Controller!";
    }
}

In the above example:

  • The class is annotated with @RestController
  • The method returns plain text (or JSON), not a view name
  • You can hit http://localhost:8080/hello to get the response

✅ What is @RequestMapping?

@RequestMapping is used to map HTTP requests to handler methods (or classes) in controller classes.

It can be placed:

  • On a class to define the base URL
  • On a method to define the path and HTTP method(s)

🔸 Basic Usage



@RestController
@RequestMapping("/api")
public class ApiController {

    @RequestMapping("/status")
    public String status() {
        return "API is up and running!";
    }
}

In the above example:

  • The base path is /api
  • The full path is /api/status

🔸 Mapping with Method Types

You can use @RequestMapping with HTTP method attributes:



@RequestMapping(value = "/users", method = RequestMethod.GET)
public List getUsers() {
    return userService.getAllUsers();
}

This is equivalent to:



@GetMapping("/users")

✅ HTTP Method Shortcuts

Spring provides specific annotations as a shortcut for @RequestMapping with method:

AnnotationEquivalent to
@GetMapping@RequestMapping(method = RequestMethod.GET)
@PostMapping@RequestMapping(method = RequestMethod.POST)
@PutMapping@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping@RequestMapping(method = RequestMethod.DELETE)

These are more readable and preferred for clarity.

🧑‍💻 Real-World Example

🔹 UserController.java



package com.kscodes.springboot.demo.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

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

    private Map users = new HashMap<>();

    @GetMapping
    public Map getAllUsers() {
        return users;
    }

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return users.getOrDefault(id, "User not found");
    }

    @PostMapping
    public String createUser(@RequestBody String name) {
        long id = users.size() + 1;
        users.put(id, name);
        return "User created with ID: " + id;
    }

    @PutMapping("/{id}")
    public String updateUser(@PathVariable Long id, @RequestBody String name) {
        if (users.containsKey(id)) {
            users.put(id, name);
            return "User updated";
        } else {
            return "User not found";
        }
    }

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        if (users.remove(id) != null) {
            return "User deleted";
        } else {
            return "User not found";
        }
    }
}

⚠️ Common Pitfalls

MistakeSolution
Forgetting @RestControllerYou’ll get a 404 or see view resolution errors
Using @Controller without @ResponseBodyYour JSON won’t render correctly
Missing method type in @RequestMappingIt will match any HTTP method by default (use with care)
Not using HTTP-specific mappingsPrefer @GetMapping, @PostMapping for clarity

✅ Best Practices

  • 🟢 Use @RestController for REST APIs
  • 🟢 Prefer @GetMapping, @PostMapping, etc. over raw @RequestMapping
  • 🟢 Keep your controller slim—delegate logic to services
  • 🟢 Handle exceptions globally using @ControllerAdvice

📌 Summary

AnnotationPurpose
@RestControllerMakes a class REST-friendly with JSON/XML response
@RequestMappingMaps a URL (and optionally a method) to a controller
@GetMapping, etc.Preferred alternatives for cleaner code

🔗 External References