#Content Negotiation in Web API?

A client might send a request with multiple media types in header

<pre class="prettyprint prettyprinted"><span class="pln">GET http</span><span class="pun">:</span><span class="com">//localhost.:21069/api/products/1 HTTP/1.1</span>
<span class="typ">Host</span><span class="pun">:</span><span class="pln"> localhost</span><span class="pun">.:</span><span class="lit">21069</span>
<span class="typ">Accept</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">json</span><span class="pun">,</span><span class="pln"> text</span><span class="pun">/</span><span class="pln">javascript</span><span class="pun">,</span> <span class="pun">*</span><span class="com">/*; q=0.01</span></pre>

Accept : Tells the server whats the client want as response.

In the above case client tells,it is comfortable with josn,xml or any type.

The server response with

<pre class="prettyprint prettyprinted"><span class="pln">HTTP</span><span class="pun">/</span><span class="lit">1.1</span> <span class="lit">200</span><span class="pln"> OK
</span><span class="typ">Content</span><span class="pun">-</span><span class="typ">Type</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">json</span><span class="pun">;</span><span class="pln"> charset</span><span class="pun">=</span><span class="pln">utf</span><span class="pun">-</span><span class="lit">8</span>
<span class="typ">Content</span><span class="pun">-</span><span class="typ">Length</span><span class="pun">:</span> <span class="lit">57</span>
<span class="typ">Connection</span><span class="pun">:</span> <span class="typ">Close</span>

<span class="pun">{</span><span class="str">"Id"</span><span class="pun">:</span><span class="lit">1</span><span class="pun">,</span><span class="str">"Name"</span><span class="pun">:</span><span class="str">"Gizmo"</span><span class="pun">,</span><span class="str">"Category"</span><span class="pun">:</span><span class="str">"Widgets"</span><span class="pun">,</span><span class="str">"Price"</span><span class="pun">:</span><span class="lit">1.99</span><span class="pun">}</span></pre>

The server makes a choice of its own of 3 types and returned the json in first place.

The process of deciding the content type between the server and client is called content -negotiation.

 

 

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s