Why you should use DTOs in your REST API

Cassio Mazzochi Molin |

DTO stands for Data Transfer Object.

This pattern was created with a very well defined purpose: transfer data to remote interfaces, just like web services. This pattern fits very well in a REST API and DTOs will give you more flexibility in the long run. And your REST resources representations don’t need to have the same attributes as the persistence objects.

Just to mention a few benefits:

  • DTOs can be tailored to your needs and they are great when exposing only a set of attributes of your persistence entities. You won’t need annotations such as @XmlTransient and @JsonIgnore to avoid the serialization of some attributes.
  • By using DTOs, you will avoid a hell of annotations in your persistence entities, that is, your persistence entities won’t be bloated with non persistence related annotations;
  • You will have full control over the attributes you are receiving when creating or updating a resource;
  • If you are using Swagger, you can use @ApiModel and @ApiModelProperty annotations to document your API models without messing your persistence entities;
  • You can have different DTOs for each version of your API;
  • You’ll have more flexibility when mapping relationships;
  • You can have different DTOs for different media types;
  • Your DTOs can have a list of links for HATEOAS. That’s the kind of thing that shouldn’t be added to persistence objects.

Mapping frameworks

You won’t need to map your persistence entities to DTOs and vice versa mannually. There are many mapping frameworks you can use to do it. For instance, have a look at MapStruct, which is annotation based and works as a Maven Annotation Processor. It also works in CDI and Spring-based applications.