Why you should use a DTO to send to your API instead of the class itself

Posted by:

|

On:

|

IWhen I first started putting together the API for my dnd app, I was just using whatever model I had on the backend as the expected argument from the body.

This worked fine for basic stuff, but eventually I ran into a problem. Take a look at my location class:

In it, I say that a location can have a list of quests. I want to keep this so I can keep a record of all the quests that started in a certain location. The problem is that I don’t want to be forced to create a list of quests during location creation. I want to be able to send just the other 4 fields and still be able to create a campaign. If I just have Location set like I had my campaign set, the API wouldn’t recognize that an object without quests was a valid location object. The solution to this was to use a DTO.

A DTO, or Data Transfer Object, is basically just a class you use to define what the information that will be in transit looks like. It’s well named, it’s an Object O, that contains data D, that is used during transfer, T. Essentially, when you’re thinking about what data you want to send over from your application to your code, you are thinking of the composition of the DTO you should be using. When to use a DTO in an application to me seems straightforward: all the time that you are dealing with transfers.

Behold the location DTO:

Advantage of using a DTO

It may seem a little redundant to have a Location model in one class and then a Location DTO in another. You might think I am making more work for myself, but consider this: what if I decide I want to add a list of monsters that can be found in a location. If I kept using my location class as the API parameter, then I would have to modify how I create my locations as well, I would have to go to my angular app and modify it so that it also sends a list of monsters, or a null list of monsters field, just to get the code to work again. With DTOs, I can make modifications to my location object, and only have to worry about modifying the service method where it finally sends to the database.

DTOs are very useful tools for managing how your data send from your app to your database. Do not by shy about using them.