In this post under Spring RestTemplate, I will show with example the purpose and how to use path parameter.
If we have to make a call to get the “Post” data with id 1 from “http://jsonplaceholder.typicode.com”. Our url will be
http://jsonplaceholder.typicode.com/posts/1
Now if I have to make a call to get the “Post” data with id 2, we need to change the above url as shown below
http://jsonplaceholder.typicode.com/posts/2
where “1” is replaced by “2”.
Instead of modifying the url by changing the id whenever we need “Post” data of different id. We can create a template as shown below
http://jsonplaceholder.typicode.com/posts/{id}
where the text “id” within “{” and “}” is called path parameter. It is replaced by actual value or id at runtime.
Spring RestTemplate provides this functionality. It lets you create url template with path parameter, which is then replaced by actual value at runtime.
Below is the main class showing its usage.
Main class
package package2;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
public class Example2 {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://jsonplaceholder.typicode.com/posts/{id}";
HashMap<String, Integer> pathVariables = new HashMap<>(0);
pathVariables.put("id", 1);
Post post = restTemplate.getForObject(url, Post.class, pathVariables);
System.out.println(post);
}
}
In the above code, at line 9 I create an instance of “RestTemplate” class.
At line 10, I define a url template.
At line 11, I create a “Map” instance. This map will have the path parameter name as key and the actual value as map value.
At line 13, I call the “getForObject” method passing 3 arguments which are
1) the url template
2) Class type of the response body
3) the map which contains path parameter name and actual value.
This method returns a “Post” object with id 1 which is printed in the console.
Below is the structure of “Post” class for your reference
Post class
package package3;
public class Post {
private int id;
private String title;
private String body;
private int userId;
//Removed getter and setter for brevity
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(id).append(":");
stringBuilder.append(title).append(":");
stringBuilder.append(body).append(":");
stringBuilder.append(userId);
return stringBuilder.toString();
}
}
In this way we can use the path parameter.