Restful Web services with Spring boot Simple Example

Restful Web services with Spring boot Simple Example

This post is aimed to give understanding about web service with spring (through spring boot) for beginners.

 

Steps to Create a simple restful web service:

1. Create a normal class and add @RestController annotation.

[java]
@RestController
public class GreetingController{
}
[/java]

 

2. Create a method and add @RequestMapping(“/greeting”) annotation.

Here /greeting refers the url endpoint to be used to hit and get the response from this method.

[java]
@RestController
public class GreetingController {

private static final String template = “Hello, %s!”;
private final AtomicLong counter = new AtomicLong();

@RequestMapping(“/greeting”)
public Greeting greeting(@RequestParam(value=”name”, defaultValue=”World”) String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
[/java]

 

 

3. In the method argument you can see @RequestParam annotation is used:

which basically helps to get the input from url/from the client.

In this case by default it prints

{“id”:26,”content”:”Hello, World!”}

If you enter /greeting?name=javadomain then you get

{“id”:26,”content”:”Hello, javadomain!”}

 

id is changing everytime because of the java concurrent package incrementAndGet() method. This is purely nothing to deal with restful web service. so don’t get confused.

 

 

4. Note, no request methods are defined, so it works for “GET”

I understand that, it will even works for post methods because spring internally adds all the methods for the url endpoints when no request method is mentioned.

If you like to specify the method then you have to put

@RequestMapping(method=”post”, value=”/greeting”)

 

 

5. Now run your spring boot application and enter the below endpoint urls

http://localhost:8080/greeting?name=javadomain

Returns,
{“id”:26,”content”:”Hello, javadomain!”}

 

http://localhost:8080/greeting
Returns,
{“id”:27,”content”:”Hello, World!”}

 

Output:

Restful Web services with Spring boot Simple Example

 

Restful Web services with Spring boot Simple Example

 

I have taken the sample restful web service project from github

 

This is a restful web services spring boot maven application, which you can directly import, build through maven / gradle and run.

 

 

Leave a Reply