Spring Boot REST Example

0

In this article we will build a REST application using Spring Boot. Spring Boot aims at simplifying Spring application bootstrapping by providing a set of starter project templates. The project templates help add the necessary dependencies. In case of a REST application, we need to add spring-boot-starter-web which in turn will add spring-boot-starter, spring-boot-tomcat, spring-web, spring-webmvc and few other artifacts. spring-boot-tomcat enables creation of standalone Spring applications by embedding a Tomcat server

Build Spring REST project

We will first build a Spring Boot project using Spring Boot’s starter website http://start.spring.io. Enter the group and artifact information. Add web as the dependency and then click on ‘Generate Project’. Unzip the source code and import in Eclipse as a Maven project.

springRESTStarterIO

Dependencies

  1. spring-boot-starter-parent – This is the parent POM. It will provide the useful Maven defaults.
  2. spring-boot-starter-web – Since we are developing a REST service, we will need spring web based dependencies. The web starter will also set up an embedded servlet container.
  3. spring-boot-starter-test – This will add spring-test module and test dependencies like JUnit, Hamcrest and Mockito.
Spring Boot Web Dependencies

Spring Boot Web Dependencies

  1. spring-boot-starter – The core Spring Boot starter, including auto-configuration support, logging and YAML
    spring-boot-starter

    spring-boot-starter

  2. spring-boot-starter-tomcat – provides an embedded servlet container
  3. spring-boot-autoconfigure – Spring Boot figures out how to configure based on the jar dependencies that you have added.
  4. spring-boot-starter-validation – Adds hibernate validator, an implementation of bean validation API
  5. jackson-databind – JSON data binding
  6. spring-web and spring-webmvc – spring web modules
spring-boot-starter-web dependencies

spring-boot-starter-web dependencies

pom.xml:

<?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>com.javarticle.spring.rest</groupId>
	<artifactId>SpringRESTExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>SpringRESTExample</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<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>

In this example, we will create a REST service and a REST client.

REST Service

Our REST service will return all the employee objects.

Employee:

package com.javarticle.spring.rest;

public class Employee {
    private String id;
    private String name;
    private int age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Let’s define few employees.

EmployeeSource:

package com.javarticle.spring.rest;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class EmployeeSource {
    private static final Map<String, Employee> EMPLOYEES = new HashMap<>();
    static {
        Employee emp1 = new Employee();
        emp1.setId("01");
        emp1.setName("Joe");
        emp1.setAge(32);
        
        Employee emp2 = new Employee();
        emp2.setId("02");
        emp2.setName("Sam");
        emp2.setAge(41);
        
        Employee emp3 = new Employee();
        emp3.setId("03");
        emp3.setName("Phil");
        emp3.setAge(22);
        
        EMPLOYEES.put(emp1.getId(), emp1);
        EMPLOYEES.put(emp2.getId(), emp2);
        EMPLOYEES.put(emp3.getId(), emp3);
    }
    
    public static Collection<Employee> getEmployees() {
        return EMPLOYEES.values();
    }
    
    public static Employee getEmployee(String empId) {
        return EMPLOYEES.get(empId);
    }
}

@RestController and @RequestMapping annotations

We now create a REST controller to handle the web request. Below are the annotations that we must be aware of:

  1. @Controller – Indicates that an annotated class is a “Controller”. Class annotated with @Controller will be automatically registered as Spring Beans. It will look for RequestMapping annotation for mapping web requests onto specific handler classes and/or handler methods.
  2. @ResponseBody – If a @RequestMapping method is annotated with @ResponseBody, its return value will be bound to the web response body. If a method returns a POJO type object, spring will automatically convert it to a JSON style data format and append to the response.
  3. @RequestMapping – It defines the routing information which spring will use to map a web request to a controller’s method
  4. @RestController – A convenience annotation that combines @Controller and @ResponseBody

Method getEmployeeNames will be called as we enter http://localhost:8080/employees in the browser.

RESTControllerExample:

package com.javarticle.spring.rest;

import java.util.Collection;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RESTControllerExample {
    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    public Collection getEmployeeNames() {
        return EmployeeSource.getEmployees();
    }

}

REST Client

We now write a simple REST client to call the above REST service.

RESTClientExample:

package com.javarticle.spring.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component("restClient")
public class RESTClientExample {
    @Autowired
    private RestTemplate restTemplate;

    public String getAllEmployees() {
        return restTemplate.getForObject("http://localhost:8080/employees", String.class);
    }
}

Spring Boot Main Application

The spring boot application will start the server and the make a REST call to our new service and retrieve the employees.

SpringRestExampleApplication:

package com.javarticle.spring.rest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SpringRestExampleApplication {
    
	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(SpringRestExampleApplication.class, args);
		System.out.println(( (RESTClientExample) context.getBean("restClient")).getAllEmployees());
	}
	
	@Bean
    public RestTemplate geRestTemplate() {
        return new RestTemplate();
    }
}

Output:

[{"id":"01","name":"Joe","age":32},{"id":"02","name":"Sam","age":41},{"id":"03","name":"Phil","age":22}]

Download the source code

This was an example about Spring Boot REST services.

You can download the source code here: SpringBootRESTExample.zip

About Author

Ram's expertise lies in test driven development and re-factoring. He is passionate about open source technologies and loves blogging on various java and open-source technologies like spring. You can reach him at [email protected]

Comments are closed.