How to consume a RESTful Web Service in Spring Boot? If you have checked spring.io, they have a guide on how to use it but unfortunately, the API is unable to access during I tried the example. Therefore, this blog post will use an alternative quote API using a similar approach.
This tutorial will build an application by using Spring’s RestTemplate to retrieve a random quote from https://api.quotable.io/random. We will use Visual Studio Code as our text editor, JDK 1.8 or later, and Maven. Please make sure Java has been setup correctly, then Extension Pack for Java and Spring Initializr Java Support extensions for VS code have been installed too (the publisher of the extensions is Microsoft).
Press Ctrl+Alt+P to run the VS Code Command Palette:
- Type Spring Initializr and then select Spring Initializr: Create a Maven Project…
- Specify Spring Boot version, normally default will do
- Specify project language: Java
- Group Id: com.example.consumingrest
- Artifact Id: ConsumingRest
- Packaging type: Jar
- Java version: 8+
- Dependencies: Spring Web
- Lastly, select a destination folder you want to project file extract to.
We will get the RESTful service by using https://api.quotable.io/random and it can be browsed using a web browser. The JSON document will look something like this:
{
"_id": "w0fjvau7GwbH",
"tags": [
"famous-quotes"
],
"content": "All is flux; nothing stays still.",
"author": "Heraclitus",
"authorSlug": "heraclitus",
"length": 33,
"dateAdded": "2019-10-12",
"dateModified": "2019-10-12"
}
We will create a domain class (src/main/java/com/example/consumingrest/Quote.java) that contains the fields for the JSON object.
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
@JsonProperty("_id")
private String _id;
@JsonProperty("content")
private String content;
@JsonProperty("author")
private String author;
@JsonProperty("authorSlug")
private String authorSlug;
@JsonProperty("length")
private int length;
@JsonProperty("tags")
private String[] tags;
public Quote() {
}
public String get_Id() {
return _id;
}
public void set_Id(String _id) {
this._id = _id;
}
public String get_Content() {
return content;
}
public void set_Content(String content) {
this.content = content;
}
public String get_Author() {
return author;
}
public void set_Author(String author) {
this.author = author;
}
public String get_AuthorSlug() {
return authorSlug;
}
public void set_AuthorSlug(String authorSlug) {
this.authorSlug = authorSlug;
}
public int get_Length() {
return length;
}
public void set_Length(int length) {
this.length = length;
}
public String[] get_Tags() {
return tags;
}
public void set_Tags(String[] tags) {
this.tags = tags;
}
@Override
public String toString() {
return "@Value {" +
"_id=" + _id +
", content=" + content +
", author=" + author +
", authorSlug=" + authorSlug +
", length=" + length +
", tags=" + tagsToString() + '\'' +
"}";
}
private String tagsToString() {
StringBuilder sb = new StringBuilder();
for (String string : tags) {
sb.append(string + ", ");
}
return sb.substring(0, sb.length() - 2);
}
}
Then, we will use a RestTemplate as a synchronized web client to perform requests to the API and it will use the Jackson JSON processing library to process the API Data.
// src/main/java/com/example/consumingrest/ConsumingRestApplication.java
package com.example.consumingrest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumingRestApplication {
// Logger to output result to console
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception { // Runs the RestTemplate
return args -> {
Quote quote = restTemplate.getForObject("https://api.quotable.io/random", Quote.class);
log.info(quote.toString());
};
}
}
Finally, just hit Run Java / Debug Java using the Run or Debug button on the top right of VS Code. Alternatively, you can use this command ./mvnw spring-boot:run to execute it without debug function.
The sample result is as below:
2022-02-13 12:07:54.979 INFO 11731 --- [ main] c.e.c.ConsumingRestApplication : No active profile set, falling back to default profiles: default
2022-02-13 12:07:57.873 INFO 11731 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-02-13 12:07:57.908 INFO 11731 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-02-13 12:07:57.909 INFO 11731 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-13 12:07:58.130 INFO 11731 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-02-13 12:07:58.131 INFO 11731 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2958 ms
2022-02-13 12:07:59.317 INFO 11731 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-02-13 12:07:59.349 INFO 11731 --- [ main] c.e.c.ConsumingRestApplication : Started ConsumingRestApplication in 5.661 seconds (JVM running for 6.724)
2022-02-13 12:08:01.327 INFO 11731 --- [ main] c.e.c.ConsumingRestApplication : @Value {_id=eDIMF-N3ATJ3, content=Let your hook always be cast; in the pool where you least expect it, there will be a fish., author=Ovid, authorSlug=ovid, length=90, tags=famous-quotes'}
Reference:
https://spring.io/guides/gs/consuming-rest/
https://github.com/lukePeavey/quotable#get-random-quote
Sample project repository:
https://github.com/sanme98/gs-consuming-rest
