Exposing domain models over API

apidomain-modellanguage-agnostic

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.

Best Answer

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.

Related Topic