Search code examples
asp.net-core.net-coreasp.net-core-webapiswagger-ui

How to deal with Id property in DTO in ASP.NET Web API


Let's consider a simple UserDTO:

public record UserDTO(string Id, string Username);

It means that in Swagger UI, for the POST request, both Id and Username will be asked, but that Id won't be used. Maybe it's confusing for the client.

On the other hand, for GET requests, it could be useful.

What is the proper way to avoid this confusion?

  • use only a Username string for the POST parameter (here it's OK but could be messy with 10 properties);
  • 2 different DTOs for POST and GET (lots of redundancy);
  • other options?

Thanks.


Solution

  • Just create separate DTO for distinct endpoints.

    • POST /users accepts `CreateUserDto(..relevant properties for creation..)
    • GET /users - return List. Where UserDto(string Id, ...other properties) and so on.

    Don't be afraid of creating more types, even if there is some duplication between them. You can always derive common abstractions later.