1

I want to create an API for a large ASP.NET MVC application. This application uses strongly typed viewmodels for all its views. The most important job for the API will be to enable the website's functionality on other platforms such as iPhone's Objective C.

Now the idea has been from the start to reuse the ViewModels and existing controller actions for the API, in such a way that the viewmodels are returned as JSON or Ajax results by the controller instead of the view.

But there has been some discussion about this, because viewmodels have a lot of composite information that does not always seem useful for an API. For example, a typical API function could be GetRanking(). The viewmodel belonging to the Ranking() action actually has more data, such as the name of the current user and maybe some explanation about the ranking.

So the question is, what would be the best way to approach this: write separate actions for the api and return serialized domain objects, or reuse the current actions and viewmodels, and just ignore the unneeded data?

1 Answer 1

0

Or third option: create a set of service models. Long-term, the big win in making separate ViewModels tends to be the view and the entities can change independently. Services also have a few unique dimensions -- such as versioning -- that you might not need to account for elsewhere. In any case, service almost always deserves a model in and of it's own.

Now, you can often argue that the ViewModels could descend from/make use of the service models for the data transfer side of their role. Especially for updates which tends to be a bit ui agnostic.

2
  • Would you the reuse the controller actions, or create separate actions for the API?
    – Randam
    Commented Dec 16, 2010 at 20:53
  • That is a bit of a tactical decision to be honest. That said, your controllers should be simple, cheap and throwaway as the real magic should be happening in the domain layer, so I'd probably do a separate set of service controllers. Commented Dec 17, 2010 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.