Skip to main content

Command Palette

Search for a command to run...

Building Your First REST API with Spring Boot

Kickstart your journey into Java backend development

Updated
7 min read
H

"Tech Enthusiast by Day, Powerlifter and Fitness Coach by Night—Bridging the Gap Between Code and Strength."

Passionate about pushing boundaries in both technology and fitness, I combine my love for coding with the discipline of powerlifting. Join me as I explore the intersections of tech innovation and physical prowess.

🚀 Welcome to Day 1 of our "30 Days of Java Backend Development".

Today, we’ll start with the basics by building a simple "Hello World" REST API using Spring Boot. This project will set the foundation for more complex applications we’ll be developing throughout this series. By the end of this tutorial, we'll have a fully functional REST API that returns a greeting message "Hello World".

🎯 What You’ll Learn

  • Setting up a Java development environment

  • Creating a Spring Boot project

  • Building a REST API endpoint

  • Running the Spring Boot application

  • Writing unit tests for your API

  • Pushing your code to GitHub

Prerequisites

Before we start, make sure you have the following installed on your machine:

  • Java Development Kit (JDK 17)

  • Maven

  • Visual Studio Code (VS Code) with the extensions mentioned in the image

Step 1: Setting Up the Development Environment

1.1 Install Java Development Kit (JDK)

  • Download JDK 17 from the official Oracle JDK website .

  • Install JDK: Follow the installation instructions specific to your operating system.

  • Verify Installation: Open your terminal or command prompt and run:

java -version  #you should see installed java version

1.2 Install Maven

  • Download Maven from the official Apache Maven website.

  • Set Up Maven: Follow the instructions to configure Maven on your system.

  • Verify Installation: Run the following command to check if Maven is installed correctly

mvn -version

Step 2: Create a New Spring Boot Project

2.1 Using Spring Initializr

  • Go to Spring Initializr: start.spring.io

  • Configure the Project with the configuration shown in the image:

  • Generate the Project: Click "Generate" to download the project as a ZIP file.

2.2 Import the Project into Visual Studio Code

  • Unzip the Project: Extract the downloaded ZIP file.

  • Open Visual Studio Code: Open the extracted project folder in VS Code.

  • Wait for Maven to Import Dependencies: VS Code will automatically detect the pom.xml file and import the necessary dependencies.

Step 3: Creating the REST API

3.1 Create a Controller Class

    package com.techsights.helloworld;

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;


    /**
     * Controller class for handling hello world requests.
     */
    /*
     * The @RestController annotation is a convenience annotation that combines @Controller and @ResponseBody.
       This annotation marks the class as a Spring MVC controller where each method returns a domain object
       instead of a view. The object data is directly written to the HTTP response as JSON or XML.
     */
    @RestController
    /* The @RequestMapping annotation is used to map web requests to specific handler classes and methods.
       Here, it maps requests that start with "/api" to methods in this controller. */
    @RequestMapping("/api")
    public class HelloWorldController {
        /* The @GetMapping annotation is a specialized version of @RequestMapping that is used to handle GET requests.
           It maps HTTP GET requests to the method sayHello().
        */
        @GetMapping("hello")
        public String sayHello() {
            /*
             * This method returns a plain text response "Hello, World!".
             * In a RESTful web service, this response is automatically serialized into the HTTP response body.
             */
            return "Hello, World";
        }

        /*
         * The @GetMapping annotation here maps HTTP GET requests to the method sayHelloTo() with a path variable.
         * The URL pattern "/hello/{name}" indicates that the URL will contain a variable part (in this case, 'name').
         */
        @GetMapping("hello/{name}")
        public String sayHelloTo(@PathVariable String name) {
            /*
             * The @PathVariable annotation binds the 'name' variable from the URL to the method parameter 'name'.
             * This allows you to capture dynamic values from the URL and use them in your method.
             * The method returns a personalized greeting using the captured 'name'.
             */
            return "Hello, " + name;
        }

    }
  • Navigate to the src/main/java/com/techsights/helloworld directory.

  • Create a New Java Class:

    • Name: HelloWorldController

    • Location: com.techsights.helloworld

  • Add the following code to HelloWorldController.java:

    • Comments in the code explain the use of various annotations and fields used.

Step 4: Running the Application

4.1 Run the Application

  • Run the Main Application: Locate HelloWorldApplication.java in the com.techsights.helloworld package.

  • Run the Application: Open the Command Palette (Ctrl + Shift + P), type Spring Boot Dashboard, and run the application from there.

  • View Console Output: You should see Spring Boot starting up and the embedded Tomcat server running.

    4.2 Test the REST API

Open a Web Browser or Postman:

  • URL: http://localhost:8080/api/hello

  • Response: You should see the text "Hello, World!" displayed.

  • URL: http://localhost:8080/api/hello/hansric

  • Response: You should see the text "Hello, Hansric!" displayed.

Step 5: Adding Unit Tests

5.1 Create a Unit Test Class

  • Navigate to the src/main/java/com/techsights/helloworld directory.

  • Open src/main/java/com/techsights/helloworld/HelloWorldController.java and right click and Go to Tests. In the command palette select Generate Tests.

  • Add below code in HelloWorldControllerTest.java, refer to comments in the code for explanations of annotations and concepts.

package com.techsights.helloworld;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(HelloWorldController.class)
public class HelloWorldControllerTests {

    @Autowired
    private MockMvc mockMvc;

// The @Test annotation marks this method as a test case that should be run by the JUnit testing framework.
    // This method tests the sayHello() method in the HelloWorldController to ensure it returns "Hello, World!".
    @Test
    public void sayHello_ShouldReturnHelloWorld() throws Exception {
        // The mockMvc.perform() method is used to simulate an HTTP GET request to the /api/hello endpoint.
        // The get() method is a static import from MockMvcRequestBuilders and represents the HTTP GET request.
        mockMvc.perform(get("/api/hello"))
                // The andExpect() method is used to define expectations for the response.
                // Here, we expect the HTTP status to be 200 OK.
                .andExpect(status().isOk()) // Verifies that the response status is 200 OK
                // We also expect the response body to contain the string "Hello, World!".
                .andExpect(content().string("Hello, World")); // Verifies that the response body is "Hello, World!"
    }

    // This test method verifies the sayHelloTo() method in the HelloWorldController.
    // It checks that the method returns a personalized greeting based on the name provided in the URL.
    @Test
    public void sayHelloTo_ShouldReturnPersonalizedGreeting() throws Exception {
        String name = "John"; // This is the name we will pass as a path variable in the request

        // mockMvc.perform() is used again to simulate an HTTP GET request, this time to the /api/hello/{name} endpoint.
        // The {name} part of the URL is replaced with the value of the 'name' variable ("John").
        mockMvc.perform(get("/api/hello/" + name))
                // We expect the HTTP status to be 200 OK.
                .andExpect(status().isOk()) // Verifies that the response status is 200 OK
                // We expect the response body to contain the personalized greeting "Hello, John".
                .andExpect(content().string("Hello, " + name)); // Verifies that the response body is "Hello, John"
    }
}

5.2 Understanding the Test Code

  • @WebMvcTest(HelloWorldController.class): Focuses only on the web layer, testing the HelloWorldController class.

  • MockMvc: Simulates HTTP requests and responses for testing purposes.

  • Test Method sayHello_ShouldReturnHelloWorld: Sends a GET request to /api/hello and verifies that the response status is OK (200) and the content is "Hello, World"

Test Method sayHelloTo_ShouldReturnPersonalizedGreeting: Sends a GET request to /api/hello/{name} and verifies that the response status is OK (200) and the content is "Hello, John!"

5.3 Running the Test

  • Run the Test: Right-click on HelloWorldControllerTest and select "Run HelloWorldControllerTest."

  • View Test Results: Ensure that the test passes successfully.

Step 6: Committing and Pushing Code to GitHub

6.1 Create a GitHub Repository

  • Go to GitHub: github.com

  • Create a New Repository:

  • Repository Name: hello-world-spring-boot

  • Description: A simple Hello World REST API with Spring Boot.

  • Visibility: Public or Private, depending on your preference.

  • Initialize with a README: Check this option.

6.2 Commit and Push Code

Open Terminal in Visual Studio Code:

  • Navigate to the project root.

  • Initialize Git: java git init

  • Add Remote Repository:

      git remote add origin https://github.com/your-username/hello-world-spring-boot.git
    
  • Add and Commit Changes:

       git add . 
       git commit -m "Initial commit - Hello World REST API"
    

* Push to GitHub:

git push -u origin main

The code developed in this tutorial is available in https://github.com/hsharma1528/spring-boot-hello-world.git

Conclusion

Congratulations! You’ve built your first REST API using Spring Boot, added unit tests, and pushed your code to GitHub. This is just the beginning of your journey to mastering backend development with Java. In the next tutorial, we’ll dive deeper into CRUD operations with an in-memory database.

30 Days of Java Backend Development

Part 1 of 2

Join us on a 30-day journey to master Java backend development, from basic REST APIs to advanced concepts like microservices and reactive programming. Build a solid foundation in Java technologies

Up next

Creating a Simple CRUD API with an In-Memory Database Using Spring Boot

A Step-by-Step Guide to Setting Up Project with Spring Initializr and Creating a CRUD API Using Spring Boot and H2 Database in Visual Studio Code