Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do partial responses using ASP.Net Web Api 2

I'm really new to API design and MVC concepts, but as far as I can tell, something like GET /api/products should return a list of products and GET /api/products/1 should return a single product. In terms of speed my feeling is that /api/products should return less information i.e. just id and name, whereas /api/products/1 should return more i.e. id, name, and description.

As far as I can see, the best way to handle this is to make certain fields of the product class not be returned in the /api/products endpoint. This is especially necessary in the case of /api/products?fields=name . I'm using ASP.Net Web Api 2 and have tried the following:

  • http://www.nuget.org/packages/WebApi.PartialResponse/ - installing this package caused an assembly version error.
  • Adding ShouldSerialize methods on the Product fields. For reasons I won't go into here, this method is a little cumbersome.
  • Looked at ASP.NET Web API partial response Json serialization but there doesn't seem to be a conclusive answer there.
  • ASP.NET WebApi and Partial Responses suggests using a product class with all nullable fields. I'm not sure I understand exactly what to do there.

Is there any simple way to do what I'm trying to do?

Otherwise could you suggest a better API design than what I'm doing?

like image 773
quijames Avatar asked Nov 18 '13 22:11

quijames


1 Answers

You could also use WebApi.PartialResponse (http://www.nuget.org/packages/WebApi.PartialResponse/). It's a package I wrote which uses LINQ to JSON (Json.NET) to manipulate the returned objects. It uses the fields syntax used by Google in their API's, eg.:

  • fields=items/id,playlistItems/snippet/title,playlistItems/snippet/position
  • fields=items(id,snippet/title,snippet/position)
  • fields=items(id,snippet(title,position))

You can find more information on the GitHub project page: https://github.com/dotarj/PartialResponse.

like image 52
dotarj Avatar answered Sep 28 '22 07:09

dotarj