BUILDING A SPRING BOOT REST WEB SERVICE IN 4 STEPS

It only takes you 15 minutes to build a REST service with the help of Spring Boot. Follow our simple steps to get you going.

Apr 10th 2018
Building a Spring Boot REST web service in 4 steps

As a Java Developer, you are without a doubt familiar with Spring – definitely, one of the most popular Java-based frameworks to build web and enterprise applications. Spring Boot is a Spring project that makes the process of configuring and publishing Spring-based applications much easier. With the aid of Spring Boot, you can have your project running as quickly as possible with the slightest upfront configuration of Spring.

In this example, I will explain how to build a simple web service with Representational State Transfer (REST) with Java.

The application will be built using Maven, which will manage the dependencies and create the JAR file that has embedded the servlet (tomcat/undertow/jetty).

 

1. Create the file

To begin with, start by creating a pom.xml in a directory of choice.

<?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>
    <artifactId>cleverti-api</artifactId>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

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

 

That’s it! The project can be built, but nothing will be created because there is no source code yet.

So let’s add some code!

First, we’ll add the start file, where the application main method is located. This file needs to be created in this directory structure: src/main/java/, and in the package com/cleverti with the name Application.java.

package com.cleverti;

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

@SpringBootApplication
public class Application {

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

 

Done! The JAR file is now created!

But wait… it can’t run yet. We need to inform Maven that this is a Spring Boot application. To do that, just add the following plugin in the Maven pom file.

<build>
        <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>build-info</id>
                            <goals>
                                <goal>build-info</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
        </plugins>
    </build>

 

Ok, now everything is set for the application to start. The plugin will create the JAR with all the dependencies needed. Spring Boot by default will use Tomcat Java servlet embedded.

To start the application just call it with Java:

java -jar target/cleverti-0.1.jar

By default, the application runs at localhost with port 8080.

 

2. Add the controller

The application is working, but no REST is added yet. For that, we need to add a Java file (AppController.java) with the controller.

package com.cleverti;

import org.springframework.web.bind.annotation.*;

@RestController
public class AppController {

    @GetMapping(path = "/")
    public String get() {
        return "hello world";
    }
}

 

This is the simplest example of a REST application.

If we make a GET request to http://localhost:8080, the returned response will be “Hello world”.

 

3. Add the Model

At this time, we want to connect some kind of datasource to this application. To maintain this application simple we will add a memory base database. Other databases can be added if needed.

These dependencies are added to the pom file.

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
       </dependency>

 

3 are added:

1. data-jpa 

  • This is the data access layer API

2. h2

  • Memory base database (The database is created at startup)
  • Spring boot will auto-detect this datasource

3. lombok

  • Create getter/setter at compile time
package com.cleverti;

import javax.persistence.*;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;

@Entity
@Table
@Getter
@Setter
public class AppModel implements Serializable {

    private static final long serialVersionUID = 876688928410084519L;

    @Id
    private long id;

    private String message;
}

 

We will then create the java file for the model and the service.

package com.cleverti;

import org.springframework.data.repository.CrudRepository;

public interface AppService extends CrudRepository<AppModel, Long> {

}

 

Is some kind of magic happening here? Not really!

Spring Boot will create all the queries for a model when you extend the interface CrudRepository.

So all CRUD requests will be available for you at Runtime.

For this example to work, we need some data in the database, so we can fetch it.

Just create the folder resources inside the main folder. Then inside the resources create an SQL file, for example, data.sql. By default, all SQL scripts are loaded before application startup.

Add the line:

  • insert into app_model values (1, 'hello world');
package com.cleverti;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.RuntimeException;

@RestController
public class AppController {

    @Autowired
    private AppService service;

    @GetMapping(path = "/")
    public AppModel get() {
         return service.findById(1L).orElseThrow(() -> new RuntimeException("Not found"));
    }
}

 

New version of the controller

By default, the response of a model is in JSON format.

So if we make another GET request to http://localhost:8080, the returned response will be:

{"id":1,"message":"hello world"}

 

4. HATEOAS

The REST service is not 100% implemented if we don’t apply the constraint of Hypermedia as the Engine of Application State (HATEOAS).

This means that we will not only return the model but also the resources available for that model.

We need to add this dependency to the pom file

<dependency>
            <groupId>org.springframework.hateoas</groupId>
            <artifactId>spring-hateoas</artifactId>
  </dependency>

 

Then we add a resource assembler to AppModel to the project, so we can add links to the response.

package com.cleverti;

import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.stereotype.Component;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;

@Component
public class AppModelResourceAssembler implements ResourceAssembler<AppModel, Resource<AppModel>> {
    
    public Resource toResource(AppModel entity) {
        Resource<AppModel> resource = new Resource<>(entity);

        addLinks(resource);

        return resource;
    }

    public void addLinks(Resource<AppModel> resource) {
        resource.add(linkTo(AppController.class).slash(resource.getContent()).withSelfRel());
    }
}

 

The get method will now return a Resource, so we need to change the AppController file.

package com.cleverti;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.RuntimeException;
import org.springframework.hateoas.Resource;

@RestController
public class AppController {

    @Autowired
    private AppService service;

    @Autowired
    private AppModelResourceAssembler assembler;

    @GetMapping(path = "/")
    public Resource<AppModel> get() {
         AppModel model = service.findById(1L).orElseThrow(() -> new RuntimeException("Not found"));

         return assembler.toResource(model);
    }
}

 

So if we make another GET request to http://localhost:8080, the returned response will be:

{"id":1,"message":"hello world","links":[{"rel":"self","href":"http://localhost:8080/1"}]}

The response contains a link with a self reference.

 

That’s it! This is a simple example of creating a Spring boot REST service. 

You can go to https://start.spring.io/ to generate your project and add all the dependencies needed on the fly.

 

Written by Patrício Pereira | Developer at Cleverti

background

Cleverti: 100% portuguese technology company with 35% growth

Back to News.. Next Article