Thursday, 25 January 2024

Build Your First Spring Boot REST Application with Gradle

 

Creating Your First REST Application with Spring Boot and Gradle

Introduction

In this tutorial, we will create a simple RESTful web service using Spring Boot and Gradle. Spring Boot makes it easy to create stand-alone, production-grade Spring-based applications, and Gradle is a powerful build tool that simplifies the build process.

Prerequisites

  • Java Development Kit (JDK) installed
  • Gradle installed
  • Basic understanding of Java and Spring concepts

Step 1: Set Up the Project

Create a new directory for your project and navigate to it in the terminal or command prompt.

  1. mkdir spring-boot-rest-gradle
  2. cd spring-boot-rest-gradle

Step 2: Create a Spring Boot Project

Create a new file named build.gradle and add the following content:

  1. plugins {
  2. id 'org.springframework.boot' version '2.6.3'
  3. id 'io.spring.dependency-management' version '1.0.11.RELEASE'
  4. id 'java'
  5. }
  6. group = 'com.example'
  7. version = '1.0-SNAPSHOT'
  8. sourceCompatibility = '11'
  9. repositories {
  10. mavenCentral()
  11. }
  12. dependencies {
  13. implementation 'org.springframework.boot:spring-boot-starter-web'
  14. testImplementation 'org.springframework.boot:spring-boot-starter-test'
  15. }
  16. test {
  17. useJUnitPlatform()
  18. }

This sets up a basic Spring Boot project with the necessary dependencies.

Step 3: Create a REST Controller

Create a new file named HelloController.java in the src/main/java/com/example directory with the following content:

  1. import org.springframework.web.bind.annotation.*;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. @RestController
  5. @RequestMapping("/api")
  6. public class HelloController {
  7. private final List<String> messages = new ArrayList<>();
  8. @GetMapping("/hello")
  9. public String sayHello() {
  10. return "Hello, Spring Boot!";
  11. }
  12. @GetMapping("/messages")
  13. public List<String> getMessages() {
  14. return messages;
  15. }
  16. @PostMapping("/messages")
  17. public String addMessage(@RequestBody String message) {
  18. messages.add(message);
  19. return "Message added: " + message;
  20. }
  21. @PutMapping("/messages/{index}")
  22. public String updateMessage(@PathVariable int index, @RequestBody String updatedMessage) {
  23. if (index < messages.size()) {
  24. messages.set(index, updatedMessage);
  25. return "Message updated at index " + index + ": " + updatedMessage;
  26. } else {
  27. return "Invalid index";
  28. }
  29. }
  30. @DeleteMapping("/messages/{index}")
  31. public String deleteMessage(@PathVariable int index) {
  32. if (index < messages.size()) {
  33. String removedMessage = messages.remove(index);
  34. return "Message removed at index " + index + ": " + removedMessage;
  35. } else {
  36. return "Invalid index";
  37. }
  38. }
  39. }

This defines a REST controller with endpoints for GET, POST, PUT, and DELETE operations on a simple list of messages.

Step 4: Run the Application

Open a terminal or command prompt and run the following command:

  1. ./gradlew bootRun

Visit http://localhost:8080/api/hello in your browser to check the initial endpoint. You can use tools like curl, Postman, or any REST client to test the other endpoints.

Step 5: Write Test Cases

Create a new file named HelloControllerTest.java in the src/test/java/com/example directory with the following content:

  1. import org.junit.jupiter.api.Test;
  2. import org.junit.jupiter.api.BeforeEach;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.test.web.servlet.MockMvc;
  8. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  9. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  10. import static org.hamcrest.Matchers.hasSize;
  11. import static org.hamcrest.Matchers.is;
  12. @SpringBootTest
  13. @AutoConfigureMockMvc
  14. public class HelloControllerTest {
  15. @Autowired
  16. private MockMvc mockMvc;
  17. @BeforeEach
  18. public void setUp() {
  19. // Clear messages before each test
  20. // This ensures a clean state for each test
  21. // Alternatively, you could use a test database or mock data
  22. // depending on your requirements
  23. HelloController messagesController = new HelloController();
  24. messagesController.getMessages().clear();
  25. }
  26. @Test
  27. public void testSayHello() throws Exception {
  28. mockMvc.perform(MockMvcRequestBuilders.get("/api/hello"))
  29. .andExpect(MockMvcResultMatchers.status().isOk())
  30. .andExpect(MockMvcResultMatchers.content().string("Hello, Spring Boot!"));
  31. }
  32. @Test
  33. public void testGetMessages() throws Exception {
  34. mockMvc.perform(MockMvcRequestBuilders.get("/api/messages"))
  35. .andExpect(MockMvcResultMatchers.status().isOk())
  36. .andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(0)));
  37. }
  38. @Test
  39. public void testAddMessage() throws Exception {
  40. mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
  41. .contentType(MediaType.APPLICATION_JSON)
  42. .content("\"Test Message\""))
  43. .andExpect(MockMvcResultMatchers.status().isOk())
  44. .andExpect(MockMvcResultMatchers.content().string("Message added: Test Message"));
  45. }
  46. @Test
  47. public void testUpdateMessage() throws Exception {
  48. mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
  49. .contentType(MediaType.APPLICATION_JSON)
  50. .content("\"Initial Message\""));
  51. mockMvc.perform(MockMvcRequestBuilders.put("/api/messages/0")
  52. .contentType(MediaType.APPLICATION_JSON)
  53. .content("\"Updated Message\""))
  54. .andExpect(MockMvcResultMatchers.status().isOk())
  55. .andExpect(MockMvcResultMatchers.content().string("Message updated at index 0: Updated Message"));
  56. }
  57. @Test
  58. public void testDeleteMessage() throws Exception {
  59. mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
  60. .contentType(MediaType.APPLICATION_JSON)
  61. .content("\"Message to Delete\""));
  62. mockMvc.perform(MockMvcRequestBuilders.delete("/api/messages/0"))
  63. .andExpect(MockMvcResultMatchers.status().isOk())
  64. .andExpect(MockMvcResultMatchers.content().string("Message removed at index 0: Message to Delete"));
  65. }
  66. }

These test cases use Spring Boot’s testing features to simulate HTTP requests and verify the behavior of the REST controller.

Step 6: Run Tests

Open a terminal or command prompt and run the following command to execute the tests:

  1. ./gradlew test

Review the test results to ensure that all tests pass successfully.

Conclusion

Congratulations! You have successfully created a basic RESTful web service with CRUD operations using Spring Boot and Gradle. This tutorial covered the implementation of endpoints for GET, POST, PUT, and DELETE operations along with corresponding test cases.

No comments:

Post a Comment

Exploring Amazon Web Services (AWS)

  Compute Services Database Services Storage Services Networking Services Analytics Services Security, Identity, and Compliance Services Ama...