Monday, July 21, 2014

Partial Responses in WCF REST API

One of the nice to have feature in any REST API is partial responses. With the help of partial responses, we can request only those fields which are required as part of response.  By only requesting information that it will actually use, a client application can more efficiently use network, CPU and memory resources. By contrast, an application that retrieves a full API feed, parses it and then drops unused fields is likely to waste some resources along the way.

An example of partial response is Youtube API.

WCF framework can be used to build REST APIs which by default does not support partial responses. However, we can easily write extension in WCF services to manipulate the response message and send only partial response. One such extension is available @ https://github.com/nishantagarwal/Snippets/tree/master/PartialFields

This extension takes the fields parameter from the query string of requested URL and accordingly sends the required fields in the response. The fields parameter limits the data fields that are returned for the feed or for specific entries in the feed. It is case insensitive.

Following are the templates for fields parameter:


  • Immediate fields of an object – To select the immediate children nodes of an object, specify the required field names separated by comma.
    E.g.: recipeId,recipeName,photoUrl,SEOPageName
  • Fields of a nested object – To select fields of a nested object, specify the name of the nested object followed by comma separated list of fields enclosed in parentheses.
    E.g.: recipeId,recipeName,Tip(TipName)
  • Fields of a collection item – To select certain set of fields of all items in a collection, specify the name of the collection and a colon (:) followed by comma separated list of fields enclosed in parentheses. E.g.: recipeId,recipeName,Ingredients:(IngredientId,IngredientName)
Note: If the start node of service response is a collection then that particular collection name and colon should not be specified in fields parameter.

This is a WCF extension and can be easily integrated to any existing WCF service using web.config.
In web.config, add a new behavior extension and then use it the required endpoint behavior.

E.g.:

<configuration>
  <system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <!-- Declare Extension -->
        <add name="partialResponse" type="PartialFields.PartialResponseProcessor, PartialFields" />
      </behaviorExtensions>
    </extensions>
<behaviors> <endpointBehaviors> <behavior name="webby"> <!-- Use extension --> <partialResponse /> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> </configuration>

No comments:

Post a Comment