Sharing the things I learn day by day

Wednesday, December 25, 2013

INTRODUCTION TO WEB API (PART 1)

Hi All,

This blog post will demonstrate on how to create a RESTful web service using Web API, which is introduced by Microsoft with the MVC 4 release. 


I’m using Visual Studio 2012 for this demonstration.


First I will create a New Project and I will select a MVC 4 Web Application. I name it as WebAPIDemo.



Next you will be prompted to select the template, and you can see that there is a template for Web API as well. This template will give you a class in which the HTTP methods are implemented which can run and test immediately. It will also provide a MVC web application which can be used to test your Web API.

But for this demonstration I will not be using the Web API template. I will use the Basic template. I will not be testing the Web API using a MVC application. I will show you some tools available in which RESTful services can be tested.




Web API works on the MVC principle. The way how to invoke a method in the Web API is the same as in MVC.

So next I will create a controller and will name at as StudentController. From the template I will select “Empty API Controller”.




All Web API controller classes extend from the ApiController class. In StudentController, I will write four methods to Insert, Update, Search and Delete to represent the CRUD oprations.


CRUD Operation
Method Name
Insert
InsertStudentDetails
Delete
DeleteStudentDetails
Update
UpdateStudentDetails
Select
SelectStudentDetails
GetAllStudents

I will create a class called Student which has four attributes. Place the Student class inside the Models folder.


The content of the class is shown below.


Now let’s implement the four methods. Since I’m not going to use a database to store and retrieve values, I will hardcode student details in a list and use it. The list is as below.


The tool I’m going to use to test the API is “RESTClient” Download. This is a tool for Firefox. If you are using chrome then you can use “Postman” Download. You can just run the application and test it in these tools.



First I will implement the GetAllStudents method which returns all the students in the list.




[HttpGet] attribute indicates to the Web API that this is a HTTP GET method. So below is the result after invoking the method.

Request URL: http://localhost:3625/api/Student/GetAllStudents

Note: You need to change the port number accordingly when you try this out in your machine.


Request:






Response:

The response contains the three student details I hardcoded in the list.

Next I will implement the SelectStudentDetails method which accepts the studentID as the parameter.




Request URL: http://localhost:3625/api/Student/SelectStudentDetails?studentID=1

Here when invoking the method the studentID is passed.

Response:














For rest of the demo please read INTRODUCTION TO WEB API (PART 2)

No comments: