Search code examples
javarestapi-design

Best Practices for incoming and outgoing DTOs


I'm facing an API design issue. Consider the following flow:

flow

As you can see, I have 2 classes to represent my model (SomethingDTO and SomethingResponse) and 2 classes to represent the 3rd party model (3rdPartyRequest and 3rdPartyResponse). I'm using a mapper to provide translation from the 3rdPArty model classes to my model classes.

The problem is: all these 4 classes have exactly the same attributes.

Should I repeat these attributes through all these classes? Should I have only one DTO class for the whole flow?

What is the best practice (or pattern) to solve this?

Thanks


Solution

  • As I previously answered, using DTOs helps to decouple the persistence models from the API models. So you seem to be doing the right thing.

    The problem is: all these 4 classes have exactly the same attributes.

    It's always a good idea to decouple the models of your API from the models of a third party API. If the third party API changes their contract, you won't break your clients. So use different models for each API.

    And stick to mapping frameworks, such as MapStruct, to reduce the boilerplate code. You also may want to consider Lombok to generate getters, setters, equals(), hashcode() and toString() methods for you.

    Should I repeat these attributes through all these classes? Should I have only one DTO class for the whole flow?

    If both request and response models contain the same set of fields, then you could start with a single class for representing both request and response payloads of each API. When the fields start to differ (request payload different from the response payload), then you create new models for representing each payload.

    In the long run, using distinct models for the request and response will give you flexibility, ensuring you'll expose and receive only the attributes you want to.