Friday, January 3, 2014

ASP .NET Web API Basics - part 1

REST - Representational State Transfer
REST suggest use of HTTP protocol(Get, Post etc) to do any operation on server. As per REST following is the protocol we should follow these conventions with HTTP verbs-
Get - Retrieve resource
Post - Create resource
Put - Update resource
Delete - Delete resource

Here are the url example which will help us understand how to achieve different server side operations based on HTTP verbs -

Get Request -
http://mydomain.com/api/books   -- retrieve all books
http://mydomain.com/api/books/1 -- retrieve book with id 1
Similarly we can utilize the POST, PUT and DELETE operations.

WebAPI -
It is possible to achieve REST full service architecture using WCF also, but it is not that straight forward, it requires a lot of configuration. Moreover TDD point of view, it is not easy to test it.

Microsoft came up with new solution which they call it as ASP.NET WEB API, which is kind of combination of both WCF WEB API and ASP.NET MVC(conceptual idea only).
It allow you to write REST based services.
Here is the architecture placement of WEBAPI(via Microsoft site) -











Creating project
This is how you can build a sample WEB-API app -
Creating project -> VS -> new project of type MVC4 -> Select Web API

WebAPI Vs MVC -
http://softtechhelp.blogspot.in/2013/11/webapi-vs-mvc.html

Controller
WebAPI controller inherits from Apicontroller.
The function name is directly mapped with the HTTP verb. Which means if i have a controller named as Person and have Get method in it, an HTTP get request to /person will execute this method. I can have overloaded methods to handle different get methods with arguments as well.
Example -
http://mydomain.com/api/books   -- retrieve all books
http://mydomain.com/api/books/1 -- retrieve book with id 1

Routing
Similar to MVC, WebAPI also has a routing table, which defines the URL structure. By default the url structure is /api/{controller}. You can always customize it.

Response format-
By default the response of get request is an XML. But it depends on what client is requesting for. If you see in fiddler, the client sends the "Accept" tag, where it mentions the desired format of the response. If we modify it and make it text/json, the same code will respond back with the same data in JSON format.

FromBody tag -
If you see the post method in the controller, the input args has "FromBody" attribute attached to it, which is responsible for de-serializing the object sent.

No comments:

Post a Comment