Wednesday, July 30, 2014

Step by Step how to add a RESTful Web API to an MVC 4 Application in 10 minutes

Want to know how to add a RESTful Web API to your MVC 4 Application? Here we'll add a Web API  supporting all C.R.U.D. (Create Retrieve Update Delete) functionality, using ApiControllers. Here we use the Visual Studio 2012 Web API template for creating Controllers inheriting from the ApiController class instead of inheriting from the Controller class.
The ApiControllers are meant to return data instead of Views, serializing this data into the format requested by the client, thus providing a RESTful API.
Common Controllers can also full that requests, but you have to code much more if you want to make a RESTful application using just regular Controllers.
The API we are building will be based on the REST (REpresentational State Transfer) architecture, created by Dr. Fielding by 2000. Our API will just check the HTTP request & determine whether it intends to   :

1) CREATE an item :     HTTP "POST" request
2) RETRIEVE  an item : HTTP "GET" request
3) UPDATE  an item :    HTTP "PUT" request
4) DELETE  an item :     HTTP "DELETE" request

Asp.Net MVC 4 supports RESTful Web APIs, and helps you creating them automatically by means of a strongly typed Controller that inherits from the ApiController class.
You can create both an entire Web API MVC Application, or add a Web API to an existing MVC app.
This way, your application could serve several different web clients, including mobile, tablets, it doesn't matter the client technology because the API will return JSON or XML data to be parsed at client side.
We'll want to create such a RESTful Web API with CRUD functionality , in 10 minutes, showing the XML returned data as follows:



First, add a folder to hold the Web API controllers:
Select API Controller with read-write actions:


Tell Visual Studio which Model to use, and which Data Context:

In this example, we use the following Model:

After the ApiController is built , we have the following CRUD (Create Retrieve Update Delete) Actions in our ApiController: there are two Actions to handle HTTP GET requests:

That was to Retrieve the data. For Create a new record, the API uses the HTTP POST method:


In order to UPDATE a record, the Web API handles HTTP PUT verbs:


And to REMOVE a record, uses an HTTP DELETE verb:

Run the application. If you get the following error:

Fix it by desabling the Proxy creation at the constructor of the ApiController:


Browse again and get the required record:



That's all!! 
In this tutorial we've learn how to add a RESTful Web API to a MVC 4 Application, supporting all CRUD (Create Retrieve Update Delete) C R U D functionality.  

Happy programming.....
       By Carmel Shvartzman
כתב: כרמל שוורצמן

No comments:

Post a Comment