-->

14/07/2012

ASP.NET WEB API Basics (MVC 4)


In earlier post we read about how WEB API evolved and what are the features that made it as one of the best frameworks to build or consume HTTP Services.

While going through the post, keep one thing in mind that WEB API is REST Complaint, so it typically consists of Get(),Put(),Post(),Delete() methods.
           Method                                        URL Structure
             Get()                                            api/Values
             GetItem(int i)                              api/Values/i
             Post (i)                                         api/Values/i with Post method
             Delete(i)                                      api/Values/i with Delete method.

Before writing tons of your custom code, lets see what the default scaffold template has given for a WEB API interface.

Step 1: Create a solution and a MVC 4 project. I named it as API_SVC, as i am planning to build a HTTP Service which can act like a business layer for my front end web app.
Step 2: Once you select the project type, now you need to choose the template for your project. There are several templates available. "Mobile" and "WEB API" are the 2 new templates we see in MVC 4.
Currently lets stick to Web Api with Razor engine.
 Step 3: Application is created and basic code is added by Scaffold. Go to Controllers and you will see a new controller with name "ValuesController". Open the file and see. You can find 5 methods called Get(), Get(xxxxx), Post(xxxx), Put(xxxx),Delete(xxxxxx).
  
public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post(string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
Observer the comment provided on top of each method. It is the way how to access that specific method using api interface.

Step 4:We need to test every method of the WEB API service to get better understanding. Unlike GET, its not easy to test Post, Put and Delete methods from browser. For this we will use "Fiddler tool".

Step 5 : Download Fiddler 2 and install it. Open it. This is how it will look like.

Step 6: Lets just modify the methods to have better test data. after modifications, this is how API Service will look like.
public class ValuesController : ApiController
    {
        private List list = new List{"Item1","Item2","Item3","Item4","Item5"};

        // GET api/values
        public IEnumerable GetList()
        {
            return list; 
        }

        // GET api/values/5
        public string GetItem(int id)
        {
            return list.Find(i => i.ToString().Contains(id.ToString()));
        }

        // POST api/values
        public List Post(string value)
        {
            list.Add(value);
            return list;
        }

        // PUT api/values/5
        public void Put(int id, string value)
        {

        }

        // DELETE api/values/5
        public List<string> DeleteItem(int id)
        {
            list.Remove(list.Find((i => i.ToString().Contains(id.ToString()))));
            return list;
        }
    }
Simple modifications.
1. GetList() - Brings all items in list.
2. GetItem(i) - Bring item from list having integer "i" in it.
3. Post(str) - Will add str to list and will display complete list to demonstrate the result.
4. Delete(i) - Will delete item from list having integer i in it,and will display complete list to demonstrate the result.

Step 7: I hosted my API Service at "http://localhost:8080/API_SVC/". so if i need to hit #1 method, open fiddler, go to "Composer" tab and enter url "http://localhost:8080/API_SVC/api/Values". Select method as "GET"
Action:

Result:

Step 8: Now enter url "http://localhost:8080/API_SVC/api/Values/1" and select GET to hit #2 method on top.
Action:
Result:
Step 9: Now enter url "http://localhost:8080/API_SVC/api/Values" and select POST to hit #3 method on top.

Step 10: Enter "http://localhost:8080/API_SVC/api/Values/1" and select DELETE to hit #4 method.
Action:
Result:

With this we have covered the basics of ASP.NET WEB API and the process of executing various methods of it.

Next post we will see Implementing / Consuming of a Custom WEB API service.

Is it helpful for you? Kindly let me know your comments / Questions.

No comments:

Post a Comment