Wednesday, December 24, 2014

How to call JSON web service (Weatherbug) and use objects

Requirement - Call Weatherbug JSON web service to authenticate


//***************************************************************************************************************************
// This function is to call Weather Auth Web service to generate token
function getWeatherAuthToken(clientId, clientSecret) {

    var externalUrl = "https://thepulseapi.earthnetworks.com/oauth20/token?grant_type=client_credentials&client_id=" + clientId + "client_secret=" + clientSecret;
    var retToken;
   
    $.ajax({
        url: "../_api/SP.WebProxy.invoke",
        type: "POST",
        async:false,
        data: JSON.stringify(
            {
                "requestInfo": {
                    "__metadata": { "type": "SP.WebRequestInfo" },
                    "Url": externalUrl,
                    "Method": "GET",
                    "Headers": {
                        "results": [{
                            "__metadata": { "type": "SP.KeyValue" },
                            "Key": "Accept",
                            "Value": "application/json;odata=verbose",
                            "ValueType": "Edm.String"
                        }]
                    }
                }
            }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {

            // status code 200 means ok, got the data
            if (data.d.Invoke.StatusCode == 200) {
                var body = JSON.parse(data.d.Invoke.Body); //Load body object
                var oAuthToken = JSON.parse(JSON.stringify(body.OAuth20));
                var accessToken = JSON.parse(JSON.stringify(oAuthToken.access_token));
                retToken = JSON.parse(JSON.stringify(accessToken.token));
                //alert(retToken);
                //retToken = JSON.parse(JSON.stringify(body["OAuth20"]["access_token"]["token"]));
            }
            else {
                // some status codes like 302 redirect do not trigger the error handler
                var err = "Status code: " + data.d.Invoke.StatusCode + ". ";
                err += data.d.Invoke.Body;
                $("#message").html(err);
            }
        },
        error: function (data) {
            var body = data.d.Invoke.Body;
            $("#message").html(body);
        }
    });
    return retToken;
}

Highlighted lines are important to note. Upon success with code = 200, parse JSON body. Then alert the entire body text using stringify. Then Watch the objects and load them one by one.

No comments:

Post a Comment