SpringSpringBootHow to create a Spring boot rest API in 6 Easy Steps?

How to create a Spring boot rest API in 6 Easy Steps?

In this post, the Spring Boot tutorial. We’re going to have a deeper look at the Spring Boot REST API. Spring Boot complements the support for Spring REST by supplying the default dependencies/converters out of the box. Writing RESTful services on Spring Boot is simple with support from the Spring Boot Auto Configuration feature.

Let’s Creating Spring Boot Project boot rest API step by step

In this article, we’re going to build a Spring Boot rest example. This will be a step-by-step exercise to create a Spring Boot RESTful web service. We will create a web service using the following key features.

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

1. Build Spring Boot Project API

Let ‘s start with our Spring Boot REST example by building a Spring Boot web application. We can either use Spring Initializr or use IDE, or we can build a Spring Boot CLI application using the Spring Boot CLI.

$ spring init --dependencies=web my-project

If you want a more visual interface to the original structure:

Creation of Spring boot rest API

Modify the pom.xml file for an existing Spring Boot project. Here is how our pom.xml looks 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>

    <groupId>com.onurdeskl</groupId>
    <artifactId>rest-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>rest-example</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.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-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

There are 2 significant dependencies in the file above. Let’s take a closer look before going to the next section.

  1. spring-boot-starter-parent – This is the auto dependency management from Spring Boot. It incorporates a lot of transitive dependencies required to run the application with a minimal code.
  2. spring-boot-starter-web This adds the necessary dependencies to our web application, like Spring-MVC, Jackson, etc.

2. Introduction to Springboot REST API

REST is a short form of REpresentative State Transition. Introduced by Roy Fielding, REST is a type of architecture for distributed hypermedia systems. REST is not a standard, but think of it as a collection of limitations or principles that must be followed if we wish to refer to the interface as RESTful. When working on the REST API, the following HTTP approaches should be kept in mind:

  1. GET – To get resources
  2. POST – To build resources
  3. PUT  – To update resources
  4. DELETE – To delete resources
  5. PATCH – To update to a particular resource

3. Spring Boot REST API Controller

Let’s set up our REST controller for this exercise. Let ‘s keep the following point in mind before we start:

  1. We will use the @RestController annotation for our controller.
  2. @RestController is a convenient annotation that is annotated by @Controller and @ResponseBody.
  3. HTTP GET returns the list of clients or clients.
  4. The HTTP POST would create a client.
  5. The DELETE method excludes the user from the device
package com.onurdesk.controller;

import com.onurdesk.data.Client;
import com.onurdesk.service.ClientService;
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;

@RestController
@RequestMapping(value = "/Clients")
public class ClientController {

	@Autowired ClientService ClientService;

   
	@GetMapping
	public ResponseEntity < List < Client >> getClients() {
		List < Client > Clients = ClientService.getClients();
		return new ResponseEntity < >(Clients, HttpStatus.OK);
	}

     /**
     * Create a Client with the system.This end point accepts Client information in 
     * the json format.It will create and send back the data to the REST Client.
     */
	@PostMapping(value = "/Client")
	public ResponseEntity < Client > createClient(@RequestBody Client Client) {
		final Client ClientData = ClientService.createClient(Client);
		return new ResponseEntity < >(ClientData, HttpStatus.CREATED);
	}

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

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

There are multiple items going on in the sample of the REST controller. Let’s take a close look at these critical points:

  • The @GetMapping annotation without any mapping (first mapping in our example) maps the HTTP GET to /clients mapping (see class level).
  • @PostMapping annotation maps the HTTP POST to the /client mapping that moves the execution to the creteClient process.
  • The @PathVariable maps the {id} to the id parameter of method.

One of the key discrepancies between the web server and the REST API is the response body. REST web service does not use the template engine to render/generate HTML for viewing, directly write the returned object to the HTTP response, and the Spring HTTP message converter translates it to the JSON object. The @RestController annotation is a mixture of @Controller and @ResponseBody.

public class Client{

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

	//getter and setter
}

There are some relevant points when operating on the REST API, such as the REST API Discoverability and naming conventions, etc. But to keep this article quick, I leave it blank. Please refer to the Spring Build REST API for details.

4. Main Class of Spring Boot

Here’s the main class of our Spring Boot:

@SpringBootApplication
public class SpringBootRestExampleApplication {

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

This is the core part of our Spring Boot REST example. We need a way to let Spring know about the REST controller and other settings. The Spring Boot Autoconfiguration offers an intelligent scanning framework for our application and provides a setup to run the application with minimal code. In our case, auto-configuration detects the spring-boot-starter-web in our classpath and configures the embedded application.

The @SpringBootApplication annotation carries out the following 3 operations for us:

  1. @Configure
  2. @EnableAutoConfiguration
  3. @ComponentScan

In our scenario, the @SpringBootApplication annotation executes the following functions for us.

  • It immediately recognizes the form of our application (in our case MVC) and configures and modifies the default configuration for us, e.g. set up the dispatche servlets, search the component with the @RestController and related annotations.
  • Configure built-in tomcat for us
  • Enable spring mvc setup default.
  • Configure and enable Jackson for JSON.

5.  JPA for Accessing Data

For the completeness of this post, we will use the Spring Boot JPA capabilities to store and retrieve the client portion. I’m not going to explain this as this requires a separate article. This section is not connected to REST but is presumably part of the program layout (when operating on actual REST services).

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

//Demo for onurdesk : How to create a Spring boot rest API in 6 Steps?

@Entity
public class ClientModel {

	@Id@GeneratedValue(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 Client entities:

package com.onurdesk.dao.entity;

import org.springframework.data.repository.CrudRepository;

public interface ClientRepository extends CrudRepository<ClientModel,Long> {
}

For communicating between REST controller and Data layer using Service class :

package com.javadevjournal.service;

import com.javadevjournal.dao.entity.ClientModel;
import com.javadevjournal.dao.entity.ClientRepository;
import com.javadevjournal.data.Client;
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 ClientService {

    @Autowired ClientRepository clientRepository;

    public Client createClient(final Client client) {

        ClientModel clientModel = new ClientModel();
        BeanUtils.copyProperties(client, clientModel);
        clientModel = clientRepository.save(clientModel);
        Client clientData = new Client();
        BeanUtils.copyProperties(clientModel, clientData);

        return clientData;
    }

    public List getClients() {
        List clients = new ArrayList<>();
        clientRepository.findAll().forEach(clients::add);

        List clientList = new ArrayList<>();
        for (ClientModel clientModel : clients) {
            Client client = new Client();
            BeanUtils.copyProperties(clientModel, client);
            clientList.add(client);
        }

        return clientList;
    }

    public Client getClient(Long id) {

        Optional client = clientRepository.findById(id);
        Client clientData = new Client();
        BeanUtils.copyProperties(client.get(), clientData);
        return clientData;
    }

    public void deleteClient(Long id) {
        clientRepository.deleteById(id);
    }
}

6. Testing REST API

It’s time to see the Spring Boot REST example in motion. Create and execute the program. The best way to execute the main() function is in the SpringBootRestExampleApplication class. This is going to start the embedded tomcat. After the program is started, we will use the REST client to validate our application.

6.1 Create Client

Let’s set up clients. Open the REST client and use the REST client http://{host}:{post}/clients/client with POST

REST API Response:

{
"name": "Onurdesk",
"age": 34,
"email": "contact@onurdesk.com",
"id": 2
}

6.2 Get Client

Now that we’ve created a few clients, let’s get this list from the REST API:

REST API Response:

[
    {
        "name": "onurdesk",
        "age": 29,
        "email": "contact@onurdesk.com",
        "id": 1
    },
    {
        "name": "Team onurdesk",
        "age": 32,
        "email": "admin@onurdesk.com",
        "id": 2
    },
    {
        "name": "User 2",
        "age": 24,
        "email": "test@onurdesk.com",
        "id": 3
    }
]

6.3 Get Client By ID

{
        "name": "User 2",
        "age": 24,
        "email": "test@onurdesk.com",
        "id": 3
    }

Conclusion

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

Subscribe Today

GET EXCLUSIVE FULL ACCESS TO PREMIUM CONTENT

Get unlimited access to our EXCLUSIVE Content and our archive of subscriber stories.

Exclusive content

Latest article

More article