BUILDING RESTFUL WEB SERVICES, Rest Controller, Request Mapping, Request Body, Path…
- User
BUILDING RESTFUL WEB SERVICES, Rest Controller, Request Mapping, Request Body, Path Variable, Request Parameter, GET, POST, PUT, DELETE APIs, Build Web Applications
- Assistant
Creating RESTful Web Services in Spring Boot involves using several annotations and concepts to build scalable, maintainable, and clean web applications. Below is a comprehensive guide on how to use the key components like
@RestController,@RequestMapping,@RequestBody,@PathVariable,@RequestParam, and HTTP methods (GET,POST,PUT,DELETE) to build REST APIs and full-fledged web applications.
🔧 Prerequisites
- Java 8 or later
- Spring Boot (2.x or 3.x)
- IDE (IntelliJ IDEA, Eclipse, etc.)
- Maven or Gradle for dependency management
🏗️ Step-by-Step Guide to Building RESTful Web Services
1. Create a Spring Boot Project
Use Spring Initializr with:
- Project: Maven
- Language: Java
- Spring Boot Version
- Dependencies:
- Spring Web
- Spring Data JPA (optional if working with databases)
2. Basic Concepts
✅
@RestControllerCombines
@Controllerand@ResponseBody. It tells Spring that every method returns data directly (not view names).@RestController public class MyController { // API endpoints here }✅
@RequestMappingMaps HTTP requests to handler methods. Can define at class or method level.
@RequestMapping("/api") public class MyController {}You can specify method types:
@RequestMapping(value = "/users", method = RequestMethod.GET)Or use shorthand annotations:
Shorthand Equivalent @GetMappingGET request @PostMappingPOST request @PutMappingPUT request @DeleteMappingDELETE request
3. Handling Requests
✅
@PathVariableUsed to extract values from the URI.
@GetMapping("/users/{id}") public String getUserById(@PathVariable Long id) { return "User ID: " + id; }Example URL:
/users/123
✅
@RequestParamUsed to extract query parameters from the URL.
@GetMapping("/search") public String searchUser(@RequestParam String name) { return "Searching for: " + name; }Example URL:
/search?name=John
✅
@RequestBodyUsed to bind the HTTP request body to a domain object.
@PostMapping("/users") public User createUser(@RequestBody User user) { return userService.save(user); }This expects JSON input like:
{ "name": "Alice", "email": "alice@example.com" }
4. CRUD Operations Example
Assume we have a
Usermodel:public class User { private Long id; private String name; private String email; // Getters and setters }Now implement CRUD operations:
@RestController @RequestMapping("/api/users") public class UserController { private List<User> users = new ArrayList<>(); // GET all users @GetMapping public List<User> getAllUsers() { return users; } // GET user by ID @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable Long id) { return users.stream() .filter(u -> u.getId().equals(id)) .findFirst() .map(ResponseEntity::ok) .orElseGet(() -> ResponseEntity.notFound().build()); } // POST create user @PostMapping public User createUser(@RequestBody User user) { users.add(user); return user; } // PUT update user @PutMapping("/{id}") public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) { return users.stream() .filter(u -> u.getId().equals(id)) .findFirst() .map(user -> { user.setName(updatedUser.getName()); user.setEmail(updatedUser.getEmail()); return ResponseEntity.ok(user); }) .orElseGet(() -> ResponseEntity.notFound().build()); } // DELETE user @DeleteMapping("/{id}") public ResponseEntity<Void> deleteUser(@PathVariable Long id) { boolean removed = users.removeIf(u -> u.getId().equals(id)); return removed ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build(); } }
5. Build a Simple Web Application (Optional View Layer)
To make it a web application, you can return HTML views instead of just JSON. Use
@Controllerinstead of@RestController.Example with Thymeleaf (HTML templates):
Add dependency in
pom.xml:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>Then:
@Controller public class WebController { @GetMapping("/") public String home(Model model) { model.addAttribute("message", "Welcome to Spring Web App!"); return "index"; // refers to index.html under resources/templates } }Create file:
src/main/resources/templates/index.html<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head><title>Welcome</title></head> <body> <h1 th:text="${message}"></h1> </body> </html>
🧪 Testing Your APIs
You can test your APIs using:
- Postman
- cURL
- Swagger UI (add
springdoc-openapi-uidependency)
📦 Summary
Annotation / Concept Purpose @RestControllerCombines @Controller&@ResponseBody@RequestMappingMaps incoming HTTP requests to controller methods @GetMapping,@PostMapping, etc.Shorthand for specific HTTP methods @PathVariableExtracts variables from URL path @RequestParamExtracts query parameters from URL @RequestBodyBinds HTTP request body to Java object ResponseEntityReturns HTTP response with status code and body
✅ Final Tips
- Keep controllers lightweight; put business logic in services.
- Use DTOs (Data Transfer Objects) instead of exposing entities directly.
- Add validation using
@Valid. - Secure your app with Spring Security when deploying.
- Use Swagger/OpenAPI for API documentation.
Would you like a downloadable sample project (e.g., GitHub repo template) or a ready-to-run Spring Boot example with these features?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.