RESTful API Lab 5
Steps and Files Used
- Check Customer Exists
- repository/AccountsRepository.java
- ResourceNotFoundException
- exception/ResourceNotFoundException.java
- GlobalLogicExceptionHandler
- exception/GlobalLogicExceptionHandler.java
- CustomerDto Account Info
- dto/CustomerDto.java
- Controller Read API
- controller/AccountsController.java
- fetchAccount()
- service/IAccountService.java
- service/impl/AccountServiceImpl.java
- Test in Postman
- Test using Postman
Lab#5 Implementing a READ API that fetches the details based on mobile number.
In this lab we are going to fetch the customer and account details based on the customers mobile number. We will find the customer object base on the mobile number. Then we will find the account based on the customer id. The account data is returned as part of the CustomerDto object. The case where a customer does not exist is handled with exceptions.
1. Check Customer Exists
First we need to add a check to see if customer already exists. Add the method findByCustomerId in AccountsRepository interface.
| AccountsRepository.java | |
|---|---|
1 2 3 4 5 6 7 8 9 | |
2. ResourceNotFoundException
Add a new ResourceNotFoundException the com.tus.accounts.exception package.
| ResourceNotFoundException.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
3. GlobalLogicExceptionHandler
Update GlobalLogicExceptionHandler to handle the exception and return an appropriate ErrorResponseDto.
| GlobalLogicExceptionHandler.java | |
|---|---|
25 26 27 28 29 30 31 32 33 34 35 | |
4. CustomerDto Account Info
Update the CustomerDto to add a new field to keep the account information. We could create a new Dto for the combined Customer and Account information but will leave like this for now.
| CustomerDto.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
5. Controller Read API
Add a new method to the controller class for the read API.
| AccountsController.java fetchAccountDetails() | |
|---|---|
1 2 3 4 5 6 | |
6. fetchAccount
Implement the fetchAccount method by adding to the Service Interface and the implementation class. This uses Lambda expressions to throw the exception.
| IAccountService.java | |
|---|---|
3 4 5 6 7 8 | |
| AccountServiceImpl.java fetchAccount() | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 | |
7. Test in Postman
Test the Application. Add a customer and then fetch the details as shown. Then use a different phone number and check that the 404 response with appropriate error message is found.

Figure 1. Test customer found.

Figure 2. Test customer not found.