WebApi Field Level Response Without Implementing Odata.

Download Complete Project: WebApiFieldLevelSelection

When you are writing a RESTful web API you often want to allow clients to feed a list of fields to the API that the clients need. The reason is to return only the useful data to the client. Say for example, you have an entity called Product that has many properties. The client may need only a few properties of the Product object. If you return the entire object every time the client asks for a product.

it unnecessarily wastes bandwidth and increases the response time. So to avoid that you can accept a list of fields the client wants and return only those. How can you do that?

Odata is best way to achieve this where you can use $Select command to fetch specific database fields in response.

Problem comes when webapi not implementing odata then how can achieve this functionality ?

To achieve this you have to use some basic .net objects like dynamic,expendoObject or  generic collections etc.

Let’s resolve the problem step by step:

  1. Create empty Webapi Project with controller name as “ProductCategory” with Two Get method.one is parameter less and other with string parameter that will accept comma separated field list in request.
  2. Get() method will return all fields of database in response while Get(string fields) method accept list of fields and return desired fields in response.
  3. In below example i have use hardcoded list with dummy values.You may replace it with actual database.

    ProductCategroyController.cs

w1.png

 DynamicObject Method:

DynamicObject accept the list of fields  and return object.here I have use .net reflection to get the value of each fields and respective value to dictionary<string,object> object. later this dictionary object pass to linq query.

w2.PNG

ApiHelper.cs

w3.PNG

OUTPUT:

  1.  When user pass two fields (productid and productName) as query string in request.you can see only two fields are coming in json response.

w4

  1.  When User pass three fields (productId,ProductName,Price) as query string in request.You can see now three fields are coming with json response.

w5.PNG

So you can see how you can implement field level selection on webapi without Odata implementation.

Advertisements

3 thoughts on “WebApi Field Level Response Without Implementing Odata.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s