Maybe, you are asking what is REST? What is RESTful Web Service with Spring Boot?

REST is an acronym for REpresentational State Transfer. It is an architectural style for distributed hypermedia systems. REST was first presented by Roy Fielding in 2000 in his famous dissertation.

Then, REST has quickly become the de-facto standard for building web services on the web because they’re easy to build and easy to consume.

RESTful Web Service with Spring Boot

If an architecture complies with REST principles, it is called a RESTful architecture.

About this RESTful Web Service with Spring Boot

In the following content, we will build a simple RESTful web service with Spring Boot. When visiting the web service, it will respond with some objects data in JSON.

When the RESTful Web Service getting HTTP GET requests at http://localhost:8080/greeting , the web service will respond with a JSON object data, such as:

{"id":1,"content":"Hello, world!"}

Also, you can add an optional name parameter in the request URL, like this:

http://localhost:8080/greeting?name=etbye

Then, the respond JSON data will like this:

{"id":1,"content":"Hello, etbye!"}

Building a Spring Boot web project

The Spring Boot recommends starting all Spring applications with the Spring Initializr. The benefit of this way to start a Spring Boot application is some setups are done for you.

In fact, if you are using IDE, such as Eclipse or IntelliJ IDEA, it’s very easy to create a new Spring Boot application.

Add dependency into pom.xml

Here, I’m going to build a RESTful Web Service with Spring Boot. So, it needs to add spring-boot-starter-web dependency into the pom.xml. The spring-boot-starter-web includes Spring MVC and REST structures.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.etbye</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>13</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Creating a resource representation class

Now, we need to create a resource representation class to model the greeting representation. So, we will create a POJO Java object with fields, constructors, and accessors for the id and content data.

package com.etbye.restservice;

public class Greeting {
    private final long id;
    private  final String content;
    
    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

The web starter includes Jackson, so, when the project running, the Spring Boot web application will use the Jackson JSON library to automatically convert instances of type Greeting into JSON. We no need to cast the object data into JSON data.

Create a Resource Controller

In RESTful web services with Spring Boot, HTTP requests are handled by a controller, which is identified by the @RestController annotation.

package com.etbye.restservice;

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

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "world") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

Some explanations:

  • @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It is shorthand for including both @Controller and @ResponseBody.
  • The @GetMapping annotation mapped the HTTP GET requests to /greeting with the greeting() method. There are also some similar annotations for other HTTP, such as  @PostMapping for POST.
  • @RequestParam to binds parameters. Here, it binds the value of the query string parameter name into the name parameter of the greeting() method.

Run the project

The code in XXXApplicaiton is not needed to modify.

...
@SpringBootApplication
public class RESTwebApplication {

    private static final Logger log = LoggerFactory.getLogger(RESTwebApplication.class);

}

Run the application by using ./mvnw spring-boot:run if you use Maven. Or run it through your IDE.

Of course, you can also build an executable JAR to run anywhere. For the executable JAR file contains all the necessary dependencies, classes, and resources and run that.

Build the executable JAR file with the command:

 ./mvnw clean package

Run the RESTful web service by JAR file:

$ java -jar target/demo-0.0.1-SNAPSHOT.jar

Open a browser, visit http://localhost:8080/greeting, then you should see the result:

{"id":1,"content":"Hello, World!"}

Visiting http://localhost:8080/greeting?name=Etbye , it will get the result:

{"id":2,"content":"Hello, etbye!"}

By now, the simplest RESTful web service with Spring Boot had finished.

Check out more posts about Spring Boot on Etbye.

Reference: https://spring.io/guides/gs/rest-service/