Introduction
REST (Representational State Transfer) APIs are a set of standards for designing web services that enable communication between clients and servers. They operate on HTTP methods like GET, POST, PUT, and DELETE, aligning with CRUD operations for seamless data interaction. REST APIs use resource-based URLs and return data in formats like JSON or XML, making them lightweight and scalable
What Are REST APIs?
REST APIs adhere to REST principles: statelessness, uniform interface, and resource-based URLs. Common operations on these APIs correspond to HTTP methods, such as:
- GET: Fetching resources.
- POST: Creating resources.
- PUT: Updating resources.
- DELETE: Deleting resources
Overview of HTTP Methods :-
GET: Used to retrieve data from a server. It is safe and does not alter the server’s state. Example: Fetching a list of users.
POST: Used to create new resources on the server. It sends data in the request body. Example: Adding a new user.
PUT: Used to update or replace a resource on the server. It is idempotent, meaning repeated requests produce the same result. Example: Updating a user’s details.
DELETE: Used to delete a resource on the server. Example: Removing a specific user.
Step-by-Step Guide to Creating a REST API in Spring Boot:-
Project Setup
To begin, use Spring Initializr to create a Spring Boot project:
- Add the Spring Web dependency for RESTful web services.
- Import the generated project into your IDE
Define the Application Structure
A typical Spring Boot application for REST APIs follows this structure:
- Create an Entity Class
The entity represents the resource being managed. Example for a “User” resource:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.example.UserRestApi.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; private String email; public User(long id,String name,String email){ this.id=id; this.name=name; this.email=email; } public User(){ } //Setter Getter public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
- Create a Repository
The repository provides methods for interacting with the database.
1 2 3 4 5 6 7 8 9 |
package com.example.UserRestApi.repository; import com.example.UserRestApi.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User,Long> { } |
- Create a Service
The service layer contains the business logic. Here’s an example UserService for handling user-related operations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.example.UserRestApi.service; import com.example.UserRestApi.model.User; import com.example.UserRestApi.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; @GetMapping public List<User>getUsers(){ return userRepository.findAll(); } @GetMapping public Optional<User> getUserById(Long id){ return userRepository.findById(id); } @PostMapping public User saveUser(User user){ return userRepository.save(user); } @PutMapping public User updateUser(Long id,User updateUser){ Optional<User> existUser = userRepository.findById(id); if(existUser.isPresent()){ User user = existUser.get(); user.setId(updateUser.getId()); user.setName(updateUser.getName()); user.setEmail(updateUser.getEmail()); return userRepository.save(user); } return null; } @DeleteMapping public void deleteUser(Long id) { userRepository.deleteById(id); } } |
- Implement a REST Controller
Define endpoints and handle HTTP methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.example.UserRestApi.controller; import com.example.UserRestApi.model.User; import com.example.UserRestApi.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> getAllUsers() { return userService.getUsers(); } @GetMapping("/{id}") public Optional<User> getUserById(@PathVariable Long id) { return userService.getUserById(id); } @PostMapping public User createUser(@RequestBody User user) { return userService.saveUser(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) { return userService.updateUser(id,updatedUser); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } } |
- Test the API
Use tools like Postman, URL, or your browser to test the endpoints:
- GET all users: GET http://localhost:8080/api/users
- POST a new user:
- PUT to update a user: PUT http://localhost:8080/api/users/1
- DELETE a user: DELETE http://localhost:8080/api/users/1
Essential Topics for REST APIs in Spring Boot:- Data Validation
1 2 3 4 5 6 7 8 9 10 |
import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotNull; public class UserDTO { @NotNull private String name; @Email private String email; } |
Ensure incoming data is accurate and meets predefined rules using annotations like @NotNull and @Email. Validation helps maintain data integrity and avoid invalid inputs.
Error Handling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.example.UserRestApi.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { return new ResponseEntity<>("An error occurred: "+ ex.getMessage(),HttpStatus.NOT_FOUND); } } |
Manage errors gracefully by centralizing exception handling and providing meaningful error messages. Use proper HTTP status codes like 404 Not Found for missing resources or 400 Bad Request for invalid inputs
ResponseEntity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; // Get all users @GetMapping public ResponseEntity<List<User>> getAllUsers() { List<User> users = userService.getUsers(); if (users.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); // If no users, return 204 No Content } return new ResponseEntity<>(users, HttpStatus.OK); // Return 200 OK with user list } |
Customize API responses, including HTTP status codes, headers, and body content. It adds flexibility to control how data and messages are returned to clients.
Conclusion:-
Spring Boot, as a powerful framework, simplifies the development of REST APIs by offering features like easy setup, built-in dependency management, and support for validation, exception handling, and pagination. It allows developers to implement secure, efficient, and user-friendly APIs, catering to modern application needs while adhering to RESTful principles such as statelessness and a uniform interface.
bluethinkinc_blog
2025-04-04