Monday, June 13, 2016

Calling RESTful API in Angular Js


Here, we will call the RESTful API from angular js.

Suppose there is a RESTful API which URL is: http://localhost:8080/saveDetails

And I want to save employee information using angular js. We will call the above API using “POST” method.

There is a button in html page. When I will click this button it will save the employee information. Data is being sent in JSON format.

Here, I am using “$resource” service to call RESTful API.
The $resource service is a factory which creates a resource object that lets you interact with RESTful server-side data sources as per the angular js documentation.

Note: It requires the ngResource module of angular js to be installed.


1.  Testing.html

<!DOCTYPE html>
<html ng-app='demoApp'>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="../angular/angular.js"></script>
    <script src="../angular-resource/angular-resource.js"></script>
    <title></title>
</head>
<body ng-controller='demoCtrl'>
    <input type="button" value="Submit" ng-click="saveDetails()" />   
    <script src="testing.js"></script>
</body>   
</html>

2.  testing.js

var demoApp = angular.module("demoApp", ['ngResource']);

demoApp.factory('employee', function ($resource) {
    return $resource('/employee/:cmd', {}, {
        saveDetails: { method: 'POST', isArray: true, params: { cmd: 'saveDetails' } },
    });
});

demoApp.controller("demoCtrl", ['$scope', 'employee', function ($scope, employee) {
    var config = {
        "empID": 1001,
        "firstName": "Shshi Bhooshan",
    };

    $scope.saveDetails = function () {
        employee.saveDetails(config, function (data) {
            // here data will come as JSON array in "data" object
            // it will be used to show input source fields

            document.write(JSON.stringify(data));
        }, function (err) {
            console.log('saveDetails error:', err);
        });
    }
}
]);


Hope this is helpful example for you. Leave your comment and provide your suggestion if any.

Calling RESTful API in asp.net

Here, we will call the RESTful API from asp.net.

Suppose there is a RESTful API which URL is: http://localhost:8083/saveDetails

And I want to save employee information using asp.net.

We will call the above API using “POST” method.

There is a button in .aspx page. When I will click this button it will save the employee information. Data is being sent in JSON format.

Here I am using “HttpClient” to call RESTful API.

1.       Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnSaveDetails" runat="server" Text="Save Details" OnClick="btnSaveDetails_Click" />
        </div>
    </form>
</body>
</html>

2.       Default.aspx.cs
using System;
using System.Net.Http;
using System.Net.Http.Headers;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    private void saveDetails()
    {
        HttpClient client = new HttpClient();
        Uri url = new Uri("http://localhost:8083/saveDetails");
        client.BaseAddress = url;

        // Add an Accept header for JSON format.

        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        System.Net.Http.HttpContent content = new StringContent(@"{""empID"":1001, ""empName"":""Shshi Bhooshan Sharma""}", System.Text.UTF8Encoding.UTF8, "application/json");

        HttpResponseMessage response = client.PostAsync(url, content).Result;
        if (response.IsSuccessStatusCode)
        {
            var result = response.Content.ReadAsStringAsync().Result;
            Response.Write(response.ReasonPhrase + "," + result);
        }
        else
        {
            Response.Write(response);
        }
    }

    protected void btnSaveDetails_Click(object sender, EventArgs e)
    {
        saveDetails();
    }
}

Hope this is helpful example for you. Leave your comment and provide your suggestion if any.

Calling RESTful API in Javascript


Here, we will call the RESTful API from javascript.

Suppose there is a RESTful API which URL is: http://localhost:8083/saveEmployeeDetail

And I want to save employee information using Javascript.

We will call the above API using “POST” method.

There is a button in html page which. When I will click this button it will save the employee information. Data is being sent in JSON format.

Here I am using “XMLHttpRequest” to call RESTful API.



1.  Testing.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <title></title>
</head>
<body ng-controller='loaderCtrl'>
    <input type="button" value="Submit" onclick="saveDetails()" />
    <script src="testing.js"></script>
</body>
</html>

2.  testing.js
var sendRequest = function (config, method) {
    if (!config) return;

    var ajaxHandler = new Object();

    if (window.XMLHttpRequest) {
        ajaxHandler.ajaxReq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        ajaxHandler.ajaxReq = new ActiveXObject('Microsoft.XMLHTTP');
    }

    ajaxHandler.ajaxResponse = function () {
        // Only if req shows "complete"
        var readyState, status;
        readyState = ajaxHandler.ajaxReq.readyState;
        if (readyState == 4) {
            status = ajaxHandler.ajaxReq.status;
        }
        if (readyState == 4) {
            if (status == 200) {
                document.writeln(ajaxHandler.ajaxReq.responseText);// here response will come success                 
                 
            } else {
                document.writeln(ajaxHandler.ajaxReq.responseText);// here response will come  show failed message                

            }
        }
    }
    ajaxHandler.ajaxReq.onreadystatechange = ajaxHandler.ajaxResponse;
    ajaxHandler.ajaxReq.open(method, "http://localhost:8083/saveEmployeeDetail", true); // second parameter is the URl of the REST API
    ajaxHandler.ajaxReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
    //ajaxHandler.ajaxReq.headers = { "Authorization": "Basic " + btoa("admin:admin") };               
    ajaxHandler.ajaxReq.send(JSON.stringify(config));
}

function saveDetails() {
    var config = {
        "empID": 1001,
        "firstName": "Shshi Bhooshan",
    };

    sendRequest(config, "POST");
}



Hope this is helpful example for you. Leave your comment and provide your suggestion if any.