In Part 1 we developed Http Client with Apache Http Components:

HttpClient.java

So now we can create a higher level Service Client for our REST API (Book Service).

To do that we should create response classes for each type of responses:

Http Request and Http Response

Response class: contains only response code and response phrase. It doesn’t contain any payload. This is applicable for DELETE http requests

BookResponse class: extends Response and contains a Book as a payload. This is applicable for POST, PUT and one of GET requests (get by id)

BooksResponse class: extends Response and contains List<Book> as a payload. This is applicable for the second GET (get books for the author)

Response.java, ResponseStatus.java, BookResponse.java and BooksResponse.java

REST API Client

Now we have everything that we need to create Service level REST API Client

We set bookService.url in application.properties

bookService.url=http://lenar.herokuapp.com/books

Read more about application.properties and how to get parameters from application.properties

Service Client usage

To start using the client we have to autowire it like this

@Autowired
BookServiceClient client;

Let’s try the scenario that we used in Part 1:

  • 1. Call POST to create a book.
  • 2. Call GET to get all books.
  • 3. Call UPDATE to update an existing book.
  • 4. Call GET to get a book by id
  • 5. Call DELETE to delete a book.

Service Client in TestNG tests with Spring Boot

See the difference between this and HttpClient that we created in Part 1. Looks much more readable without low level code almost only business logic.

All you need now is to add your assertions to verify responses

I intentionally didn’t include any assertion - this is out of scope of the post


You may also find these posts interesting: