Creating a REST service in SpringBoot

gautham
Eat-Sleep-Code-Repeat
3 min readSep 4, 2020

In my last post running your first spring boot project, i had shown on how can we create a spring boot project using Spring Initializr and import that into our eclipse workspace. When we executed the application, the localhost:8080 url was responding us with a white label error. Now in this post, we will create a working REST Service and we will invoke a GET method.

Creating GET method

Lets start with creating a Controller class within our package.

  • Lets Right click the package → New → Class ( as shown below )
  • Lets enter the name the class “SpringBootDemoController” in the window and click Finish
  • Now we have an empty SpringBootDemoController.java file.

The powerful part of spring boot are the annotations. Annotations help us autowire or instruct the class or methods to behave in the ways we want. Since in this controller will be defining and hosting the REST methods, we need to assign the annotation @RestController to the class.We might have to import the dependencies needed from org.springframework.web as shown below.

import org.springframework.web.bind.annotation.RestController;@RestController
public class SpringBootDemoController {
}

The details are shown on the below images.

  • Now lets define a simple Hello world method which returns a String object
public String helloWorld() {
return “My First Spring Boot Service”;
}

Now lets expose this method as a GET service by adding a @GetMapping annotation on the helloworld method. This GetMapping annotation takes a path parameter where you can define the method URL which will be invoked from the client calling this service. We need to import the dependencies for GetMapping also as shown below.

For our service i have given the url as @GetMapping(“/demo/helloworld”). the class file now looks as below

package com.springboot.demo.webservices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpringBootDemoController {
@GetMapping(“/demo/helloworld”)
public String helloWorld() {
return “My First Spring Boot Service”;
}
}

Now save the class and run the Spring boot application as a Java Application from your eclipse and once the application is started , go to the browser and load the URL http://localhost:8080/demo/helloworld which should return the String that you returned from your GET method

The URL is created as below http://<Host>:<port>/urlpath

Congratulations, you created your first REST Service with GET Method in SpringBoot.

--

--

gautham
Eat-Sleep-Code-Repeat

Avid Reader || Blogger || Tech Enthusiast || Working as an Engineering Manager at Atlassian