© Balaji Varanasi and Maxim Bartkov 2022
B. Varanasi, M. BartkovSpring RESThttps://doi.org/10.1007/978-1-4842-7477-4_3

3. RESTful Spring

Balaji Varanasi1   and Maxim Bartkov2
(1)
Salt Lake City, UT, USA
(2)
Kharkov, Ukraine
 
In this chapter, we will discuss the following:
  • The basics of Spring Boot

  • Building a Hello World REST application

  • Tools for accessing REST applications

One of the Spring Framework’s goals is to reduce plumbing code so that developers can focus their efforts on implementing core business logic. However, as the Spring Framework evolved and added several subprojects to its portfolio, developers ended up spending a considerable amount of time setting up projects, finding project dependencies, and writing boiler plate code and configuration.

Spring Boot, a Spring portfolio project, aims at simplifying Spring application bootstrapping by providing a set of starter project templates. These would pull all the proper dependencies that are needed based on project capabilities. For example, if you enable JPA capability, it automatically includes all the dependent JPA, Hibernate, and Spring JAR files.

Spring Boot also takes an opinionated approach and provides default configuration that simplifies application development quite a bit. For example, if Spring Boot finds JPA and MySQL JARs in the classpath, it would automatically configure a JPA Persistence Unit. It also enables creation of standalone Spring applications with embedded Jetty/Tomcat servers, making them easy to deploy on any machine with just Java installed. Additionally, it provides production-ready features such as metrics and health checks. Throughout this book, we will be exploring and learning these and additional features of Spring Boot.

Note

Spring Roo is another Spring portfolio project that attempts to provide rapid Spring application development. It provides a command line tool that enables easy project bootstrapping and generates code for components such as JPA entities, web controllers, test scripts, and necessary configuration. Although there was a lot of initial interest in the project, Spring Roo never really became mainstream. AspectJ code generation and a steep learning curve coupled with its attempt to take over your project are some reasons for lack of its adoption. Spring Boot, by contrast, takes a different approach; it focuses on jump-starting the project and providing clever, sensible, default configuration. Spring Boot doesn’t generate any code that makes it easy to manage your project.

Generating a Spring Boot Project

It is possible to create a Spring Boot project from scratch. However, Spring Boot provides the following options to generate a new project:
  • Use Spring Boot’s starter website (http://start.spring.io).

  • Use the Spring Tool Suite (STS) IDE.

  • Use the Boot command line interface (CLI).

We will explore all three alternatives in this chapter. However, for the rest of the book, we will be opting for the Boot CLI to generate new projects. Before we start with project generation, it is important that Java is installed on your machine. Spring Boot requires that you have Java SDK 1.8 or higher installed. In this book we will be using Java 1.8.

Installing a Build Tool

Spring Boot supports the two most popular build systems: Maven and Gradle. In this book we will be using Maven as our build tool. Spring Boot requires Maven version 3.5 or higher. The steps to download and configure Maven on your Windows machine are given here. Similar instructions for Mac and other operating systems can be found on Maven’s install page (https://maven.apache.org/install.html):
  1. 1.

    Download the latest Maven binary from https://maven.apache.org/download.cgi. At the time of writing this book, the current version of Maven was 3.8.1. For Windows, download the apache-maven-3.8.1-bin.zip file.

     
  2. 2.

    Unzip the contents of the zip file under C: oolsmaven.

     
  3. 3.

    Add an Environment variable M2_HOME with value C: oolsmavenapache-maven-3.8.1. This tells Maven and other tools where Maven is installed. Also make sure that the JAVA_HOME variable is pointing to the installed JDK.

     
  4. 4.

    Append the value %M2_HOME%in to the Path environment variable. This allows you to run Maven commands from the command line.

     
  5. 5.

    Open a new command line and type the following:

     
mvn - v
You should see an output similar to Figure 3-1, indicating that Maven was successfully installed.
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig1_HTML.png
Figure 3-1

Maven installation verification

Note

To learn more about Maven, refer to Introducing Maven, published by Apress (http://www.apress.com/9781484208427).

Generating a Project Using start.spring.io

Spring Boot hosts an Initializr application at http://start.spring.io . The Initializr provides a web interface that allows you to enter project information and pick the capabilities needed for your project, and voilà—it generates the project as a zip file. Follow these steps to generate our Hello World REST application:
  1. 1.

    Launch the http://start.spring.io website in your browser and enter the information shown in Figure 3-2.

     
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig2_HTML.png
Figure 3-2

start.spring.io website

  1. 2.

    Under Dependencies ➤ Web, select the option “Web” and indicate that you would like Spring Boot to include web project infrastructure and dependencies.

     
  2. 3.

    Then hit the “Generate Project” button. This will begin the hello-rest.zip file download.

     
On completion of the download, extract the contents of the zip file. You will see the hello-rest folder generated. Figure 3-3 shows the contents of the generated folder.
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig3_HTML.jpg
Figure 3-3

hello-rest application contents

A quick look at the hello-rest contents shows that we have a standard Maven-based Java project layout. We have the srcmainjava folder, which houses Java source code; srcmain esources, which contains property files; static content, such as HTMLCSSJS files; and the src estjava folder, which contains the test cases. On running a Maven build, this project generates a JAR artifact. Now, this might be a little confusing for the first-timer who is used to WAR artifacts for deploying web applications. By default, Spring Boot creates standalone applications in which everything gets packaged into a JAR file. These applications will have embedded servlet containers such as Tomcat and are executed using a good old main() method.

Note

Spring Boot also allows you to work with WAR artifacts which contain html, css, js, and other files necessary for the development of web applications that can be deployed to external Web and application containers.

Listing 3-1 gives the contents of the hello-rest application’s pom.xml file .
<?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.5.3</version>
            <relativePath/>
      </parent>
      <groupId>com.appress</groupId>
      <artifactId>hello-rest</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <name>Hello World REST</name>
      <description>Hello World REST Application Using Spring Boot</description>
      <properties>
            <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>
      </build>
</project>
Listing 3-1

hello-rest pom.xml file Contents

The groupId, artifactId, and version elements in the pom.xml file correspond to Maven’s standard GAV coordinates describing our project. The parent tag indicates that we will be inheriting from the spring-boot-starter-parent POM. This ensures that our project inherits Spring Boot’s default dependencies and versions. The dependencies element lists two POM file dependencies: spring-boot-starter-web and spring-boot-starter-test. Spring Boot uses the term starter POMs to describe such POM files.

These starter POMs are used to pull other dependencies and don’t actually contain any code of their own. For example, the spring-boot-starter-web pulls Spring MVC dependencies, Tomcat-embedded container dependencies, and a Jackson dependency for JSON processing. These starter modules play an important role in providing needed dependencies and simplifying the application’s POM file to just a few lines. Table 3-1 lists some of the commonly used starter modules.
Table 3-1

Spring Boot Starter Modules

Starter POM dependency

Use

spring-boot-starter

Starter that brings in core dependencies necessary for functions such as auto-configuration support and logging

spring-boot-starter-aop

Starter that brings in support for aspect-oriented programming and AspectJ

spring-boot-starter-test

Starter that brings in dependencies such as JUnit, Mockito, and spring-test necessary for testing

spring-boot-starter-web

Starter that brings in MVC dependencies (spring-webmvc) and embedded servlet container support

spring-boot-starter-data-jpa

Starter that adds Java Persistence API support by bringing in spring-data-jpa, spring-orm, and Hibernate dependencies

spring-boot-starter-data-rest

Starter that brings in spring-data-rest-webmvc to expose repositories as REST API

spring-boot-starter-hateoas

Starter that brings in spring-hateoas dependencies for HATEOAS REST services

spring-boot-starter-jdbc

Starter for supporting JDBC databases

Finally, the spring-boot-maven-plugin contains goals for packaging the application as an executable JAR/WAR and running it.

The HelloWorldRestApplication.java class serves as the main class for our application and contains the main() method. Listing 3-2 shows the contents of the HelloWorldRestApplication.java class. The @SpringBootApplication annotation is a convenient annotation and is equivalent to declaring the following three annotations:
  • @Configuration—Marks the annotated class as containing one or more Spring bean declarations. Spring processes these classes to create bean definitions and instances.

  • @ComponentScan—This class tells Spring to scan and look for classes annotated with @Component, @Service, @Repository, @Controller, @RestController, and @Configuration. By default, Spring scans all the classes in the package where the @ComponentScan annotated class resides. To override the default behavior, we can set this annotation in the configuration class and define basePackages argument as the name of the package.

  • @EnableAutoConfiguration—Enables Spring Boot’s auto-configuration behavior. Based on the dependencies and configuration found in the classpath, Spring Boot intelligently guesses and creates bean configurations.

Typical Spring Boot applications always use these three annotations. In addition to providing a nice alternative in those scenarios, the @SpringBootApplication annotation correctly denotes the class’s intent.
package com.apress.hellorest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWorldRestApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloWorldRestApplication.class, args);
    }
}
Listing 3-2

HelloWorldRestApplication Contents

The main() method simply delegates the application bootstrapping to SpringApplication’s run() method. run() takes a HelloWorldRestApplication.class as its argument and instructs Spring to read annotation metadata from HelloWorldRestApplication and populate ApplicationContext from it.

Now that we have looked at the generated project, let’s create a REST endpoint that simply returns “Hello REST.” Ideally, we would create this endpoint in a separate controller Java class. However, to keep things simple, we will create the endpoint in HelloWorldRestApplication, as shown in Listing 3-3. We start by adding the @RestController, indicating that HelloWorldRestApplication has possible REST endpoints. We then create the helloGreeting() method, which simply returns the greeting “Hello REST.” Finally, we use the RequestMapping annotation to map web requests for “/greet” path to helloGreeting() handler method.
package com.apress.hellorest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@RestController
public class HelloWorldRestApplication {
    public static void main(String args) {
        SpringApplication.run(HelloWorldRestApplication.class, args);
    }
    @GetMapping("/greet")
    public String helloGreeting() {
        return "Hello REST";
    }
}
Listing 3-3

Hello REST Endpoint

The next step is to launch and run our application. To do this, open a command line, navigate to the hello-rest folder, and run the following command:
mvn spring-boot:run
You will see Maven downloading the necessary plugins and dependencies, and then it will launch the application, as shown here:
  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _
( ( )\___ | '_ | '_| | '_ / _` |
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
[32m :: Spring Boot :: [39m              [2m (v2.5.3)[0;39m
[2m2021-08-12 21:54:43.147[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[         main][0;39m [36mc.a.hellorest.HelloWorldRestApplication [0;39m [2m:[0;39m Starting HelloWorldRestApplication using Java 1.8 on DESKTOP-82GK4GP with PID 15012 (C:UsersmakusOneDriveDesktophello-rest argetclasses started by makus in C:UsersmakusOneDriveDesktophello-rest)
[2m2021-08-12 21:54:43.149[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[         main][0;39m [36mc.a.hellorest.HelloWorldRestApplication [0;39m [2m:[0;39m No active profile set, falling back to default profiles: default
[2m2021-08-12 21:54:43.843[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[         main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat initialized with port(s): 8080 (http)
[2m2021-08-12 21:54:43.851[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[         main][0;39m [36mo.apache.catalina.core.StandardService  [0;39m [2m:[0;39m Starting service [Tomcat]
[2m2021-08-12 21:54:43.851[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.apache.catalina.core.StandardEngine [0;39m [2m:[0;39m Starting Servlet engine: [Apache Tomcat/9.0.50]
[2m2021-08-12 21:54:43.917[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].      [0;39m [2m:[0;39m Initializing Spring embedded WebApplicationContext
[2m2021-08-12 21:54:43.917[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[           main][0;39m [36mw.s.c.ServletWebServerApplicationContext[0;39m [2m:[0;39m Root WebApplicationContext: initialization completed in 734 ms
[2m2021-08-12 21:54:44.286[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[         main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat started on port(s): 8080 (http) with context path ''
[2m2021-08-12 21:54:44.297[0;39m [32m INFO[0;39m [35m15012[0;39m [2m---[0;39m [2m[         main][0;39m [36mc.a.hellorest.HelloWorldRestApplication [0;39m [2m:[0;39m Started HelloWorldRestApplication in 1.445 seconds (JVM running for 2.055)
To test our running application, launch a browser and navigate to http://localhost:8080/greet. Notice that Spring Boot launches the application as the Root context and not the hello-world context. You should see a screen similar to that in Figure 3-4.
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig4_HTML.jpg
Figure 3-4

Hello REST greeting

Spring Initializr

The Spring Initializr application hosted at http://start.spring.io itself is built using Spring Boot. You can find the source code of this application on GitHub at https://github.com/spring-io/initializr. It is also possible for you to build and host your own instances of the Initializr application.

In addition to providing a web interface, the Initializr provides an HTTP endpoint that provides similar project generation capability. In fact, Spring Boot’s CLI and IDEs such as STS use this HTTP endpoint behind the scenes for generating projects.

The HTTP endpoint can also be invoked from the command line using curl. For example, the following command would generate the hello-rest project zip file using curl. The –d options are used to provide data that gets passed as request parameters:
curl https://start.spring.io/starter.zip -d style=web -d name=hello-rest

Generating a Project Using STS

Spring Tool Suite or STS is a free Eclipse-based development environment that provides great tooling support for developing Spring-based applications. You can download and install the latest version of STS from Pivotal’s website at https://spring.io/tools. At the time of writing this book, the current version of STS was 4.11.0.

STS provides a user interface similar to Initializr’s web interface for generating Boot starter projects. Here are the steps for generating a Spring Boot project:
  1. 1.

    Launch STS if you haven’t already done so. Go to File ➤ New and click Spring Starter Project, as shown in Figure 3-5.

     
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig5_HTML.jpg
Figure 3-5

STS Spring starter project

  1. 2.

    In the following screen, enter the information as shown in Figure 3-6. Enter Maven’s GAV information. Hit Next.

     
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig6_HTML.png
Figure 3-6

Starter project options

  1. 3.

    In the following screen, enter the information as shown in Figure 3-7. Select the web starter option. Hit Next.

     
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig7_HTML.png
Figure 3-7

Starter project options

  1. 4.

    On the following screen, change the location where you would like to store the project. The “Full Url” area shows the HTTP REST endpoint along with the options that you selected (see Figure 3-8).

     
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig8_HTML.png
Figure 3-8

Starter project location

  1. 5.

    Hit the Finish button and you will see the new project created in STS. The contents of the project are similar to the project that we created earlier (see Figure 3-9).

     
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig9_HTML.png
Figure 3-9

STS Spring starter project resources

STS’s starter project wizard provides a convenient way to generate new Spring Boot projects. The newly created project automatically gets imported into the IDE and is immediately available for development.

Generating a Project Using the CLI

Spring Boot provides a command line interface (CLI) for generating projects, prototyping, and running Groovy scripts. Before we can start using the CLI, we need to install it. Here are the steps for installing the Boot CLI on a Windows machine:
  1. 1.

    Download the latest version of the CLI ZIP distribution from Spring’s website at https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started.html#getting-started.installing.cli. At the time of writing this book, the current version of CLI was 2.5.3. This version can be downloaded directly from https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.5.3/spring-boot-cli-2.5.3-bin.zip.

     
  2. 2.

    Extract the zip file and place its contents (folders such as bin and lib) under C: oolsspringbootcli, as shown in Figure 3-10.

     
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig10_HTML.jpg
Figure 3-10

Spring Boot CLI contents

  1. 3.

    Add a new environment variable SPRING_HOME with value c: oolsspringbootcli.

     
  2. 4.

    Edit the Path environment variable, and add the %SPRING_HOME%/bin value to its end.

     
  3. 5.

    Open a new command line and verify the installation running the following command:

     
spring --version
You should see an output similar to that shown in Figure 3-10.
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig11_HTML.jpg
Figure 3-11

Spring Boot CLI installation

Now that we have the Boot CLI installed, generating a new project simply involves running the following command at the command line:
spring init --dependencies web rest-cli
The command creates a new rest-cli project with web capability. The output of running the command is shown in Listing 3-4.
C: est>spring init --dependencies web rest-cli
Using service at https://start.spring.io
Project extracted to 'C: est est-cli'
Listing 3-4

Boot CLI Output

Accessing REST Applications

There are several free and commercial tools that allow you to access and experiment with REST API/applications. In this section we will look at some of the popular tools that allow you to quickly test a request and inspect the response.

Postman

Postman is a Chrome browser extension for making HTTP requests. It offers a plethora of features that makes it easy to develop, test, and document a REST API. A Chrome app version of Postman is also available that provides additional features such as bulk uploading that are not available in the browser extension.

Postman can be downloaded and installed from the Chrome Web Store. To install Postman, simply launch the Chrome browser and navigate to https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop. You might be asked to log in to your Google Chrome account and confirm using the “New app” installation dialog. On completion of the installation, you should be able to locate and launch Postman using the “Apps icon” in the Bookmarks bar or by typing chrome://apps/shortcut. Figure 3-10 shows Postman launched in the Chrome browser.

Postman provides a clean intuitive user interface for composing an HTTP request, sending it to a server, and viewing the HTTP response. It also automatically saves the requests, which are readily available for future runs. Figure 3-12 shows an HTTP GET request made to our Greet service and its response. You can also see the request saved in the History section of the left sidebar.
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig12_HTML.png
Figure 3-12

Postman browser extension

Postman makes it easy to logically group related API calls into collections, as shown in Figure 3-12. It is possible to have subcollections of requests under a collection.
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig13_HTML.jpg
Figure 3-13

Postman collections

RESTClient

RESTClient is a Firefox extension for accessing REST APIs and applications. Unlike Postman, RESTClient doesn’t have a lot of bells and whistles, but it provides basic functionality to quickly test a REST API. To install RESTClient, launch the Firefox browser and navigate to the URL https://addons.mozilla.org/en-US/firefox/addon/restclient/. Then click the “+ Add to Firefox” button, and in the following “Software Installation” dialog, click the “Install Now” button.

On completion of the installation, you can launch RESTClient using the RESTClient icon ../images/332520_2_En_3_Chapter/332520_2_En_3_Figa_HTML.jpg on the top right corner of the browser. Figure 3-14 shows the RESTClient application with a request to our Greet service and the corresponding response.
../images/332520_2_En_3_Chapter/332520_2_En_3_Fig14_HTML.jpg
Figure 3-14

RESTClient

Summary

Spring Boot provides an opinionated approach to building Spring-based applications. In this chapter, we looked at Spring Boot’s features and used it to build a Hello World REST application. We also looked at the Postman and RESTClient tools for testing and exploring the REST API.

In the next chapter, we will begin working on a more complex REST application and discuss the process of identifying and designing resources.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.190