Building a Simple Web API

In this article we are going to create a simple Web API, that basically exposes an in-memory List<Student> over HTTP, for a client application to play with the list members.

Although this article would have relatively limited applicability to a practical web API implementation, it is a foundation toward understanding how to use the ASP.NET Web API framework to build your web API.

Step 1

Run Visual Studio and create a new ASP.NET Web Application. Give the project a name of StudentAPI. Select the ‘Web API’ template which will automatically select MVC and Web API Checkboxes. For now you can leave Authentication method use for API by default it is “No Authentication”.

Right-click on the Controllers folder in the Solution Explorer. Select Add => Controller and select MVC API 2 Controller -Empty. Other API option like controller with actions , using entity frame work etc, are scaffolding templates that write starter code for you. Then give controller name to StudentController.

It create the class StudentController that  inherits from ApiController. It serves as a base class for all the resources that we decide to expose via the API.


Step 2

Now we need to add a model class with name of Students, in the model folder.

Step 3

Now we will create a list of Students in controller.

Step 4

Then we will add the Action Methods to Get, Post, Put, and Delete Students. after adding methods, our controller is

Step 5

Now build and run the project, it show the home page with URL of http://localhost:xxxxx/. In the fiddler request composer type http://localhost:<port>/api/Students Replace <port> with the actual port your application runs on, then we would get result in json:

We can also get the details of a specific student by performing an HTTP GET on http://localhost:xxxxx/api/students/2. In this case, we get the JSON:

A hope

I hope that you will have better understanding of process for building your own Web API. I would like to hear valuable feedback or question from you. It encourage me to write more quality article.
Happy Reading 🙂

Advertisements

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s