REST API Development with Spring Boot

 

🌐 REST API Development with Spring Boot

Creating RESTful web services is one of the most common requirements in modern application development. Spring Boot, a project from the Spring ecosystem, makes it incredibly easy to develop REST APIs by minimizing the amount of configuration required.

In this blog post, we’ll dive into the essentials of building RESTful APIs using Spring Boot. We'll cover the architecture, annotations, data handling, error management, and security considerations.


🚀 Why Use Spring Boot for REST API Development?

Spring Boot offers several advantages when building REST APIs:

  • Minimal boilerplate code

  • Embedded server support (no need for external Tomcat deployment)

  • Seamless integration with databases

  • Production-ready features with Spring Boot Actuator

  • Auto-configuration and dependency management


🧱 Key Concepts of RESTful Architecture

Before we jump into code, here are key principles of REST:

  • Stateless: Each request contains all the information needed to process it.

  • Resource-based: URLs represent resources.

  • Use of HTTP methods:

    • GET – Retrieve data

    • POST – Create new resource

    • PUT – Update existing resource

    • DELETE – Remove resource


📦 Setting Up a Spring Boot Project

Use Spring Initializr to generate a base project with these dependencies:

  • Spring Web

  • Spring Boot DevTools

  • Spring Data JPA

  • H2 Database (for demo)


🏗 Project Structure

rest-api-app/
├── controller/
├── model/
├── repository/
├── service/
├── exception/
└── Application.java

🧑‍💻 Defining a Model Class

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // getters and setters
}

📂 Creating a Repository Interface

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

🧠 Writing the Service Layer

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new UserNotFoundException(id));
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

🌐 Creating the Controller

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

    @Autowired
    private UserService userService;

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

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

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

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.ok().build();
    }
}

⚠️ Exception Handling

Create a custom exception and a global exception handler:

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(Long id) {
        super("User not found with ID: " + id);
    }
}
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}

🔐 Adding Basic Security (Optional)

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

Add to application.properties:

spring.security.user.name=admin
spring.security.user.password=admin123

🧪 Testing the API

Use Postman or curl to test:

GET http://localhost:8080/api/users
POST http://localhost:8080/api/users

Payload:

{
  "name": "Alice",
  "email": "alice@example.com"
}

📊 Using Spring Boot Actuator

To monitor and manage your application:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Then visit:

http://localhost:8080/actuator/health

✅ Summary

Spring Boot makes REST API development fast, intuitive, and scalable. With features like embedded servers, auto-configuration, easy integration with databases, and support for modern tools like Actuator and Swagger, Spring Boot is a robust choice for building web services.


Previous
Next Post »