Spring Boot REST Example

Spring Boot REST Example

In this REST example we will use same project that we created earlier.To create basic project, you can follow below link.

Spring Boot Project set up



After creating project right click on package and create one class, for example RestService

Add below code

 
package com.example.preparationforinterview.FirstSpringBootPreparation;

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 RestService {	
	
	@RequestMapping(value = "/api", method = RequestMethod.GET)
	public String getMessage(@RequestParam("name") String name){
		return "Hello" + " " + name;		
	}
}

If we have RestService on separate package then we need to include @Import({ RestService.class }) in spring boot class , in our example


 
@SpringBootApplication
@Import({ RestService.class })
public class FirstSpringBootPreparationApplication {

That's all we require, now right click on FirstSpringBootPreparationApplication and run as Java Application or spring boot app

It will start embedded tomcat and you can check that your service is mapped properly



Now hit http://localhost:8080/api?name=developer.We will get below output




Download source code

Spring Boot REST Example



Visit Others Links

Spring Boot Introduction
Spring Boot Setup
REST API Example Using Spring Boot
Spring Boot REST API Test with Mock MVC Using standaloneSetup
Spring Boot REST API Test with Mock MVC Using webAppContextSetup
Spring Boot REST API Test with Embedded Server
Actuator In Spring Boot
Deployment Of Spring Boot In External Tomcat
Spring Boot with OAuth
Top Spring Boot Interview Question