'REST architecture using and organising DTO's

For developing a REST web service there are 5 basic use cases (as I see it)

/api/entities        - GET
/api/entities/{id}   - GET
/api/entities        - POST
/api/entities/{id}   - PUT
/api/entities/{id}   - DELETE

A DTO provides an optimal representation of the data needed to interact with a web service.

I like both of these concepts but where I am struggling is how to organise DTO's in relation to how they interact with a particular web service.

Should there only be one DTO per web service? Example:

EntityDto
    - Property1
    - Property2
    - Property3
    - Property4
    - Property5

Or should there be a DTO per use case? Example:

GetEntityDto 
   - Property1
   - Property2
   - Property3
   - Property4
   - Property5

AddEntityDto
   - Property2
   - Property3
   - Property4
   - Property5

EditEntityDto
   - Property4
   - Property5

The way I see it if you can only update 2 properties why send all 5?

What is the best way to deal with DTO's in relation to REST web services?



Solution 1:[1]

I guess the question I would ask myself would be: do I want to optimize my API for network bandwidth and couple it to HTTP methods or do I would want to expose my API as a simple model to allow the consumers (current and future) greater latitude in how they implement their use of the API?

Solution 2:[2]

I almost always develop DTO's as needed. It is easily done using .NET anonymous types and/or mapping utilities like AutoMapper. DTO are highly coupled with UI and you barely can optimize your development by pre designing them without knowing exactly what is your UI going to look like. The exception is the Delete in which you would inly need the ID.

Solution 3:[3]

You are correct You can create DTOs customized to the views, for instance querying a list of entities that are going to be only displayed in a list can only have a name, id, and image but the detail page might require a Dto with many more properties from the same entity. DTO's depend on your endpoints, and verbs. a POST might require you to send data that might not even be in the entity like category id in the case of one to many or many to many relationships. Often in the case of many to many relationships you will omit the links to avoid recursive/circular references too while returning data.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sixto Saez
Solution 2 Aidin
Solution 3 Pierre Huguet