Question

I'm building a simple RESTful API for a web-based application I'm working on, and I'm wondering about the best way to go about exposing my domain models.

Let's say I have a User class and I want to provide a JSON response with the various user properties. I obviously don't want to publicly expose every property of my model (things such as DateCreated, PasswordHash etc) due to security and bandwidth issues.

I've read into Data Transfer Objects and I'm wondering if this is the way to go. If I'm right I could pass, for example, a User model to my User DTO and ensure said DTO only allows exposure of the User properties I choose (which would also help decouple my models from my public API).

Is this solution appropriate or are there better ways to go about this?

Thanks.

Was it helpful?

Solution

That's exactly one of the reasons why DTOs exists.

The tradeoff here is that adding DTOs makes your implementation a bit more complex, and thus prone to errors - such as a mismatch in mapping the domain object to a DTO. Use unit tests for this!

Another thing that you could do with your DTO and tends to be highly overlooked in RESTful services is treating hypertext data for references, nested objects and possible operations.

Refer to Martin Fowler's PoEAA: "[...] it's worth mentioning that another advantage is to encapsulate the serialization mechanism for transferring data over the wire. By encapsulating the serialization like this, the DTOs keep this logic out of the rest of the code and also provide a clear point to change serialization should you wish."

http://martinfowler.com/eaaCatalog/dataTransferObject.html

TL;DR: I like the idea of separating the concerns of domain logic and "RESTful wiring" through DTOS, albeit introducing a more complex design.

OTHER TIPS

Though it is not the primary intent of Data Transfer Objects, DTOs can be used to satisfy this concern in a similar manner to the data portion of a Presentation Model.

As it has been pointed out, this may bloat your design and something as simple as an added field may require changes to bubble up through the additional layers. Because of this, it is advisable to see if you can provide metadata to describe the serialization of the object. In many languages, this takes the form of specialized annotations that can be applied to your domain objects to avoid the tedious translation to DTOs. Packages like Jackson (through the use of Mixins) often take this idea a bit farther to completely separate your metadata from your domain model.

Licensed under: CC-BY-SA with attribution
scroll top