2

I've seen this that suggest I can build different views based on user: different json views for the same entity

However in asp web api, one uses a Model class, I can't just add new properties willy-nilly.

So, for example I may have uri:

http://host/api/products/id

Returning the model:

public class Product{
   public string Code { get; set; }
   public string Description { get; set; }
}

But for another purpose I want to add more information, suppose this is expensive because it joins other data to build the model, or formats the data in a very specific way:

http://host/api/productsspecial/id

Returning the model:

public class ProductSpecial{
   public string Code { get; set; }
   public string Description { get; set; }
   public decimal Price { get; set; } //assume expensive to look up
}

So obviously I have a way to do this, two different controllers, returning different views on the data. My question is, is this OK or is there a better way?

Anyway I could do this for example: http://host/api/products/id?includeprice=true and use that to return the alternative model? And is that a good idea?

Community
  • 1
  • 1
user2586804
  • 321
  • 1
  • 10

1 Answers1

1

I would suggest

GET /host/api/products/{id}?fields=code,description,price

You should avoid complicating your resource URL in the manner you describe. Every possible configuration of values would need a new name: "productsReallySpecial", etc.

The problem with ?includePrice=true is you then have a parameter for every variable you might want to make optional. Your documentation can list the default return values and the available return values.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52
  • Thanks, and how would I achieve filtering when I'm not building this response using a json writer of any sort, I just have model classes that are automatically serialised? – user2586804 Sep 13 '13 at 13:57
  • Well, you'd either have to use a JSON writer, or you'd need a model class with all the properties, and you only populate the ones the user requests. Then you're saving the effort of the expensive work, and serialization will do the Right Thing. – Eric Stein Sep 13 '13 at 14:02
  • "do the right thing"? meaning it will exclude `null` properties? My example is a `decimal` anyway, but I guess I can use `decimal?` anyway – user2586804 Sep 13 '13 at 14:22
  • I'm not 100% sure how it will serialize - whether it will exclude the property entirely or have a property name but no value. I believe it will exclude the property entirely. It should be pretty easy to try it and see what happens. – Eric Stein Sep 13 '13 at 17:30
  • Thanks, I am able to control the formatting of the json serializer to ignore `null`s using techinque here: http://stackoverflow.com/questions/12629144/how-to-force-asp-net-web-api-to-always-return-json – user2586804 Sep 18 '13 at 15:05