There are many ways to create Java REST clients such as using the built-in java.net.URL package, leveraging client API of RESTful frameworks like Jersey, Resteasy, Spring Rest, etc. In this tutorial, we’d like to show how to create a Java REST client using Spring RestTemplate.
1. Preparation
Let’s assume that we have a RESTful web service with several APIs as follows:
1.1. Get all books
1 |
GET http://localhost:8080/v1/books |
1.2. Create a new book
1 |
POST http://localhost:8080/v1/books |
Example:
1 2 3 4 |
{ "name": "Into the Water", "author": "Celeste Ng" } |
Responses: application/json
Example:
1 2 3 4 5 |
{ "id": 5 "name": "Into the Water", "author": "Celeste Ng" } |
STATUS 201 if the book is created successfully.
1.3. Update a book
1 |
PUT http://localhost:8080/v1/books/{id} |
Example:
1 2 3 4 5 |
{ "id": 5 "name": "Into the Water: A Novel", "author": "Paul Hawkins" } |
Responses: application/json
STATUS 200 if the book is updated successfully.
STATUS 400 if there is no book with given id
1.4. Delete a book
1 |
DELETE http://localhost:8080/v1/books/{id} |
STATUS 204 if the book is deleted successfully.
STATUS 400 if there is no book with given id or cannot delete the book.
1.5. Source code
The source code presented in this tutorial is available on the Github.
About the library, we’re going to use some libraries:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.6.RELEASE</version> </dependency> |
1.6. POJO
Let’s define a POJO class “Book” to map with the above JSON:
1 2 3 4 5 6 7 |
public class Book { private Long id; private String name; private String author; //getters and setters } |
2. Create A Java REST Client Using Spring RestTemplate
Let’s get to some examples of creating Java REST client using Spring RestTemplate. We’re going query, create, update and delete resources from the above REST service.
2.1. Using Spring RestTemplate to make a GET request
Firstly, let’s see how we use the Spring RestTemplate to issue an HTTP request to the first API to get all books:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Arrays; import java.util.List; import org.springframework.web.client.RestTemplate; import com.howtoprogram.domain.Book; public class BookRepositoryImplSpring { private static final String URI_BOOK = "http://localhost:8080/v1/books"; private RestTemplate restTemplate = new RestTemplate();; public Book[] getAllBooks() { Book[] books = restTemplate.getForObject(URI_BOOK, Book[].class); return books; } } |
We just need to specify the URL of the REST service and the ResponseType which is Book[].class in the example, and the Spring RestTemplate will convert the response into an array of Books.
We can test with a simple main method as below:
1 2 3 4 5 |
public static void main(String[] args) { BookRepositoryImplSpring bookRepository = new BookRepositoryImplSpring(); Book[] books = bookRepository.getAllBooks(); System.out.println(Arrays.asList(books)); } |
2.2. Using Spring RestTemplate to make a POST request
Secondly, we’re going to use the Spring RestTemplate to issue a request to the 2nd API to create a book:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import com.howtoprogram.domain.Book; public class BookRepositoryImplSpring { private static final String URI_BOOK = "http://localhost:8080/v1/books"; private RestTemplate restTemplate = new RestTemplate(); public Book createBook(Book book) { Book createdBook = restTemplate.postForObject(URI_BOOK, book, Book.class); return createdBook; } } |
We need to specify the URL of the RESTful service, the entity to be created and the ResponseType. Note that the API returns the STATUS 201 and the newly created book (includes the generated Id field) as JSON; however, we have used the postForObject method, we can not get the returned HTTP status. If we want to obtain the Http Status, we can use the postForEntity method as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class BookRepositoryImplSpring { private static final String URI_BOOK = "http://localhost:8080/v1/books"; private RestTemplate restTemplate = new RestTemplate(); public Book createBook(Book book) { // Book createdBook = restTemplate.postForObject(URI_BOOK, book, Book.class); ResponseEntity<Book> responseEntity = restTemplate.postForEntity(URI_BOOK, book, Book.class); Book createdBook = null; if (responseEntity.getStatusCode() == HttpStatus.CREATED) { createdBook = responseEntity.getBody(); } return createdBook; } } |
If the RESTful API returns a URI for the newly created object, we can use another method: postForLocation of the Spring RestTemplate.
1 |
URI uri = restTemplate.postForLocation(URI_BOOK, book); |
To test the method “createBook “, we can create a simple main method.
1 2 3 4 5 6 |
public static void main(String[] args) { Book book = new Book(null, "Effective Java", "Joshua Bloch"); BookRepositoryImplSpring bookRepository = new BookRepositoryImplSpring(); Book createdBook = bookRepository.createBook(book); System.out.println(createdBook); } |
The output console is:
1 |
Book [id=4, name=Effective Java, author=Joshua Bloch] |
Note that the response includes the new field: id=4.
2.3. Using Spring RestTemplate to make a PUT request
And next, in the following example, we’re going to use the Spring RestTemplate to update a remote resource (Book) by making a PUT request to the RESTful API:
1 2 3 4 5 6 7 8 9 |
public class BookRepositoryImplSpring { private static final String URI_BOOK = "http://localhost:8080/v1/books"; private RestTemplate restTemplate = new RestTemplate(); public void updateBook(Book book) { restTemplate.put(URI_BOOK + "/{id}", book, book.getId()); } } |
We have called the put method provided by the Spring RestTemplate class. And we can update the main method to test the updateBook method.
1 2 3 4 5 6 7 8 9 |
public static void main(String[] args) { BookRepositoryImplSpring repository = new BookRepositoryImplSpring(); // Getting the first book from the RESTful service Book book = repository.getAllBooks()[0]; // Change the name book.setName(book.getName() + " 3rd"); // Then update the book repository.updateBook(book); } |
2.4. Using Spring RestTemplate to make a DELETE request
And finally, we’re going to use the Spring RestTemplate to delete or remove a remote resource by making a DELETE request:
1 2 3 4 5 6 7 8 9 |
public class BookRepositoryImplSpring { private static final String URI_BOOK = "http://localhost:8080/v1/books"; private RestTemplate restTemplate = new RestTemplate(); public void deleteBook(Long id) { restTemplate.delete(URI_BOOK + "/{id}", id); } } |
We need to call the delete method of the Spring RestTemplate class, specify the URL and URL variables.
The main method will be updated to test as below:
1 2 3 4 5 6 7 |
public static void main(String[] args) { BookRepositoryImplSpring repository = new BookRepositoryImplSpring(); // Getting the first book from the RESTful service Book book = repository.getAllBooks()[0]; // Try to delete the book repository.deleteBook(book.getId()); } |
3. Conclusion
The tutorial has illustrated us how to create a Java REST client using Spring RestTemplate. The tutorial just only covers some very basic methods provided by Spring RestTemplate. If you want to get to know more about other methods of the RestTemplate, you can refer to Spring RestTemplate site. In near future, I will provide more examples of implementing Java REST client with other libraries, frameworks.
Below are other related tutorials:
Simple Java REST Client Using java.net.URL package(using the built-in package java.net.URL of the JDK)
Java REST Client Using Resteasy Client
Java REST Client Using Jersey Client
Java REST Client Using Resteasy Client Proxy Framework
Java REST Client Using Netflix Feign
Java REST Client Using Apache HttpClient