Build a Spring Boot REST Application With Gradle

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.

What Is REST?

REST, Representational State Transfer, is a set of architectural principles ensuring your APIs are interoperable, scalable, and maintainable. Imagine building Lego blocks — different applications can seamlessly interact with your API as long as they follow the RESTful guidelines, just like Legos click together regardless of their set.

What Is Spring Boot?

Spring Boot is a powerful framework that simplifies the development process. Think of it as a pre-built toolkit stocked with components and features, saving you time and effort in setting up your application infrastructure. You can focus on crafting the core logic of your API without getting bogged down in boilerplate code.

Ready to unleash your inner API developer? This guide will empower you to create your first Spring Boot REST application using Gradle, a popular build tool. Whether you’re a seasoned Java programmer or just starting your exploration, this step-by-step journey will equip you with the essential knowledge to build dynamic and interactive web services.

Key Takeaways

  • Create RESTful APIs using Spring Boot: Spring Boot is a popular Java framework that simplifies the development process of RESTful APIs. It provides a wide range of features out of the box, such as automatic configuration and dependency injection, which can save you time and effort.
  • Understand the core concepts of RESTful APIs: REST stands for Representational State Transfer. It is a set of architectural principles that ensure that your APIs are interoperable, scalable, and maintainable. Some of the key concepts of RESTful APIs include resource representation, HTTP methods, and status codes.
  • Implement basic CRUD operations: CRUD stands for Create, Read, Update, and Delete. These are the basic operations that you will need to implement in your API endpoints in order to allow users to interact with your data.
  • Test your API thoroughly: It is important to test your API thoroughly before deploying it to production. This will help you to ensure that it is working as expected and that there are no bugs.
  • Explore advanced functionalities: As you become more familiar with Spring Boot and RESTful APIs, you can explore more advanced functionalities, such as data management, security, and authentication.

By combining the power of REST with the streamlined approach of Spring Boot, you’ll be able to create efficient and user-friendly APIs that can integrate seamlessly with other applications. So, are you ready to unlock the potential of RESTful APIs with Spring Boot and Gradle? Let’s begin!

Prerequisites

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

Step 1: Set Up the Project

To start with the project we need to initiate the below 3 steps.

  • Open a terminal or command prompt
  • Create a new directory for your project
  • Navigate to the project directory
  • Initiate a basic spring boot project structure

Shell

 

mkdir spring-boot-rest-gradle
cd spring-boot-rest-gradle
gradle init --type spring-boot

Step 2: Create a Spring Boot Project

Please edit the existing build.gradle file present in the directory with the below content.

Groovy

 

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()
}

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:

Java

 

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";
        }
    }
}

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:

Java

 

./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:

Java

 

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"));
    }
}

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:

Java

 

./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.

Additional Notes:

  • This is a very basic example. You can expand upon it by creating more endpoints, handling different HTTP methods (POST, PUT, DELETE), and adding functionality like data management.
  • Consider adding unit tests for your controller using frameworks like JUnit.
  • You can use the Spring Initializr (https://start.spring.io/) to quickly generate a project with additional dependencies and configurations.

For further learning, check out these resources:

Remember, this is just the beginning of your Spring Boot journey! Keep exploring and building amazing applications.

Source:
https://dzone.com/articles/build-your-first-spring-boot-rest-application-with