Spring Boot Rest Example

In this article of Spring Boot tutorial. we will have a detail look at the Spring Boot REST example. Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot is easy with support from Spring Boot auto configuration feature.

 

Introduction

In this post, we will create a Spring Boot rest example. This will be a step-by-step exercise to build a RESTful web service using Spring Boot. We will develop a web-service using the following main features.

  1. Create a customer.
  2. Get Customer/ Customers.
  3. Delete a Customer.

 

1. Creating Spring Boot Project

To start with our Spring Boot REST example, let’s create a Spring Boot web application. We can either use Spring Initializr or use IDE to create Spring Boot application. This is how our pom.xml look like:

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.javadevjournal</groupId>
    <artifactId>spring-boot-rest-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring Boot Rest Example</name>
    <description>Spring Boot Rest Example</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-devtools</artifactId>
            <scope>runtime</scope>
        </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>

We will add JPA capabilities later int he articles. We will use JPA for storing and fetching customer information.

 

2. Quick Introduction to REST

REST is a short form of REpresentational State Transfer. Introduced by Roy Fielding, REST is an architecture style for distributed hypermedia systems. REST is not a standard but think of it as a set of constraints or principles it must satisfy if we want to refer to an interface as RESTful. While working on the REST API, we should keep in mind the following HTTP methods:

  1. GET – To fetch resources
  2. POST – To create resources
  3. PUT  – Update resources
  4. DELETE – Delete resources
  5. PATCH – Partial update to a resource
Read HTTP Methods in RESTful Web Services  to get a basic understanding of the HTTP methods for your REST API.

 

3. Spring Boot REST Controller

Let’s create our REST controller for this exercise. Before we start, let’s keep following point in mind:

  • Spring we will use @ResstController annotation for our controller.
  •  A convenience annotation that is itself annotated with @Controller and @ResponseBody.
  • HTTP GET will return customer or customers list.
  • HTTP POST will create a customer.
  • DELETE method will remove a customer from the system
package com.javadevjournal.controller;

import com.javadevjournal.data.Customer;
import com.javadevjournal.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation. * ;

import java.util.ArrayList;
import java.util.List;

@[email protected](value = "/customers")
public class CustomerController {

	@Autowired CustomerService customerService;

     /**
     * Get all the customer available in the underlying system
     * @return list of customers
     */
	@GetMapping
	public ResponseEntity < List < Customer >> getCustomers() {
		List < Customer > customers = customerService.getCustomers();
		return new ResponseEntity < >(customers, HttpStatus.OK);
	}

     /**
     * Create a customer with the system.This end point accepts customer information in 
     * the json format.It will create and send back the data to the REST customer.
     * @param customer
     * @return newely created customer
     */
	@PostMapping(value = "/customer")
	public ResponseEntity < Customer > createCustomer(@RequestBody Customer customer) {
		final Customer customerData = customerService.createCustomer(customer);
		return new ResponseEntity < >(customerData, HttpStatus.CREATED);
	}

     /**
     * Deleted the customer from the system.client will pass the ID for the customer and this 
     * end point will remove customer from the system if found.
     * @param id
     * @return
     */
	@DeleteMapping(value = "/customer/{id}")
	public ResponseEntity < String > deleteCustomer(@PathVariable Long id) {
		customerService.deleteCustomer(id);
		return new ResponseEntity < >(HttpStatus.OK);
	}

     /**
     * Get the customer detail based on the id passed by the client API.
     * @param id
     * @return customer detail
     */
	@GetMapping(value = "/customer/{id}")
	public ResponseEntity < Customer > getCustomer(@PathVariable Long id) {
		Customer customer = customerService.getCustomer(id);
		return new ResponseEntity < >(customer, HttpStatus.OK);
	}
}

This is our Customer data class:

public class Customer {

	private String name;
	private int age;
	private String email;
	private Long id;

	//getter and setter
}
There are few important points while working on the REST API like REST API Discoverability and naming conventions, etc. But to keep this article simple, I am leaving it blank. Please refer to the Build REST API with Spring for detail.

 

4. Spring Boot Main Class

Here is our Spring Boot main class:

@SpringBootApplication
public class SpringBootRestExampleApplication {

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

 

5. Accessing Data with JPA

For the completeness of this article, we will use Spring Boot JPA capabilities to store and retrieve customer section. I will not explain this as this need separate post. We do not relate this section to REST but probably part of your application layout (when working on real REST services).

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class CustomerModel {

	@[email protected](strategy = GenerationType.AUTO)
	private Long id;
	private String name;
	private int age;
	private String email;

	//getters and setters
	public Long getId() {
		return id;
	}
}

Our repository interface that works with Customer entities:

package com.javadevjournal.dao.entity;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<CustomerModel,Long> {
}

Service class which works between REST controller and Data layer:

package com.javadevjournal.service;

import com.javadevjournal.dao.entity.CustomerModel;
import com.javadevjournal.dao.entity.CustomerRepository;
import com.javadevjournal.data.Customer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class CustomerService {

    @Autowired CustomerRepository customerRepository;

    public Customer createCustomer(final Customer customer) {

        CustomerModel customerModel = new CustomerModel();
        BeanUtils.copyProperties(customer, customerModel);
        customerModel = customerRepository.save(customerModel);
        Customer customerData = new Customer();
        BeanUtils.copyProperties(customerModel, customerData);

        return customerData;
    }

    public List getCustomers() {
        List customers = new ArrayList<>();
        customerRepository.findAll().forEach(customers::add);

        List customerList = new ArrayList<>();
        for (CustomerModel customerModel : customers) {
            Customer customer = new Customer();
            BeanUtils.copyProperties(customerModel, customer);
            customerList.add(customer);
        }

        return customerList;
    }

    public Customer getCustomer(Long id) {

        Optional customer = customerRepository.findById(id);
        Customer customerData = new Customer();
        BeanUtils.copyProperties(customer.get(), customerData);
        return customerData;
    }

    public void deleteCustomer(Long id) {
        customerRepository.deleteById(id);
    }
}

 

6. Testing REST API

It’s time to see our Spring Boot REST example in action. Build and deploy your application. The easiest way is to run the main() method in SpringBootRestExampleApplication class. This will start the embedded tomcat. Once the application start, we will use REST client to test our application.

 

6.1 Create Customer

Let’s create customers. Open the REST client and use the http://{host}:{post}/customers/customer  with POST

Spring Boot Rest Example

Response

{
"name": "Java Dev Journal",
"age": 34,
"email": "[email protected]",
"id": 3
}

 

6.2 Get Customers

Now we have created few customer, let’s get this list from the REST API:

Customers

REST API Response:

[
    {
        "name": "Java Dev Journal",
        "age": 30,
        "email": "[email protected]",
        "id": 1
    },
    {
        "name": "Java Dev Journal",
        "age": 33,
        "email": "[email protected]",
        "id": 2
    },
    {
        "name": "User 1",
        "age": 34,
        "email": "[email protected]",
        "id": 3
    }
]

 

6.3 Get Customer By ID

our REST API example also has an endpoint to give customer information based on the ID:

Get Customer Detail

REST API Response:

{
    "name": "Java Dev Journal",
    "age": 30,
    "email": "[email protected]",
    "id": 1
}

 

Summary

In this article, we have a detail look at the Spring Boot REST example. We covered the steps to create a REST API using Spring Boot. The source code for this article is available on our GitHub repository

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of