00:00

Spring Boot REST API

A Spring Boot REST API is used to build backend services that expose data and functionality over HTTP using REST (Representational State Transfer) principles. These APIs are commonly consumed by web applications, mobile apps, or other microservices. Spring Boot simplifies REST API development by providing auto-configuration, embedded servers, and production-ready features.


What is REST?

REST is an architectural style for designing networked applications. It uses standard HTTP methods and works with resources represented as JSON or XML.

Key REST Principles

  • Client-Server: Client and server are independent.
  • Stateless: Each request contains all necessary information.
  • Resource-Based: Everything is treated as a resource.
  • Uniform Interface: Uses standard HTTP methods.

Common HTTP Methods

  • GET – Retrieve data
  • POST – Create new data
  • PUT – Update existing data
  • DELETE – Remove data
  • PATCH – Partial update

Why Use Spring Boot for REST APIs?

  • Minimal configuration and faster development
  • Embedded Tomcat/Jetty (no external server needed)
  • Auto-configuration of Spring MVC
  • Easy JSON handling with Jackson
  • Production-ready features (Actuator, Security, Monitoring)

Spring Boot REST API Architecture

A typical Spring Boot REST API follows a layered architecture:

  • Controller Layer – Handles HTTP requests and responses
  • Service Layer – Contains business logic
  • Repository Layer – Interacts with the database
  • Model/Entity – Represents database tables or DTOs

Core Annotations Used in Spring Boot REST API

@RestController

Combines @Controller and @ResponseBody. It tells Spring that this class handles REST requests and returns data directly (usually JSON).

@RequestMapping

Maps HTTP requests to handler methods or controller classes.

@GetMapping

Used to handle HTTP GET requests.

@PostMapping

Used to handle HTTP POST requests.

@PutMapping

Used to handle HTTP PUT requests.

@DeleteMapping

Used to handle HTTP DELETE requests.

@PathVariable

Used to extract values from the URI path.

@RequestParam

Used to read query parameters from the URL.

@RequestBody

Converts incoming JSON request body into a Java object.


Simple REST API Example

Controller Layer

    @RestController
    @RequestMapping("/api/users")
    public class UserController {
    
        @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.saveUser(user);
        }
    }
    

Service Layer

The service layer contains business logic and acts as a bridge between controller and repository.

    @Service
    public class UserService {
    
        public List<User> getAllUsers() {
            // business logic
        }
    
        public User getUserById(Long id) {
            // business logic
        }
    
        public User saveUser(User user) {
            // business logic
        }
    }
    

Repository Layer

Spring Data JPA simplifies database access using repositories.

    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
    }
    

Data Format (JSON)

Spring Boot uses Jackson to automatically convert Java objects to JSON.

    {
      "id": 1,
      "name": "Sandeep",
      "email": "sandeep@example.com"
    }
    

Exception Handling in REST API

Spring Boot provides centralized exception handling using @ControllerAdvice.

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(ResourceNotFoundException.class)
        public ResponseEntity<String> handleException(Exception ex) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
        }
    }
    

HTTP Status Codes

  • 200 OK – Request successful
  • 201 Created – Resource created
  • 400 Bad Request – Invalid request
  • 404 Not Found – Resource not found
  • 500 Internal Server Error – Server error

Validation in Spring Boot REST API

Bean Validation ensures correct input data.

    @NotNull
    @Size(min = 3, max = 20)
    private String username;
    

Security in REST API

  • Spring Security for authentication and authorization
  • JWT for stateless authentication
  • OAuth2 for third-party login

Best Practices

  • Use meaningful URLs and HTTP methods
  • Return proper HTTP status codes
  • Keep controllers thin and services rich
  • Handle exceptions globally
  • Use DTOs instead of entities in APIs

Conclusion

Spring Boot REST API development is simple, fast, and highly scalable. With minimal configuration, powerful annotations, and strong ecosystem support, Spring Boot is an excellent choice for building modern RESTful web services and microservices.