DEV Community

Jotty John
Jotty John

Posted on

Building a RESTful API with Spring Boot: A Comprehensive Guide to @RequestMapping

@RequestMapping is a versatile annotation in Spring that can be used to map HTTP requests to handler methods of MVC and REST controllers. Here’s an example demonstrating how to use @RequestMapping with different HTTP methods in a Spring Boot application.

Step-by-Step Example
Set up the Spring Boot project as mentioned in my previous post, with Spring Web dependency.

Create a new package for your controller, e.g., com.demo.controller.

Create a new Java class inside this package, e.g., UserController.java.

package com.demo.controller;

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

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

    // GET method to retrieve user details
    @RequestMapping(method = RequestMethod.GET, value = "/{userId}")
    public String getUser(@PathVariable String userId) {
        return "User details for user " + userId;
    }

    // POST method to create a new user
    @RequestMapping(method = RequestMethod.POST)
    public String createUser(@RequestBody String user) {
        return "User created: " + user;
    }

    // PUT method to update user details
    @RequestMapping(method = RequestMethod.PUT, value = "/{userId}")
    public String updateUser(@PathVariable String userId, @RequestBody String user) {
        return "User updated for user " + userId + ": " + user;
    }

    // DELETE method to delete a user
    @RequestMapping(method = RequestMethod.DELETE, value = "/{userId}")
    public String deleteUser(@PathVariable String userId) {
        return "User deleted with userId " + userId;
    }
}
Enter fullscreen mode Exit fullscreen mode

@RestController: This annotation is used to mark the class as a RESTful controller.
@RequestMapping("/api/users"): This annotation is used at the class level to map all requests that start with /api/users to this controller.

@RequestMapping(method = RequestMethod.GET, value = "/{userId}"): This maps GET requests to /api/users/{userId} to the getUser method. The @PathVariable annotation is used to extract the userId from the URL.

@RequestMapping(method = RequestMethod.POST): This maps POST requests to /api/users to the createUser method. The @RequestBody annotation is used to bind the HTTP request body to a transfer object.

@RequestMapping(method = RequestMethod.PUT, value = "/{userId}"): This maps PUT requests to /api/users/{userId} to the updateUser method. The @PathVariable and @RequestBody annotations are used similarly as before.

@RequestMapping(method = RequestMethod.DELETE, value = "/{userId}"): This maps DELETE requests to /api/users/{userId} to the deleteUser method.

Top comments (0)