First Web Api Project

by Sachin Singh


Posted on Thursday, 30 April 2020

Tags: Creating web api project Rest principles validaet rest principles with web api

I believe in learning every new concept from scratch, so instead of analyzing the Web API template offered by the visual studio which is a combination of MVC and Web API, we will take an empty template of Web API and we will create an API from scratch.

In the previous article we have learned that Web API is used to create RESTful services, and also learned what actually the Rest principles are.

Now it's time to make our hands dirty and create a real-world Rest service and expose it to the outside world and check whether have we followed the REST principles or not.

The point that you shouldn't forget is, an API only exposes the data to the outside world in the form of representation like JSON or XML, and how the client uses those data and display the data is completely up to them. For example, your client may be a JavaScript App that displays the data it gets from your API in a table on the HTML page.

Let's create an API that exposes Employee related data of a company, being an API the offered services can be consumed by any client like browser, JQuery Ajax, or third-party tools like Postman or fiddler. In this article I will only demonstrate the get method so the browser would be sufficient to test the API as each request from a browser is actually a get request, later I will use Fiddler to test the API, you are free to use any tool of your desire.

Let's start :-
Step 1.Open visual studio and select Web-->Asp.Net Web Application ,name your project and click OK. Then select empty template and check Web API checkbox.

Create Empty Web API project
Empty Web API figure1
Create Empty Web API project
Empty Web API figure 1.1

Before going to step 2 , let's take a look of directory structure of the web Api project.

Create Empty Web API project
Directory structure of web Api

As you can see ,the directory structure of an web API project is very much similar to a MVC project. Actually there is only two difference :-
1. The first one is absence of View ,and it is very much understood ,cause an API only exposes the data part so there is no need of view, the consumer of your API may create view (display) to represent data he gets from your API.
2. Instead of RouteConfig ,here we have WebAPIConfig to configure the web API routes.

So, the request response mechanism is exactly the same as an MVC project has ,with little deviation.
  • At first the routing module does his job ,it extracts the controller name from URL ,checks the request type like get, put, post and delete and accordingly maps it with appropriate controller and action method to process the request.
  • Action methods gets the Parameter ,which is referred as parameter binding which you will learn in later article.
  • Media Type Formatters format the data into appropriate representation as per the client wish ,this process is referred as Content negotiation. You will learn about content negotiation in later article.
  • Finally ,the representation of resource is sent to the client. The http response body carries the representation.

Step 2. Create a controller by selecting Web API 2 empty controller and name it EmployeeController as shown in below figure.

Create Empty Web API project
Empty Web API Controller
Create Empty Web API project
Create a EmployeeController

Step 3.Create an Employee class under model folder like below.


  public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
    }

Step 3.Create two action method One for Exposing all Employees data and second to expose particular employee data by his Id.


    public List<Employee> LoadEmployee()
        {

            List<Employee> Employees = new List<Employee>(){
                new Employee(){Id=1,Name="Sachin",Salary=600000},
                 new Employee(){Id=2,Name="Arjun",Salary=350000},
                  new Employee(){Id=3,Name="Vikash",Salary=500000},
                   new Employee(){Id=4,Name="Abhijit",Salary=45000},
            };
            return Employees;
        }

        public List<Employee> GetAllEmployee()
        {

            var emps = LoadEmployee();
            return emps;
        }

        public Employee GetAllEmployeeById(int Id)
        {
            Employee emp = LoadEmployee().Where(x => x.Id == Id).SingleOrDefault();
            return emp;
        }

Step 4.Run the application ,and Enter the URL:-
1. http://localhost:portNo/api/employee
It will return the below representation.

Create Empty Web API project
XML representation for all employee

2. http://localhost:portNo/api/employee/4
It will return the below represntation.

Create Empty Web API project
XML representation for particular employee

So, we have successfully created an API.

Now Let's dive deep and check whether have we followed the rest principles or not.

1.Everything is resource.(No need to verify ,yes everything is a resource. here EmployeeList and single employee both are resource on server).

2.Each resource is uniquely identifiable.(verified)
For List of Employee we have :- http://localhost:portNo/api/employee
For single Employee we have :- http://localhost:portNo/api/employee/1

3.Interface must be simple.(yes ,verified.)
as our method names are starting with Get prefix so the URL are simple. And request is mapping with appropriate action method .The question is how will we achieve simpler interface when method names do not start with http verb.

4.Stateless(verified, over http ,no doubt)

5.Response must be a representation.(yes, verified)
we are getting XML representation back. But how???? who is doing that. we will try to find out this puzzle in next article.

Is everything good? yes, almost. We are following rest principles obediently. But almost doesn't mean everything.

Let's see what are we missing.

case 1.what if List of employee gets null.(we must return http status code 204 (No content) with no employee found message)

case 2.what if any run time error occurs.(we must return 500 internal server error).

case 3.what if there is no employee of specified Id exist.( we must return 204 status code, with no employee with specified Id exist message. )

In short ,No we are not following rest principles completely. Rest means respect the http protocol and utilize it as much as you can.

Lets modify the above code to get the desired outcome and fulfill the rest principles completely.


    public HttpResponseMessage GetAllEmployee()
        {
            try
            {
                List<Employee> Employees = LoadEmployee();
                if(Employees!=null){
                     return Request.CreateResponse(HttpStatusCode.OK, Employees);
                }
               return Request.CreateErrorResponse(HttpStatusCode.NotFound,"No result found");
            }
            catch{
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
           
        }

        public HttpResponseMessage GetAllEmployeeById(int Id)
        {
            try
            {
                 Employee emp = LoadEmployee().Where(x => x.Id == Id).SingleOrDefault();
                if(emp!=null){
                    return Request.CreateResponse(HttpStatusCode.OK,emp);
                }
                return Request.CreateErrorResponse(HttpStatusCode.NotFound,"Employee with id " +Id+ " Not found");
              
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
       
           
        }

Now ,Run the application and request employee who doesn't exist like employee with id 5. you will get below representation.

Create Empty Web API project
No Result found Error representation

Now Everything is fine. Hurrah ,you have learnt how to create Restful services with Web API.