In this post under JAX-RS Client I will show with example how to use URL template to make rest api calls.
But first what is URL template. A URL template is a template with placeholders. At runtime these placeholders are replaced with actual data forming the actual url to be requested.
The placeholders are placed between “{” and “}”. At runtime placeholders including “{” and “}” are replaced by actual values.
For our example, in our previous post we used query parameters to request user information with id 1 from “https://jsonplaceholder.typicode.com”
WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users");
webTarget = webTarget.queryParam("id", "1");
In this example also, we will do the same thing but instead of sending query parameters containing user id, we will use url template.
Below is url template
https://jsonplaceholder.typicode.com/users/{userId}
I will be requesting for user information with id 1. So at the runtime “{userid}” will be replaced by 1 and the url will be
https://jsonplaceholder.typicode.com/users/1
Below is the complete code for your reference
Main class
1 package defaultPackage;
2
3 import jakarta.ws.rs.client.Client;
4 import jakarta.ws.rs.client.ClientBuilder;
5 import jakarta.ws.rs.client.Invocation;
6 import jakarta.ws.rs.client.WebTarget;
7 import jakarta.ws.rs.core.Response;
8
9 public class Example7 {
10 public static void main(String[] args) {
11 Client client = ClientBuilder.newClient();
12 WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users/{userId}");
13 webTarget = webTarget.resolveTemplate("userId", 1);
14 Invocation.Builder builder = webTarget.request();
15 Invocation invocation = builder.buildGet();
16 Response response = invocation.invoke();
17 if(response.getStatus() == 200) {
18 System.out.println("Successful");
19 String result = response.readEntity(String.class);
20 System.out.println(result);
21 } else {
22 System.out.println("Failed");
23 }
24 client.close();
25 }
26 }
In the above code, at line 12 we create an instance of WebTarget by using the url template.
At line 13, we are telling JAX-RS client to replace the template parameter “userId” with 1 at runtime.
Then we request the server with the url created at runtime, get the response and based on the response we display the output.
In this way we can make any type of request using url templates.
Below is the output for our code
Output
Successful
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}