C# – Is creating ViewModels in Web API a bad practice

apicrestweb-apiweb-development

So, somebody at work who is twice as experienced than I am, told us that we must not create ViewModel classes within Web API. (We are using Angular for UI)

In his opinion ViewModel is ASP.NET MVC approach. And we must come out of it when using Web API.

Here is my argument for using ViewModel in WebAPIs:

Database Tables

Employee

name | phone | categoryId |...Col15

Category

categoryId | Description

C# Class

Class Employee
{
 public string name {get;set;}
 public phone {get;set;}
 public categoryId {get;set;}
 //...till col15
}

If your UI page shows only :

 name | phone | categoryId | CategoryDescription

Wouldn't it make sense to create a ViewModel class in API that has only these 4 properties as opposed to all 15 properties?
The JSON that will be returned by this class will only have 4 properties instead of 15 properties where 11 of them contain null value.

If there is a list of say 100 Employees it would mean 1100 empty json properties that will be sent to the UI if we use original Employee class instead of a ViewModel class.

Also, if we stick to our original Employee class we might have to do one of the following:

  1. CategoryDescription must be added to original Employee class
  2. Make a second API call from UI to get the description.

Best Answer

What you are doing is fine. You should expose only the data which is necessary for the clients.

Just don't call it "view models" since this term have a specific meaning in the context of user interfaces and will create confusion when used outside of this context. Call it "Data Transfer Objects" and everyone will be happy.

It is not a good idea to expose entities directly through an API. This creates a tight coupling which means any minor change in the business logic will cause breaking changes in the API (and vice versa). You want to avoid that.

Related Topic