This tutorial is going to cover about how to develop a Java REST client example with Retrofit 2 which is a Type-safe HTTP client for Android and Java by Square.
1. Preparation
Let’s assume that we have a RESTful web service with several API as below. And we’re going to use Retrofit 2 API to create several basic Java REST client examples which will communicate with this RESTful web service.
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": "Java How To Program", "author": "Paul Deitel" } |
Responses: application/json
Example:
1 2 3 4 5 |
{ "id": 5 "name": "Java How To Program", "author": "Paul Deitel" } |
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": 1, "name": "Java How To Program 2nd", "author": "Paul Deitel" } |
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 example source code can be found on the Github.
We will use Retrofit 2 httpclient to communicate with the Rest API. Hence, we need to include Retrofit library in the build path. The Maven dependency for Retrofit is:
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>converter-gson</artifactId> <version>2.1.0</version> </dependency> |
Note that we also included gson converter library into the build path so that we can specify the GsonConverterFactory for Retrofit to use later. And both versions of Retrofit and Converter-gons are 2.1.0.
We also define a POJO to map with the Book response as below:
1 2 3 4 5 6 |
public class Book { private Long id; private String name; private String author; // All getters and setters } |
2. Java REST Client Example With Retrofit 2
In this section, we will use Retrofit 2 API to create some Java REST client examples including create a resource, update a resource, query resource and delete a resource from REST API.
2.1. Define a service interface at the client side
This interface should contain all the methods we need to call/invoke from the REST API. As mentioned above, in this tutorial, we’re going to define 4 methods for the BookResourceService as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; public interface BookResourceService { @Headers({ "Accept: application/json" }) @GET("v1/books") Call<List<Book>> getAllBooks(); @POST("v1/books") Call<Book> createBook(@Body Book book); @PUT("v1/books/{id}") Call<Book> updateBook(@Path("id") Long id, @Body Book book); @DELETE("v1/books/{id}") void deleteBook(@Path("id") Long id); } |
Let’s take a look at several methods:
1 2 3 |
@Headers({ "Accept: application/json" }) @GET("v1/books") Call<List<Book>> getAllBooks(); |
This method is used to get all books available on the server. Because the REST API requires the HTTP GET method, we simply define the annotation @GET for the interface method. We can also define the headers for the request by using annotation @Headers
Call is An invocation of a Retrofit method that sends a request to a web server and returns a response. It can be executed synchronously with execute(), or asynchronously with enqueue(Callback<T> callback)
Another method that we will take a look is:
1 2 |
@POST("v1/books") Call<Book> createBook(@Body Book book); |
Because the REST API requires HTTP POST method for creating a resource, we annotate this method by the @POST annotation. We also put the @Body annotation to the Book object that we want Retrofit to serialize it and set the result directly as request body by using Gson converter that we defined above.
2.2. Invoke methods on the interface
In this section, we are going to invoke the methods we defined on the above Java interface to communicate with the REST API.
2.2.1. Make a GET request to the REST API (Get all books)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class BookRepositoryImplRetrofit2 { private static final String URI_BOOK = "http://localhost:8080"; public List<Book> getAllBooks() throws Exception { //Create retrofit, set the API base URL and GSonConverterFactory Retrofit retrofit = new Retrofit.Builder().baseUrl(URI_BOOK) .addConverterFactory(GsonConverterFactory.create()).build(); //Create service BookResourceService bookResource = retrofit.create(BookResourceService.class); Call<List<Book>> books = bookResource.getAllBooks(); return books.execute().body(); } } |
2.2.2. Make a POST request to the REST API (create a book)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class BookRepositoryImplRetrofit2 { private static final String URI_BOOK = "http://localhost:8080"; public Book updateBook(Book book) throws Exception { Retrofit retrofit = new Retrofit.Builder().baseUrl(URI_BOOK) .addConverterFactory(GsonConverterFactory.create()).build(); BookResourceService service = retrofit.create(BookResourceService.class); return service.updateBook(book.getId(), book).execute().body(); } } |
2.2.3. Make a PUT request to the REST API (Update a book)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class BookRepositoryImplRetrofit2 { private static final String URI_BOOK = "http://localhost:8080"; public Book updateBook(Book book) throws Exception { Retrofit retrofit = new Retrofit.Builder().baseUrl(URI_BOOK) .addConverterFactory(GsonConverterFactory.create()).build(); BookResourceService service = retrofit.create(BookResourceService.class); return service.updateBook(book.getId(), book).execute().body(); } } |
2.2.4. Make a DELETE request to the REST API (delete a book)
1 2 3 4 5 6 7 8 9 10 11 12 |
public class BookRepositoryImplRetrofit2 { private static final String URI_BOOK = "http://localhost:8080"; public void deleteBook(Long id) { Retrofit retrofit = new Retrofit.Builder().baseUrl(URI_BOOK) .addConverterFactory(GsonConverterFactory.create()).build(); BookResourceService bookResource = retrofit.create(BookResourceService.class); bookResource.deleteBook(id); } } |
3. Conclusion
We have learned how to create Java REST client example with Retrofit 2, an HTTP client for Java and Android. In similar to other Rest client proxy frameworks such as Resteasy, Netflix Feign, etc. Retrofit 2 simplifies and abstracts the communication with REST API. Beside the Retrofit 2, there are a lot of approaches to creating Java REST client, you can refer to the following for more detail.
How To Post JSON With Retrofit
Java REST Client Examples Using OkHttp
Java REST Client Using Netflix Feign
Java REST Client Using Apache HttpClient
Java REST Client Using Spring RestTemplate
Java REST Client With Jersey Client
Java REST Client Using Resteasy Client
Java REST Client Using Resteasy Client Proxy Framework
Java REST Client Using Apache CXF Proxy based API