Dot Net For All

First ASP.NET Web API with GET request

In this article I will discuss about the need of the ASP.NET Web API along with the development of the first Web API application. The WEBAPI application which I will develop will support GET method.

Why ASP.NET Web API ?

Before starting the development of our first web api application we should know the purpose and scenarios where the ASP.NET web api would be best fit. Please have a look at the below points.

My FIrst ASP.NET Web API

Lets start developing my first ASP.NET web API using Visual Studio 2015 community addition with C# as the programming language.

      1. Go To File > New > Project. A new project creation template screen will open. Create a new web project named Person.WebAPI as shown in the figure below.
        Create New Project ASP.NET Web API

         

      2.  In the next screen select the empty project template. And select Web API option in the add folders and core references section. Please check the figure below.
        Select Empty Project Template

         

      3. In this step we will add the controller for the ASP.NET Web API. This is the same controller to which all our requests to the WEB API will be sent. I will name the controller as Person.
        Adding A controller

        In the next window I will select the “Web API 2 Controller – Empty” as the option and click “Add”. In the next windows I will name the controller as PersonController. Please note that whatever name we are using for the controller it needs to be suffixed with Controller.

      4. We have a new controller in the Controllers folder. The class derived from ApiController. This is the class which provides all the necessary plumbing between Request and response. For this project I will not be working with some outside data source like SQL. I will create a local in memory data source which Will be a collection of Person Object. The person class is as shown below.
            public class Person
            {
                public string FirstName { get; set; }
                public string LastName { get; set; }
                public int Age { get; set; }
            }

        The code for the PersonController.cs class I have changed as following.

         IList<Person> person;
                public PersonController()
                {
                    person = new List<Person>() { new Person() { FirstName = "Vikram", LastName = "Chaudhary", Age = 33, ID = 1 },
                        new Person() { FirstName = "Prasad", LastName = "M", Age = 33, ID = 2 },
                        new Person() { FirstName = "Abhishek", LastName = "Singh", Age = 33, ID = 3 },
                     };
                }
        
                public IList<Person> Get()
                {
                    return person;
                }
        
                public Person Get(int id)
                {
                    return person.Where(person => person.ID == id).SingleOrDefault();
                }

        The functions which I have created in the above code will be resources for the Web API. The functions we usually create in controller are analogous to the REST verbs i.e. GET, PUT , POST, DELETE.

      5. Now lets run the project. Once the project is started we will see a screen as shown below figure. There is no HTML to render that is why we got a screen like this.
        First Web API

         

      6. Now to access the resources of the WEB API. We have to change the URL in the browser to “http://localhost:51110/api/person“.  This is due to the reason that route for the API controllers have a “api” prefixed to differentiate it from the normal MVC route. The code for routing you can see in WebApiConfig.cs which is present in App_Start folder. Enter the whole API url in the address bar of the chrome and you can see a list of all the persons. By default the GET request is sent to the controller. And as we can see in the code above, the GET request sends all the persons.
        WebAPi Get Request

         

      7. Now if I want to get a single person from the collection. I have to get it by providing the id in the URL. The URL will be like “http://localhost:51110/api/person?id=1“. In this case the Get method with the parameter will be called and return a single person from the List as shown in the figure below.
        GET with parameter

        The id in the URL is mapped to the id parameter of the Get method with the help of the route we have defined in the WebApiConfig.cs. Please have a look at the code.

          public static void Register(HttpConfiguration config)
                {
                    // Web API configuration and services
        
                    // Web API routes
                    config.MapHttpAttributeRoutes();
        
                    config.Routes.MapHttpRoute(
                        name: "DefaultApi",
                        routeTemplate: "api/{controller}/{id}",
                        defaults: new { id = RouteParameter.Optional }
                    );
                }

        If we change the “id” to suppose “PersonID”. Then we have to change it at all the places including the name of the parameter for the Get method. And the set URL will be like “http://localhost:51110/api/person?personId=1“.

Conclusion :

In this article I have listed out the usages of ASP.NET Web API over other ways of transporting messages across internet. I have also created my first WEB API with simple GET request. In my next article I will show how to add data to the collection using POST request.

 

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview