Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Consume a Web API Using Angular

DZone's Guide to

How to Consume a Web API Using Angular

In this article, we show you step-by-step how you can query, consume and display data from a Web API in your Angular web application.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

In development, sometimes we consume data from different sources, for example, web services. Today, in this article, we are going to learn:

  • How to consume data from Web APIs using Angular.
  • The ng-repeat directive in Angular. 

What Is a Web API?

As we all know, API stands for Application Programming Interface. The main purpose of a web API is to create RESTful services. Web APIs are consumed by a broad range of clients like:

  1. IoT (Internet of Things).
  2. Mobile apps.
  3. Web based apps.
  4. Desktop apps.

So we are going to learn how to consume services through Angular. So let's take a look.

Step 1:
 Open Visual Studio.

Step 2: 
File>>New>> Project

Project

Choose ASP.NET Web Application

Step 3: Select Web API

Project

Click OK.

Check the Solution Explorer.

Project

Here you can see that it looks like an MVC Application, where we have Models, View, and a Controller. But my friend, here we will create web APIs.

Now the question arises: what is the difference between a Web API Controller and an MVC Controller?

Project

If we're talking about MVC Controllers, an MVC Controller will be inherited by the controller and the Web API Controller will be inherited by the API Controller. This is the biggest difference between these two.

And the Web API is designed to return data in JSON and XML.

So, in this example, we have one StudentDB database, where we have student information. So, first, create a StudentDB and one table called StudentMaster.

Project

Below is the data when it's put into one StudentMaster table.

Project

Now, create an Edmx File, and connect StudentDB with your entity. In this example, my entity name is StudentEntity.

Click on the Add Button. Now, using wizard, create an EDmx file.

  • Once you click on the finish button, your screen looks like this:

Project

Now, open HomeController. By default, HomeController will be inherited by Controller like this: HomeController:Controller. Change this to HomeController:ApiController, and copy the below code.

usingAngularwithWebAPI.DbContext;  
using System;  
usingSystem.Collections.Generic;  
usingSystem.Linq;  
usingSystem.Web;  
usingSystem.Web.Http; // This namespace is responsible for IHttpActionResult  
usingSystem.Web.Mvc;  

namespaceAngularwithWebAPI.Controllers {  
    publicclassHomeController: ApiController {  
        DbContext.StudentEntitiesstudentEntities = newDbContext.StudentEntities();  
        publicIHttpActionResultGetStudents() {  
            var query = studentEntities.StudentMasters.ToList();  
            return Ok(query);  
        }  
    }  
}   
  • Now, let's understand the above code line by line. You can see in the above code we have Homecontroller: ApiController, because we want to work on a Web API.
  • I created an object called studentEntities, so we can get all the table sps from StudentDB very easily.
  • After that, we have public IHttpActionResultIHttpActionResult is introduced in Web API 2. This needs a namesapcesystem.web.http. Ihttpactionresult is used for building HTTP response messages.
  • Now run your service.usingAngularwithWebAPI.DbContext; using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Web.Http; // This namespace is responsible for IHttpActionResult usingSystem.Web.Mvc;  namespaceAngularwithWebAPI.Controllers {     publicclassHomeController: ApiController {         DbContext.StudentEntitiesstudentEntities = newDbContext.StudentEntities();         publicIHttpActionResultGetStudents() {             var query = studentEntities.StudentMasters.ToList();             return Ok(query);         }     } }
  • After that, we get a list of student data from our query and then return OK (query). That means this will convert this into an XML array, which I have labeled Studentmaster. With this, we can easily console this into our Angular code.

Our Angular Code

Script.js

var testApp = angular

module("testModule", [])

controller("testController", function($scope, $http) {

    $http.get('http://localhost:50623/api/home/getstudents').then(function(response) {

        $scope.students = response.data;

    });

});

Here I use $http, which is used for sending get, put, post, and delete requests to the server. After we get the result of this request, we can store it in the $scope variable.

$http.get('url' ) - here we have to call our URL, so please first, call your web API and check your port number, and then use your URL with the $http.get request.

Now, call the $scope variable to your page.

index.html

<!DOCTYPE html>  
<html ng-app="testModule">  

    <head>  
        <script src src="Scripts/angular.min.js">  
            </script>  
            <script src script src="Scripts/js/Script.js">  
                </script>  
                <title></title>  
                <meta charset meta charset="utf-8" />  
    </head>  

    <body>  
        <div ng-controller="testController">  
            <table border="1">  
                <thead>  
                    <tr>  
                        <th>  
                            Student Id  
                        </th>  
                        <th>  
                            Name  
                        </th>  
                        <th>  
                            Address  
                        </th>  
                        <th>  
                            Email  
                        </th>  
                        <th>  
                            Phone  
                        </th>  
                    </tr>  
                </thead>  
                <tr ng-repeat="s in students">  
                    <td>  
                        {{s.Id}}  
                    </td>  
                    <td>  
                        {{s.Name}}  
                    </td>  
                    <td>  
                        {{s.Address}}  
                    </td>  
                    <td>  
                        {{s.Email}}  
                    </td>  
                    <td>  
                        {{s.Phone}}  
                    </td>  
                    </tr>  
                    </table>  
                    </div>  
    </body>  

    </html>  

In the above code, I used the ng-repeat directive. With the use of this directive, we can call list information, so we have scope variable for students. So, I used ng-repete='s in student so this will give me all the related object data, one by one. You can see, I used the ng-repete<tr> section because we want data row wise, so every time the ng-repeat loop runs, this will create a new <tr> row with data.

Now it's time to check the output.

&lt;!DOCTYPEhtml /&gt;   &lt;title&gt;&lt;/title&gt;&lt;thead&gt;   &lt;tr&gt;     &lt;th&gt;                             Student Id                         &lt;/th&gt;     &lt;th&gt;                             Name                         &lt;/th&gt;     &lt;th&gt;                             Address                         &lt;/th&gt;     &lt;th&gt;                             Email                         &lt;/th&gt;     &lt;th&gt;                             Phone                         &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt;&lt;td&gt;                         <span ng-non-bindable>{{s.Id}}</span>                     &lt;/td&gt;&lt;td&gt;                         <span ng-non-bindable>{{s.Name}}</span>                     &lt;/td&gt;&lt;td&gt;                         <span ng-non-bindable>{{s.Address}}</span>                     &lt;/td&gt;&lt;td&gt;                         <span ng-non-bindable>{{s.Email}}</span>                     &lt;/td&gt;&lt;td&gt;                         <span ng-non-bindable>{{s.Phone}}</span>                     &lt;/td&gt;

You can see, finally, our data is consumed by a web API. We can see all student data row by row through ng-repeat.

If you have any questions or suggestions regarding this article, please send your valuable comments.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
web dev ,.net ,angular ,web api

Published at DZone with permission of Sourabh Mishra. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}