0

I am consuming an external/third party api and I have created an endpoint in my SpringBoot application that currently returns its response via Spring REST API (RestTemplate). My ultimate goal is to re-structure the response and to do so I created both entity and a new Dto with the expected format.

I am not really sure when it comes to the right approach to convert the existing third party api response to a custom one. Can you advise on it? Shall I write a dto to dto converter? Is there any example I can follow? Would such conversion be part of a service? Any advice is much appreciated.

Thank you

panza
  • 1,341
  • 7
  • 38
  • 68

1 Answers1

0

The answer is: it depends

It depends on what you want to return and what returns your 3rd party site. Let's assume both are jsons so best approach is to create two dtos. Mapping depends on how do you want to process that data.

There are couple of mapping libraries, you can use one of those (read here)

If you don't want to use mapping libraries you can think about writing builders for dtos and you can write your own Mapper util class:

public Mapper {

public static SecondDto mapDto(FirstDto firstDto) {
    return SecondDto
            .firstParam(firstDto.getFirstParam())
            .secondParam(firstDto.getSecondParam())
            .build();
}

}

Krzysztof K
  • 736
  • 4
  • 19
  • Thank you, this is of great help indeed. Just an additional question, I would need to collect any error that might arise when converting from a format to another (there are not only structural changes, but also data type ones), I guess this approach would work also for brand new fields such as an Error Dto. Is that a correct assumption? – panza Mar 15 '21 at 22:16