Spring Boot REST Example

Filed Under: Spring

Spring Boot is an awesome module from Spring Framework. Once you are used to it, then working with Spring is a breeze because it takes care of all the spring container specific configurations and allows us to focus more on our application.

REST web services are very popular these days, so in this tutorial, we will see how easily we can create a RESTful web service using Spring Boot.

Spring Boot REST Dependencies

Since web services run on the server, apart from Spring Boot we need to add Spring MVC to our project. I am using Eclipse to create my basic spring boot project, but you can also use Spring Initializr.

When we use Eclipse for creating Spring project, it actually uses Spring Initializr and configures it. Let’s get started.

Spring Boot REST Project

  1. Create new Spring Starter Project as shown in below image. Eclipse should have Spring support for this, all the latest Eclipse release has built-in Spring support.
    new spring starter project
  2. In the next popup screen, provide project basic details. I am using Maven, you can use Gradle too.

    spring boot maven project configurations

  3. Next screen asks to add dependencies apart from Spring Boot. Add “Web” dependencies and click next.
    spring boot rest maven dependencies
  4. We could have click on Finish in the earlier screen, but clicking on next provides us the Spring Initializr URL that we can use to create this project easily through the command line.
    spring initializr project url

    Here is the complete URL, you can just go to this URL in the browser and download the skeleton maven project that we have created so far.

    
    https://start.spring.io/starter.zip?name=Spring-Boot-REST&groupId=com.journaldev.spring&artifactId=Spring-Boot-REST&version=0.0.1-SNAPSHOT&description=Spring+Boot+REST+Example&packageName=com.journaldev.spring&type=maven-project&packaging=jar&javaVersion=10&language=java&bootVersion=2.0.2.RELEASE&dependencies=web
    
  5. Below image shows the contents of the auto-generated project.

    spring boot rest project

    Most important of these is SpringBootRestApplication class that is configured as Spring Boot application and contains java main method. When we run this class, it automatically runs our project as Spring Boot Web project.

    If you will check the console logs, it should print Tomcat started on port(s): 8080 (http) with context path ''.

Now that our base Spring Boot REST application is ready, it’s time to add some endpoints and business logic to it.

We will use a java bean class for sending REST web service response. Here is the code for it.


package com.journaldev.spring;

import org.springframework.stereotype.Component;

@Component
public class Person {

	private String name;

	public String getName() {
		return name;
	}

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

Spring REST Endpoints Configuration

We will create a @RestController and add some methods and annotate them with @RequestMapping. Below is our REST Controller class that exposes few GET and POST endpoints.


package com.journaldev.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonController {

	@Autowired
	private Person person;
	
	@RequestMapping("/")
	public String healthCheck() {
		return "OK";
	}
	
	@RequestMapping("/person/get")
	public Person getPerson(@RequestParam(name="name", required=false, defaultValue="Unknown") String name) {
		person.setName(name);
		return person;
	}
	
	@RequestMapping(value="/person/update", method=RequestMethod.POST)
	public Person updatePerson(@RequestParam(name="name", required=true) String name) {
		person.setName(name);
		return person;
	}
	
}

Please go through the above class properly, this is the most important part of this tutorial. It’s very easy to understand what is happening here:

  • When we annotate the controller class with @RestController, Spring Boot scans it to find the REST endpoints to configure.
  • @RequestMapping annotation on methods tells Spring to use this method as handler for any client requests. This is very important spring annotation, we can configure additional features such as HTTP methods supported, Content-Type of request, response content type etc. By default, GET method is supported and JSON response is returned.

That’s it, our Spring Boot RESTful web service is ready to run and test.

Spring Boot REST Web Service Test

When you will run the main class, check the logs for endpoints configuration.


2018-05-25 16:20:15.961  INFO 11802 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.journaldev.spring.PersonController.healthCheck()
2018-05-25 16:20:15.962  INFO 11802 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/person/get]}" onto public com.journaldev.spring.Person com.journaldev.spring.PersonController.getPerson(java.lang.String)
2018-05-25 16:20:15.962  INFO 11802 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/person/update],methods=[POST]}" onto public com.journaldev.spring.Person com.journaldev.spring.PersonController.updatePerson(java.lang.String)

All seems good, GET requests can be tested in the browser itself.

Spring Boot REST GET API

spring boot rest get

spring boot rest get parameter

I am using Postman Chrome app for testing POST requests.

Spring Boot RESTful POST Header Content Type

Spring Boot REST Post Body Response 200 JSON

Spring Boot REST JSON Request Response

JSON is the standard messaging format for REST web services, I didn’t liked that we are accepting String as POST request, let’s change our method to accept JSON request.


@RequestMapping(value="/person/update", method=RequestMethod.POST, consumes = "application/json")
	public Person updatePerson(@RequestBody Person p) {
	person.setName(p.getName());
	return person;
}

That’s it, couple of changes in method annotations and we are done. Now when you will run the main program, it will produce following output for endpoint configuration.


2018-05-25 16:31:12.613  INFO 11813 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/person/update],methods=[POST],consumes=[application/json]}" onto public com.journaldev.spring.Person com.journaldev.spring.PersonController.updatePerson(com.journaldev.spring.Person)

Below image shows the Postman settings and input for the POST method call.

Spring Boot REST Example

Summary

In this post, we learned how to use Spring Boot to create a RESTful web service. Spring Boot did all the configurations and we only had to focus on our business logic. You can download the final project from below link.

Download Spring Boot REST Project.
You can also download the project from our GitHub Repository.

Comments

  1. krish says:

    Super Explanation.. thank you very much

  2. AbiGanesh says:

    Hi,

    You have mentioned run the main class. Can you explain that please? Should I run the application class in which we mention this annotation @SpringBootApplication ? I should run that as a java application or the entire project as a spring boot application. When I try both I get 404 error in postman

    Thanks

    1. Pankaj says:

      When we say run the main class, it means the one where we have defined our main method. So in this case, SpringBootRestApplication class. You can run it as a simple java application and Spring Boot will take care of all the configuration and bindings for you.

  3. raashid khan says:

    For the updatePerson method, we didn’t specify produces param still it gives JSON response, how?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages