Saturday, February 24, 2018

Content Negotiation in Web API


What is Content Negotiation?

One of the standards of the RESTFul services is that the client should be able to decide the format of the response they want from the server. E.g. does that client want to response in JSON, xml, etc?
When a client sends a request to the server, the request holds accept header. Using this accept header the client can specify the format of the response they want from the server. E.g. if accept header is set to Accept:application/xml, then the server sends the response in xml format. If accept header is set to Accept:application/json, then the response received will be in json format.
When server sends a response in a requested format, it also sets the Content-type header to appropriate value. If the requested format is xml, server sets the Content-type to application/xml and if the requested format is json, it would be set to application/json. So, depending on the value of the accept header in request, the server sends the response. This is called Content Negotiation.
The Web API controller generates the data that we want to send to the client and hand over the data to Web API pipeline which then looks at the accept header and depending on the format specified, Web API will choose the appropriate formatter to format the data. If client has requested xml data, Web API chooses xml formatter and json formatter for json data. These formatters are nothing but classes and these are called MediaTypeFormatter.  We can also create our own custom formatter.
We can also specify multiple formatter in accept header. E.g. if I want both xml and json data, I would specify it as Accept: application/json, application/xml.

We can also specify quality factor in accept header. E.g. Accept: application/json;q=0.4, application/xml;q=0.9. In this case, xml has got higher quality factor than json. So the server sends the data in xml format.
If accept header is not specified, Web API returns the data in json format.
Depending upon the content type specified by the client, the server chooses appropriate formatter. If we set accept header to application/json, the server knows it is dealing with json data and uses appropriate formatter to convert json data to .Net type. These formatters are used by the server for both request and response messages. These formatters are called MediaTypeFormatters.

We can change the settings of these formatters to meet our application’s requirements. Let’s say we want json data to be properly indented or property names should use any particular cases, we can specify it in WebAPICofig.cs file.
Config.formatters.JsonFormatter.SerializerSettings.Formatting = NewtonSoft.Json.Formatting.Indented; 

MediaTypeFormatter is an abstract class from which all the formatters (JsonMediaTypeFromatter, XmlMediaTypeFormatter or custom formatter) are derived from.  

How to return data in a particular format from Web API service?
In WebAPIConfig.cs file’s Register method, add below line of code to return data only in Json format.
config.Formatters.Remove(config.Formatters.XmlFormatter);

This will return the data in only Json format even if accept header is set to application/xml. Similarly if we want the data to be returned in only xml format, we will do
config.Formatters.Remove(config.Formatters.JsonFormatter);

ASP.Net Web API

ASP.Net Web API is a framework which is used to build API (Http Services) on top of the .Net framework. The most common use case for using Web API is for building RESTFul services. These services can then be consumed by broad range of clients like browsers, mobile applications, desktop applications, IOTs. The term IOT stands for Internet of Things. IOTs are the objects or devices that have an IP address and can communicate over the internet with other internet enabled devices and objects. E.g. Security Systems, electronic devices like desktop, laptop, smart phones, etc. Though ASP .Net Web API is widely used to create RESTFul services, it can also be used to create services which are not RESTFul. In short, it does not dictate any architectural style for creating services.


What are RESTFul services?
REST stands for Representational State Transfer, first introduced by Roy Fielding. It is an architectural pattern for creating API that uses Http as its underlined communication mechanism. REST architectural pattern specifies set of constraints that a system should adhere to.

REST constraints: 
1.       Client Server:
Client sends a request, server send a response. This separation of concerns supports the independent evolution of client side logic and server side logic.

2.       Stateless:
The communication between the client and the server should be stateless, which means we should not be storing anything on the server related to the client between requests. The request from the client should contain all the necessary information for the server to process that request. This ensures that each request can be treated independently by the server.

3.       Cacheable:
Sub data provided by the server like list of products, list of department, does not change that often. This constraint tells the client that how long the data is good for, so the client does not have to come back to server over and over again for the same data. Caching avoids unnecessary processing and increased the performance.

4.       Uniform Interface:
It defines an interface between client and a server. To understand uniform interface, we must understand what a resource is and the Http verbs GET, POST, PUT and DELETE. In context of REST APIs, resources typically represent data entities. Product, Employee, Department, etc are all resources. The Http verb GET, PUT, POST, DELETE sent with each request tells the APIs what to do with the resource. Each resource is indentified by a specific Uri.

Let’s look at the below table.  

Resource
Verb
Outcome
/Customers
GET
Gets list of customers
/Customer/1
GET
Gets a customer with id = 1
/Customers
POST
Creates a new customer
/Customer/1
PUT
Updates a customer with id = 1
/Customer/1
DELETE
Deletes a customer with id = 1



Resource here is Customer. So typical Uri would be http://sitename/Customers. This Uri with the verb GET, is going to get us list of Customers.

http://sitename/Customer /1. This Uri with the verb GET would get us a customer with id = 1.
http://sitename/Customers. This Uri with the verb POST would create a new customer.
And you are smart enough to understand the functions of remaining verbs.

Another concept related to Uniform Interface is HATEOS (Hypermedia as the Engine of Application State). It means that in each request, there will be a set of hyperlinks that lets you know what other actions can be performed on the resource.


When to choose WCF services?
We can also use WCF service to convert into a RESTFul service but it requires a lot of configuration. The more natural choice to create a RESTFul service would be a Web API which is specifically created to create a RESTFul service. 
a.       WCF is used when you want to create a service which is transport/protocol independent. A single service with multiple endpoints. Suppose you have two clients, a java client and a .Net client. Java client wants message in XML format over Http protocol and .Net client wants binary message over tcp protocol. We can simply define two endpoints for two clients and our work is done.

b.      If you have an existing SOAP service but want to add REST to reach more clients, use WCF service.

c.       If you have limitation of using .Net framework 3.5, use WCF service.