Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Boot 2: Building a RESTful Web Service

DZone's Guide to

Spring Boot 2: Building a RESTful Web Service

In this article, we will learn how to develop a simple “Hello World!” web application that highlights some of Spring Boot’s key features.

· Integration Zone ·
Free Resource

How to Transform Your Business in the Digital Age: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation.

In this article, we will learn how to develop a simple “Hello World!” web application that highlights some of Spring Boot’s key features. We use Maven to build this project since most IDEs support it.

We use the latest release of Spring Boot 2.0.5.RELEASE which requires Java 8 or 9, Spring Framework 5.0.9.RELEASE or above and Maven 3.2+.

Let's get started with our objective is to build a RESTful web service using Spring Boot 2.

What We'll Build?

We’ll build a service that will accept HTTP GET requests at:

http://localhost:8080/greeting

and respond with a JSON representation of a greeting:

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

We can customize the greeting with an optional name parameter in the query string:

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

The name parameter value overrides the default value of "World" and is reflected in the response:

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

Let me list tools and technologies that we will use to develop RESTFul web services using Spring Boot 2.

Tools and Technologies Used

  • Spring Boot — 2.0.5.RELEASE

  • JDK — 1.8 or later

  • Spring Framework — 5.0.9 RELEASE

  • Maven — 3.2+

  • IDE — Eclipse or Spring Tool Suite (STS)

Create Spring Boot Project

There are many ways to create a Spring Boot application. The simplest way is to use Spring Initializr at http://start.spring.io/, which is an online Spring Boot application generator.

Image title

Refer above diagram and enter the required fields like Group, Artifact, select dependencies etc and click on Generate Project button will generate a spring boot project and downloads it. Next, Unzip the downloaded zip file and import it into your favorite IDE.

Project Directory Structure

Following is the packing structure of this application for your reference-

Image title

Let's understand pom.xml first and then we will start writing code to develop RESTFul API.

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.springboot</groupId>
    <artifactId>Springboot-helloworld-application</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Springboot-helloworld-application</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</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-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

From above pom.xml, let's understand few important spring boot features.

Spring Boot Maven Plugin

The Spring Boot Maven plugin provides many convenient features:

  • It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.

  • It searches for the public static void main() method to flag as a runnable class.

  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.

spring-boot-starter-parent

All Spring Boot projects typically use spring-boot-starter-parent as the parent in pom.xml.

<parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.0.5.RELEASE</version>
</parent>

Parent Poms allow you to manage the following things for multiple child projects and modules:

To know more how Spring Boot Starter Parent works on  Overview of Spring Boot Starter Parent

Create a Resource Representation Class

Now that we’ve set up the project and build system, we can create your web service. The service will handle GET requests for /greeting, optionally with a name parameter in the query string. The GET request should return a 200 OK response with JSON in the body that represents a greeting. It should look something like this:

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

The id field is a unique identifier for the greeting, and content is the textual representation of the greeting.

To model the greeting representation, you create a resource representation class. Provide a plain old java object with fields, constructors, and accessors for the id and content data:

package net.javaguides.springboot.Springboothelloworldapplication;

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

Next, we create the resource controller that will serve these greetings.

Create a Resource Controller

In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @RestController annotation, and the GreetingController below handles GET requests for /greeting by returning a new instance of the Greeting class:

package net.javaguides.springboot.Springboothelloworldapplication;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

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

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

The @RequestMapping annotation ensures that HTTP requests to /greeting are mapped to the greeting() method.

The above example does not specify GET vs. PUT, POST, and so forth, because of @RequestMapping maps all HTTP operations by default. Use @RequestMapping(method=GET) to narrow this mapping.

@RequestParam binds the value of the query string parameter name into the name parameter of the greeting() method. If the name parameter is absent in the request, the defaultValue of "World" is used.

Make the Application Executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.

Spring boot offers many ways to deploy and run Spring boot applications. You can learn on Different Ways of Running Spring Boot Application.

package net.javaguides.springboot.Springboothelloworldapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootHelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootHelloworldApplication.class, args);
    }
}


@SpringBootApplication is a convenience annotation that adds all of the following:
1. @Configuration tags the class as a source of bean definitions for the application context.
2. @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
2. @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.

Running the Application

Usually, we can start the standalone Spring boot application by maven command or from IDE.

1. From the root directory of the application and type the following command to run it -

$ mvn spring-boot:run

2. From your IDE, run the SpringbootHelloworldApplication.main() method as a standalone Java class that will start the embedded Tomcat server on port 8080 and point the browser to http://localhost:8080/.

Now, our application is up and running, it's time to test the service.

Test the Service

Now that the service is up, visit http://localhost:8080/greeting, where you see:

Image titleProvide a name query string parameter with http://localhost:8080/greeting?name=User. Notice how the value of the content attribute changes from "Hello, World!" to "Hello User!":

Image title

That's all, congratulations! You’ve just developed a RESTful web service with the latest release of Spring Boot 2.0.5 RELEASE.

This is a simple web application, to learn how to develop CRUD RESTFul API on Spring Boot 2 Hibernate 5 MySQL CRUD REST API Tutorial

Learn how to do CRUD RESTFul APIs custom validation on Spring Boot CRUD REST APIs Validation Example

Check out how to handle exceptions in Spring boot 2 REST API on Spring Boot 2 Exception Handling for REST APIs.

Thanks for reading, hope you enjoyed reading this article. Happy learning, and keep coding!

Make your mark on the industry’s leading annual report. Fill out the State of API Integration 2019 Survey and receive $25 to the Cloud Elements store.

Topics:
spring boot 2 ,rest api ,maven 3.5.0 ,jdk 1.8 ,integration ,restful web service

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}