Building Your First Spring RESTful API: A “Hello World” Guide

Let’s dive into the exciting world of Spring Boot and RESTful APIs. If you’re looking to build robust, scalable web services, Spring Boot is an excellent choice and understanding how to create a simple REST API is a fundamental first step.

In this tutorial, we’ll walk through creating a “Hello World” RESTful service that exposes JSON data. This example will cover the basic setup of a Spring Boot project and demonstrating how to handle HTTP GET requests.

Prerequisites

Before we begin, make sure you have the following installed:

  • Java Development Kit (JDK) 8 or higher: You can download it from the Oracle website.
  • Apache Maven: For project management and dependency handling. Download from the Maven website.
  • An Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or VS Code with Java extensions are all great choices.

Step 1: Create a Spring Boot Project

The easiest way to start a Spring Boot project is by using the Spring Initializr. Go to the website and configure your project as follows:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Choose the latest stable version (e.g., 2.7.x or 3.x.x)
  • Group: com.ankurm.restapi
  • Artifact: hello-world
  • Name: hello-world
  • Package name: com.ankurm.restapi.helloworld
  • Packaging: Jar
  • Java: 17 (or your preferred version)
  • Dependencies: Add Spring Web

Click “Generate” to download the project as a ZIP file. Extract it to your desired location.

Step 2: Project Structure Overview

After extracting, your project structure will look something like this (simplified):

hello-world/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── ankurm/
        │           └── restapi/
        │               └── helloworld/
        │                   └── HelloWorldApplication.java
        └── resources/
            ├── application.properties
            └── static/
            └── templates/

The HelloWorldApplication.java file is your main Spring Boot application entry point.

Step 3: Define Your REST Controller

Now, let’s create our first REST controller. This controller will handle incoming HTTP requests and return JSON responses.

Create a new package named com.ankurm.restapi.helloworld.controller and inside it, create a new Java class called HelloWorldController.java.

package com.ankurm.restapi.helloworld.controller;

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

@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public String helloWorld() {
        return "Hello from ankurm.com REST API!";
    }
}

Let’s break down what’s happening here:

  • @RestController: This is a convenience annotation that combines @Controller and @ResponseBody. It tells Spring that this class is a REST controller and that the return value of its methods should be directly bound to the web response body.
  • @GetMapping("/hello"): This annotation maps HTTP GET requests to the /hello endpoint to the helloWorld() method.
  • public String helloWorld(): This method simply returns a String. Spring, thanks to @RestController, automatically serializes this String into the HTTP response body as plain text (or JSON if an appropriate HTTP header is sent).

Step 4: Create a DTO (Data Transfer Object) for JSON Response

While returning a simple string is fine, in most real-world REST APIs, you’ll be returning more structured data, usually in JSON format. Let’s create a simple Java class to represent our “Hello World” message.

Create a new package named com.ankurm.restapi.helloworld.model and inside it, create a new Java class called Greeting.java.

package com.ankurm.restapi.helloworld.model;

public class Greeting {

    private String message;
    private String author;

    public Greeting(String message, String author) {
        this.message = message;
        this.author = author;
    }

    // Getters and Setters
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

Now, let’s modify our HelloWorldController to return an instance of this Greeting class.

package com.ankurm.restapi.helloworld.controller;

import com.ankurm.restapi.helloworld.model.Greeting;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @GetMapping("/hello-json")
    public Greeting helloWorldJson() {
        return new Greeting("Hello from ankurm.com REST API!", "Ankur M.");
    }
}

When you return an object from a @RestController method, Spring Boot (with Jackson, which is included by default for web projects) automatically converts that object into JSON and sends it in the response body. Magic!

Step 5: Run Your Spring Boot Application

You can run your application in several ways:

From your IDE:

Right-click on the HelloWorldApplication.java file and choose “Run”.

From the command line (using Maven):

Navigate to your project’s root directory (where pom.xml is located) in your terminal and run:

mvn spring-boot:run

You should see output indicating that Spring Boot has started on port 8080 (by default).

...
2023-10-27 10:30:00.123  INFO 12345 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-10-27 10:30:00.134  INFO 12345 --- [  restartedMain] c.a.r.h.HelloWorldApplication            : Started HelloWorldApplication in X.XXX seconds (JVM running for Y.YYY)
...

Step 6: Test Your REST API

Once the application is running, open your web browser or use a tool like Postman or curl to test the endpoints:

Test 1: Simple String Response

Go to: http://localhost:8080/hello

You should see the text:

Hello from ankurm.com REST API!

Test 2: JSON Response

Go to: http://localhost:8080/hello-json

You should see a JSON output similar to this:

{
  "message": "Hello from ankurm.com REST API!",
  "author": "Ankur M."
}

Congratulations! You’ve successfully built and tested your first Spring Boot RESTful API that returns JSON data.

What’s Next?

This is just the beginning! From here, you can explore many more features of Spring Boot REST, such as:

  • Handling path variables and request parameters
  • Implementing POST, PUT, and DELETE requests
  • Validation of request bodies
  • Error handling
  • Connecting to databases
  • Security

Stay tuned to ankurm.com for more in-depth tutorials on building powerful web services with Spring Boot. If you have any questions or run into issues, feel free to leave a comment below!

Happy Coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.