DEV Community

AdityaPratapBhuyan
AdityaPratapBhuyan

Posted on

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.

mkdir spring-boot-rest-gradle
cd spring-boot-rest-gradle
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Spring Boot Project

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

plugins {
    id 'org.springframework.boot' version '2.6.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '1.0-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}
Enter fullscreen mode Exit fullscreen mode

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:

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
public class HelloController {

    private final List<String> messages = new ArrayList<>();

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }

    @GetMapping("/messages")
    public List<String> getMessages() {
        return messages;
    }

    @PostMapping("/messages")
    public String addMessage(@RequestBody String message) {
        messages.add(message);
        return "Message added: " + message;
    }

    @PutMapping("/messages/{index}")
    public String updateMessage(@PathVariable int index, @RequestBody String updatedMessage) {
        if (index < messages.size()) {
            messages.set(index, updatedMessage);
            return "Message updated at index " + index + ": " + updatedMessage;
        } else {
            return "Invalid index";
        }
    }

    @DeleteMapping("/messages/{index}")
    public String deleteMessage(@PathVariable int index) {
        if (index < messages.size()) {
            String removedMessage = messages.remove(index);
            return "Message removed at index " + index + ": " + removedMessage;
        } else {
            return "Invalid index";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

./gradlew bootRun
Enter fullscreen mode Exit fullscreen mode

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:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @BeforeEach
    public void setUp() {
        // Clear messages before each test
        // This ensures a clean state for each test
        // Alternatively, you could use a test database or mock data
        // depending on your requirements
        HelloController messagesController = new HelloController();
        messagesController.getMessages().clear();
    }

    @Test
    public void testSayHello() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/hello"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Hello, Spring Boot!"));
    }

    @Test
    public void testGetMessages() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/api/messages"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(0)));
    }

    @Test
    public void testAddMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Test Message\""))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message added: Test Message"));
    }

    @Test
    public void testUpdateMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Initial Message\""));

        mockMvc.perform(MockMvcRequestBuilders.put("/api/messages/0")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Updated Message\""))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message updated at index 0: Updated Message"));
    }

    @Test
    public void testDeleteMessage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/api/messages")
                .contentType(MediaType.APPLICATION_JSON)
                .content("\"Message to Delete\""));

        mockMvc.perform(MockMvcRequestBuilders.delete("/api/messages/0"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Message removed at index 0: Message to Delete"));
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

./gradlew test
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)