Introduction
The Web API is the Application Programming Interface (API) for both the web server and web browser. The API is a framework for building HTTP services that can be consumed by the clients, either by a browser, iPhone, tablets or a mobile. A server- side Web API is a programmatic interface to define the request/response message system, these are expressed in JSON or XML that are exposed via the web.
Features of Web API
- Web API is open source
- Used to make a non-SOAP based HTTP Service
- Based of HTTP and easy to define, expose and consume in a RESTful way.
- Web API does not have any cumbersome and tedious configuration like WCF REST service.
- Web API is a lightweight architecture and is good for a device that has limited/reduced bandwidth (smartphones).
Basic procedure for creating a Web API and consuming in a HTML page
- Create a Web API
- Adding a Model
- Adding a controller
- Consuming the Web API
Create a Web API
Start the Visual Studio and choose "New Project" then choose the "ASP.NET Web application" template.
After selecting the project, choose an Empty template and select the "Web API" under the "Add folder and core reference for :"
You may also choose a Web API project using the "Web API" template. The Web API template uses ASP.NET MVC to provide API help pages.
Adding a Model
Model class used for to represent the data and the data are used in our application. Web API automatically serializes our model to JSON, XML or some other format and then we write the serialize data into the body of the response message.
This is the code of the model class, where we create properties of the Student.
- namespace StudentRecord
- {
- public class Student
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string Class { get; set; }
- public string Address { get; set; }
- public int PercentageMarks { get; set; }
- }
- }
Adding a controller
We use a controller for the handler of HTTP requests. In the project I added a controller and that controller returns a list of students or a single student as passed by ID.
Add a Scaffold, select "Web API controller -Empty". Click Add.
This is the controller class where we define the Get all the students function and get the student by id, these methods definitions are in the snippet below.
- namespace StudentRecord.Controllers
- {
- public class StudentsController : ApiController
- {
- Student[] st = new Student[]{
- new Student{ID=1, Name="Rajeev Ranjan",Address="pune", Class="IX", PercentageMarks=87},
- new Student{ID=2, Name="Manish Shrivastava",Address="pune", Class="IX", PercentageMarks=88},
- new Student{ID=3, Name="Chandan Singh",Address="Ranchi", Class="IX", PercentageMarks=99},
- new Student{ID=4, Name="Manish Singh",Address="Ranchi", Class="IX", PercentageMarks=85},
- new Student{ID=5, Name="Rohit",Address="New Delhi", Class="IX", PercentageMarks=79},
- new Student{ID=6, Name="Kunal",Address="New Delhi", Class="IX", PercentageMarks=64},
- new Student{ID=7, Name="Thomas Minz",Address="Hazaribagh", Class="IX", PercentageMarks=33},
- new Student{ID=8, Name="Santosh",Address="pune", Class="IX", PercentageMarks=56},
- new Student{ID=9, Name="Amrut Gholkhar",Address="Aurangabad", Class="IX", PercentageMarks=82},
- new Student{ID=10, Name="Gaurav Lahe",Address="Amrawati", Class="IX", PercentageMarks=98},
- };
- public IEnumerable<Student> GetAllStudent() {
- return st;
- }
- public IHttpActionResult GetStudents(int id)
- {
- var stud = st.FirstOrDefault((s) => s.ID == id);
- if(stud== null)
- {
- return NotFound();
- }
- return Ok(stud);
- }
- }
- }
Consuming the Web API
This is the final section of when we consume and disply in the HTML page, using jQuery and Ajax. Ajax calls the Web API and we use jQuery to make the Ajax calls.
If you have no jQuery file then install it from the Nuget Packet Manager. It is essential to attach the jQuery file inside the HTML page, if we missed that then jQuery and Ajax will not able to consume the Web API request and response object.
This is the HTML and jQuery codes to make the app possibilities come true.
- <html>
- <head>
- <title>Student Record</title>
- </head>
- <body>
- <div>
- <h2>Student</h2>
- <table id="student" cellpadding="2" cellspacing="2" border="1" width="400px">
- <tr>
- <td style="background-color: gray; color: white">ID</td>
- <td style="background-color: gray; color: white">Name</td>
- <td style="background-color: gray; color: white">Class</td>
- <td style="background-color: gray; color:white">Percentage Marks</td>
- <td style="background-color: gray; color:white">Address</td>
- </tr>
- </table>
- </div>
-
- <div>
- <h2>Search by ID</h2>
-
- <input type="text" size="5" id="stuId" />
- <input type="button" value="Search" onclick="find();" />
-
- <p id="st"></p>
- </div>
- <script src="Scripts/jquery-2.1.1.js"></script>
- <script type="text/javascript">
-
- var uri = 'api/students';
- $(document).ready(function () {
- $.getJSON(uri)
- .done(function (data) {
- $.each(data, function (key, item) {
- $('#student').append("<tr><td>" + item.ID + "</td>" + "<td>" + item.Name + "</td>" + "<td>" + item.Class + "</td>" + "<td>" + item.PercentageMarks + '%' + "</td>" + "<td>" + item.Address + "</td></tr>");
- });
- });
- });
-
- function formatItem(item) {
- return item.Name + '-' + item.PercentageMarks;
- }
- function find() {
- var id = $('#stuId').val();
- $.getJSON(uri + '/' + id)
- .done(function (data) {
- $('#st').text(formatItem(data));
- })
- .fail(function (jqXHR, textStatus, err) {
- $('#student').text('error' + err);
- })
- }
- </script>
- </body>
- </html>
Output
This is the output of all the records fetched.
When we select by ID then the result will shown as in the following.
When we enter the wrong (lower / upper) records then we get the following output message.
Summary
In this article we learned how to make a Web API and how to consume it in a HTML page using jQuery and AJAX. We also covered the benefits of the Web API. HTTP is not just for serving up web pages, it is also a powerful platform for building an API that exposes data and services. Almost every platform can easily get the data from the Web API, either Tablet or website by HTTP.