Building RESTful Web Services with Spring Boot: A Beginner-Friendly Guide

Learn how to create RESTful Web Services with Spring Boot using this beginner-friendly guide. Includes step-by-step examples, best practices, and top interview questions for your preparation.

Imagine you and your friends are playing a game where everyone can request a candy from you. You’re in charge of handing out candies. Here’s how it works:

  1. A friend asks, “Can I have one candy?”
  2. You give them a candy if you have one, or you say, “Sorry, no candy left.”

In this example:

  • You are the server (like a Spring Boot application).
  • Your friends are the clients (like a browser or app).
  • The candy requests are like HTTP requests.
  • The candy is the data being shared.

RESTful Web Services work the same way—they enable servers (like your Spring Boot app) to share “candies” (data) with clients via HTTP.


Step-by-Step Guide to Building RESTful Web Services in Spring Boot

1. What is REST?

REST (Representational State Transfer) is a set of principles for designing web services.
Key principles include:

  • Statelessness: Each request from a client contains all the information needed to process it.
  • Resources: Data is represented as resources identified by URIs (e.g., /api/users).
  • HTTP Methods: Use HTTP verbs (GET, POST, PUT, DELETE) to interact with resources.


2. Setting Up Spring Boot Project

Go to Spring Initializr and generate a project with the following dependencies:

  • Spring Web
  • Spring Boot DevTools
  • Lombok

Unzip and import the project into your favorite IDE.


3. Creating Your First RESTful Web Service

File: UserController.java

javaCopy codepackage com.example.demo.controller;

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

import java.util.Arrays;
import java.util.List;

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

    @GetMapping
    public List<String> getUsers() {
        return Arrays.asList("Alice", "Bob", "Charlie");
    }

    @PostMapping
    public String addUser(@RequestBody String name) {
        return "User " + name + " added successfully!";
    }

    @DeleteMapping("/{name}")
    public String deleteUser(@PathVariable String name) {
        return "User " + name + " deleted successfully!";
    }
}

4. Understanding the Code

  1. @RestController: Marks this class as a REST API controller.
  2. @RequestMapping("/api/users"): All endpoints in this controller will start with /api/users.
  3. @GetMapping: Handles HTTP GET requests to fetch user data.
  4. @PostMapping: Handles HTTP POST requests to add a new user.
  5. @DeleteMapping("/{name}"): Handles HTTP DELETE requests to remove a user by their name.

5. Testing the Endpoints

Use tools like Postman or cURL to test your RESTful API:

  1. GET /api/users:
    Returns a list of users: ["Alice", "Bob", "Charlie"].
  2. POST /api/users (Body: "David"):
    Response: "User David added successfully!".
  3. DELETE /api/users/David:
    Response: "User David deleted successfully!".

6. Best Practices for RESTful Web Services

  1. Use Proper HTTP Status Codes: Return appropriate status codes like 200 OK, 201 Created, 400 Bad Request, 404 Not Found, etc.
  2. Validate Input Data: Ensure the data received in requests is valid.
  3. Handle Exceptions Gracefully: Use @ControllerAdvice to handle exceptions globally.
  4. Enable CORS: To allow requests from different domains, configure CORS policies.

7. Common Spring Boot RESTful Web Service Interview Questions

  1. What is a RESTful Web Service?
    A RESTful Web Service is a service that adheres to REST principles and uses HTTP methods to expose data as resources.
  2. What is the difference between @Controller and @RestController?
    • @Controller is used for MVC-based web applications and returns views.
    • @RestController is used for RESTful APIs and returns data directly as JSON or XML.
  3. How do you handle exceptions in Spring Boot REST APIs?
    Use @ControllerAdvice along with custom exception handler methods annotated with @ExceptionHandler.
  4. What are the HTTP methods supported in REST?
    • GET: Retrieve data.
    • POST: Create data.
    • PUT: Update data.
    • DELETE: Remove data.
  5. How can you secure REST APIs in Spring Boot?
    • Use Spring Security for authentication and authorization.
    • Implement OAuth2 or JWT for token-based security.
  6. What is the purpose of @RequestBody and @PathVariable?
    • @RequestBody: Maps the request payload to a method parameter.
    • @PathVariable: Extracts values from the URI path.

Leave a Reply

Your email address will not be published. Required fields are marked *