One of most important and basic operations in Java Backend is Consuming Rest api. In this blog I use REST Template to demonstrate the task.
GET Method
You have to create 2 projects, from one demo we use other's get endpoint.
For 1st Project, which only has the name[Your name].
-
You have to add spring-web dependency for web services.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webmvc</artifactId> </dependency>
java Create a MainController class in the controller package.
Add
@RestControllerannotation to make it RESTful web services and instruct it to return the data instead of view.Add a Get endpoint return your name.
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MainController {
@GetMapping("/name")
public String myName() {
return "Ayush Singh";
}
}
- Add a variable in
application.propertiesto change the server port,server.port = 9090.
For 2nd Project, do the same for dependencies and controller.
- Create a Rest Template bean OR initialize it in the MainController class.
private RestTemplate rest; public MainController() { rest = new RestTemplate(); }java - Create a
hello()method for showing the greeting and annotate it with@GetMapping("/hello") - In the
application.propertiescreate a variable to store the url likename.service.url = http://localhost:9090. This will be the url from where we fetch the name of the user. -
Add a field in the MainController name
baseUrlto inject the value of the url of another server.
@Value("${name.service.url}") private String baseUrl; Create a full URI by adding base url and resource name.
-
Now implement the
getForObject()method to get the data from the another server.
String response = rest.getForObject(url, String.class);-
urlis the full url. -
String.classis the response type.
-
-
At last return the response variable add with
Hello.
return "Hello " + response;
Top comments (0)