Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /home/bibiizjb/ptutorials.com/en/account/functions/check_point_2.php on line 25
REST API Development (@RestController, @RequestMapping) Tutorial

Java REST API Development: @RestController and @RequestMapping Tutorial

REST (Representational State Transfer) APIs are a popular way to build web services that allow clients to interact with server resources over HTTP. In Java, the Spring Framework provides powerful annotations like @RestController and @RequestMapping to simplify REST API development. This tutorial will guide you through the basics of creating RESTful APIs using these annotations.

By the end of this tutorial, you'll understand how to create REST endpoints, handle HTTP methods, and build a fully functional REST API in Java.

What is a REST API?

A REST API is a set of endpoints that allow clients to perform CRUD (Create, Read, Update, Delete) operations on resources using HTTP methods like GET, POST, PUT, and DELETE.

  • Key Principles:
    • Stateless: Each request contains all the information needed to process it.
    • Resource-Based: Resources are identified by URLs (e.g., /users).
    • HTTP Methods: Use standard HTTP methods to perform operations (e.g., GET for reading, POST for creating).

Creating a REST API with @RestController

The @RestController annotation is a combination of @Controller and @ResponseBody. It simplifies the creation of RESTful web services by automatically serializing return values into JSON or XML.

  • Example: Simple REST Controller:
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
        @GetMapping("/hello")
        public String sayHello() {
            return "Hello, World!";
        }
    }
  • Key Annotations:
    • @RestController: Marks the class as a REST controller.
    • @GetMapping: Maps HTTP GET requests to the method.
    • @PostMapping: Maps HTTP POST requests to the method.
    • @PutMapping: Maps HTTP PUT requests to the method.
    • @DeleteMapping: Maps HTTP DELETE requests to the method.

Using @RequestMapping

The @RequestMapping annotation is used to map HTTP requests to handler methods in a controller. It can be applied at the class or method level.

  • Example: Class-Level @RequestMapping:
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class ApiController {
        @GetMapping("/hello")
        public String sayHello() {
            return "Hello, API!";
        }
    }
  • Example: Method-Level @RequestMapping:
    @RestController
    public class UserController {
        @RequestMapping(value = "/users", method = RequestMethod.GET)
        public List<User> getUsers() {
            // Return a list of users
        }
    }

Handling Path Variables and Query Parameters

REST APIs often use path variables and query parameters to pass data to the server.

  • Path Variables:
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
        // Fetch user by ID
        return userService.getUserById(id);
    }
  • Query Parameters:
    @GetMapping("/users")
    public List<User> getUsersByRole(@RequestParam String role) {
        // Fetch users by role
        return userService.getUsersByRole(role);
    }

Example: Full REST API

Here's an example of a complete REST API for managing users:

import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;

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

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

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.updateUser(id, user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}

This tutorial covered the basics of REST API development in Java using @RestController and @RequestMapping. Practice building RESTful APIs to create scalable and maintainable web services.

0 Interaction 0 Views 0 likes
Heart Button
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home