What are Data Transfer Objects (DTOs) used for?

NicolasBrondinBernard

Author
@NicolasBrondinBernard

Are you exposing data through an API available on the Internet? This article should interest you!

Article published on 24/07/2023, last updated on 10/08/2026

If you're building APIs, and they're accessible from the internet, the concept of DTO (Data Transfer Object) is truly essential for securing your data!

Let's take the example of a Rest API, in which you handle user data. Let's take a very simplified data entity like this one:

public class UserEntity {
    public int id;
    public string? email;
    public string username;
    public string? password;
}

This entity, you'll surely retrieve it from a database, perform some processing if needed, and return it in your HTTP response.

You think it's secure...

Because you've been careful to never request the password or email in your SQL query, so these two fields are always empty when the client retrieves a user's profile data.

Except that one day, someone on your team modifies the query, and adds this data.

And within a few hours, the emails and passwords end up out in the wild...

The solution: DTO

DTOs are objects that represent a subset of your entities, containing only the information that is transferred between the client and the API, in order to avoid any data leaks.

Here's an example of a DTO for a User object that would be returned in a public list, for instance:

public class PublicUserDto {
    public int id;
    public string username;
}

Here, there's no risk of accidentally sending back the password, even if the database query is modified.

Before each server response, entities will be transformed into DTOs, and vice versa when receiving the request!

Here, for example, is a specific DTO to receive the data during a user's registration.

public class UserCreateDto {
    public string email;
    public string username;
    public string password;
}

As a bonus

In addition to securing data transfers, DTOs can be used to more clearly document your API's inputs/outputs, by automatically generating OpenAPI documentation, for example!

In conclusion

All the data that travels between your services and your database are entities, and everything that passes through your API's HTTP requests are DTOs (secure subsets of your entities).


Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet