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.
- With the increase in the reach of internet and the devices on which we can browse and access data, there is need of much more type of data being supported. WEB api solve this problem by supporting not only JSON and XML but other types of data such as binary, text, images and many more.
- Web API are REST based unlike WCF which supports RPC or SOAP based communication, REST based communication is much more faster and lighter way to communicate over internet. This helps smaller devices to communicate better.
- There are no more bulkier configuration files unlike WCF.
- Incoming request can be handled more elegantly with routes and handlers.
- It is easier to automatically negotiate content types and serve various content formats directly.
- More control on request and response using HTTPResponseMessage and HTTPRequestMessage.
- A simple get request can be done using a Web browser.
- WEB API is resource based. While calling the methods of Web API we have to simply adhere to the HTTP methods like GET, PUT, POST and DELETE. I have discussed all the methods in my previous article.
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.
- 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.
- 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.
- 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.
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.
- 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; public PersonController() { person = new List () { 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 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.
- 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.
- 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.
- 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.
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.
Pedro René González says
Perfect Job!!! i need to consume this Get api fom mvc controller, how can i do that??? thx and good job man!!!!
Vikram Chaudhary says
Please have a look at the below code for api calling.
using (var httpClient = new HttpClient())
{
string apiURL = “your service URL”;
httpClient.BaseAddress = new Uri(apiURL);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
HttpResponseMessage response = await httpClient.GetAsync(“api/Controller”);
if (response.IsSuccessStatusCode)
{
}
}
Pedro René González says
Thx man!!!!