Consuming a RESTful Web Service
This guide walks you through the process of creating an application that consumes a RESTful web service.
What You Will Build
You will build an application that uses Spring’s
RestTemplate
to retrieve a random Spring Boot quotation at
http://localhost:8080/api/random
.
Java 17 or later
You can also import the code straight into your IDE:
Like most Spring Getting Started guides , you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
To start from scratch , move on to Starting with Spring Initializr .
To skip the basics , do the following:
Download
and unzip the source repository for this guide, or clone it using
Git
:
git clone
https://github.com/spring-guides/gs-consuming-rest.git
cd into
gs-consuming-rest/initial
Jump ahead to Fetching a REST Resource .
When you finish
, you can check your results against the code in
gs-consuming-rest/complete
.
You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
To manually initialize the project:
Navigate to https://start.spring.io . This service pulls in all the dependencies you need for an application and does most of the setup for you.
Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
Click Dependencies and select Spring Web .
Click Generate .
Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
With project setup complete, you can create a simple application that consumes a RESTful service.
Before you can do so, you need a source of REST resources. We have provided an example of such a service at https://github.com/spring-guides/quoters . You can run that application in a separate terminal and access the result at http://localhost:8080/api/random . That address randomly fetches a quotation about Spring Boot and returns it as a JSON document. Other valid addresses include http://localhost:8080/api/ (for all the quotations) and http://localhost:8080/api/1 (for the first quotation), http://localhost:8080/api/2 (for the second quotation), and so on (up to 10 at present).
If you request that URL through a web browser or curl, you receive a JSON document that looks something like this:
That is easy enough but not terribly useful when fetched through a browser or through curl.
A more useful way to consume a REST web service is programmatically. To help you with that task, Spring provides a convenient template class called
RestTemplate
.
RestTemplate
makes interacting with most RESTful services a one-line incantation. And it can even bind that data to custom domain types.
First, you need to create a domain class to contain the data that you need. The following listing shows the
Quote
record class, which you can use as your domain class:
src/main/java/com/example/consumingrest/Quote.java
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record Quote(String type, Value value) { }
This simple Java record class is annotated with
@JsonIgnoreProperties
from the Jackson JSON processing library to indicate that any properties not bound in this type should be ignored.
To directly bind your data to your custom types, you need to specify the variable name to be exactly the same as the key in the JSON document returned from the API. In case your variable name and key in JSON doc do not match, you can use
@JsonProperty
annotation to specify the exact key of the JSON document. (This example matches each variable name to a JSON key, so you do not need that annotation here.)
You also need an additional class, to embed the inner quotation itself. The
Value
record class fills that need and is shown in the following listing (at
src/main/java/com/example/consumingrest/Value.java
):
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record Value(Long id, String quote) { }
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumingRestApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
A logger, to send output to the log (the console, in this example).
A
RestTemplate
, which uses the Jackson JSON processing library to process the incoming data.
A
CommandLineRunner
that runs the
RestTemplate
(and, consequently, fetches our quotation) on startup.
The following listing shows the finished
ConsumingRestApplication
class (at
src/main/java/com/example/consumingrest/ConsumingRestApplication.java
):
You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you use Gradle, you can run the application by using
./gradlew bootRun
. Alternatively, you can build the JAR file by using
./gradlew build
and then run the JAR file, as follows:
Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote]
, it is possible that you are in an environment that cannot connect to the backend service (which sends JSON if you can reach it). Maybe you are behind a corporate proxy. Try setting the
http.proxyHost
and
http.proxyPort
system properties to values appropriate for your environment.
Want to write a new guide or contribute to an existing one? Check out our contribution guidelines .