How to grab REST API data and display in a html page - html

Hi i am trying to get data from my LMS's rest API and then display it on a html page, I have a URL and an authorization bearer key
I was provided with some examples of how I should show my url and where to place my Authorization key see below
GET https://example.thoughtindustries.com/incoming/v2/ping
Example Request
CURL https://example.thoughtindustries.com/incoming/v2/ping -H 'Authorization: Bearer APIKEY'
I get a call back using the CURL in Visual Studio code so i know it can be pulled.
I found this method online which I thought would work
$.ajax({
url: "https://api.apiscience.com/v1/monitors/1572022",
headers: {
"Authorization": "Bearer NN_6xxxxx"
}
}).done(function(data) {
$('#monitor_data').append(JSON.stringify(data))
});
<h2>Response Data</h2>
<div id="monitor_data">
<!--location for Javascript to print data-->
</div>
I thought this would be the answer when replacing with my own URL and key but nothing happened. Do I need to include the -H somewhere and if so what might that look like?

It's easy as you have already done this. Write a get ajax call to your API and render your html part from the response you get from the API.
Take a sample example:
var getGamePeriod = function(){
$.ajax({
type: "GET",
url: "yourendpointhere?param=val",
contentType: "application/json",
dataType : 'json',
success : function(response){
if(response && response.isSuccess){
// do your stuffs here..
}
},
error : function(data,textStatus,errorMessage){
alert( textStatus + " " + errorMessage);
}
});
}
Of course you need to pass header or auth token if it is required to access the API. Place this method under document.ready method.

Related

How to ensure the API response for a request is JSON type in Google Apps Script? [duplicate]

This question already has answers here:
Apps Script - UrlFetchApp.fetch {url, method: "GET"} to a gzip gets failed with code 406
(2 answers)
Closed 1 year ago.
I'm trying to login to the tableau rest API in apps script and then get all the available views under a workbook. I'm authenticating via PATs and on successful sign-in I receive a response from the API that looks like XML response.
Here's the fetch code for that:
function tableauTM() {
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
Accept: 'application/json',
payload: JSON.stringify(
{
credentials: {
personalAccessTokenName: 'Tableau',
personalAccessTokenSecret: '<token_secret>',
site: {
contentUrl: 'pixybi',
},
},
}
),
};
const response = UrlFetchApp.fetch(
'https://10ay.online.tableau.com/api/3.13/auth/signin', options
);
Logger.log(response)
This is the response text I receive:
<?xml version='1.0' encoding='UTF-8'?><tsResponse xmlns="http://tableau.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableau.com/api https://help.tableau.com/samples/en-us/rest_api/ts-api_3_13.xsd"><credentials token="1j4LgLC1TQagsevrKPwJEw|VGo4bJwHbRQPRYxuOaeHhnsVth7nNc3e" estimatedTimeToExpiration="363:04:39"><site id="c3f66f3d-1112-4bff-a5f4-b4022e303d13" contentUrl="udacitybi"/><user id="c34bf5f6-86b8-4de6-a619-f68837bce120"/></credentials></tsResponse>
How to ensure that the response is of JSON type and if that's not possible how can
one extract the attribute values for fields like token, user, and site id?
We tried the below code but it's throwing the type error: TypeError: Cannot read property 'getChild' of null
var root = XmlService.parse(response).getRootElement().getChild('credentials').getChild('user').getAttribute('id').getValue()
You can parse XML using XML Service. Based on your error message, no root element exists, therefore you should first try hasRootElement() before calling getRootElement(). Instead you can try getDescendants() and log out its result.
Fix your options by adding Headers under the headers parameter. See the UrlFetch Docs. Basically, see headers below for what I mean. Hopefully this should enable you to receive JSON.
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
headers: { Accept: 'application/json' }, …
}

JSONP req.body is not work

I'm using nodejs and angular when I clicked on a button on angular side it makes a json post but I use JSONP because of crossdomain problems. When I try to get the data that I sent from client via JSONP I get something like this;
{ '{"userName": "something", "password" : "123"}': '' }
I get it from req.body on my server.js.
Here is my serverside code
app.post('/', function(req,res){
console.log("consoleeee:" + req.body);
res.end();
});
and here my client side function that works when clicked the button
function loginPageLogin(a, b, c, d, e, f, g, h, i, j) {
$.ajax
({
type: "POST",
url: 'http://localhost:777/node',
dataType: 'jsonp',
async: false,
data: '{"userName": "' + a.value + '", "password" : "' + b.value + '"}'
})
How Can I get req.body correctly? I want it as object. Thank you...
It is not possible to POST json data using the JSONP transport because JSONP requests are sent by appending a <script> tag to the body of the page, meaning post params cannot be sent, only get params. It also means that the data you are sending needs to be in key/value pairs, not JSON. It can't be synchronous either.
Therefore, You need to decide whether you want to go the JSONP route, or the JSON route with proper CORS setup. If JSONP, organize your paypload as an object, not json, and if json, modify your server to properly handle CORS by adding the CORS middleware.
You need to change data with this so it pushes an object instead a string:
$.ajax
({
type: "POST",
url: 'http://localhost:777/node',
dataType: 'json',
async: false,
data: {userName: a.value, password: b.value}
})

Box Get an Access token with ajax

I need to get the Access Token in ajax, the following example is in Curl how can i do the same in ajax call?
curl https://www.box.com/api/oauth2/token \
-d 'grant_type=authorization_code&code={your_code}&client_id={your_client_id}&client_secret={your_client_secret}' \
-X POST
i send ajax as following:
$.ajax({
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20https%3A%2F%2Fwww.box.com/api/oauth2/token',
type: 'POST',
dataType: 'jsonp',
processData: false,
data: {grant_type:'authorization_code', client_id:'3d2yi406h9eoykhucw9b8w3d2oky7kdy' , client_secret:'YQtHVIoutEnKLNpbmjk3CvZ72bshnpGk'},
complete: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
})
XMLHttpRequest {statusText: "", status: 0, response: "", responseType: "", responseXML: null…}
Alert: {"statusText":"OK","status":200,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}
As you can see i get an status:200 but the response is empty, and not including an "Access token", why?
If you look here: http://developers.box.com/oauth/
You will see that in the section "Getting the Access Token" that you can provide a redirect_uri.
When you register your application with Box they present you a page where you enter what is the redirect url that will be used (see example from link above). However, you can override that and provide the redirect url on your call during oAuth. So all you have to do is provide a page on your own web site which will hold the state change (either success or failure), and check on the state.
I saw that you added another detail on the request.
Note that the request is being done to https://query.yahooapis.com/v1/public/y... instead of http://developers.box.com/oauth/. That redirection is probably changing the query or the headers. Try updating and resubmitting. Let me know if it doesn't work.

Posting parameters in one URL and getting JSON from another URL

Am working in jQueryMobile and PhoneGap.
Currently am facing an issue that; For get the details in JSON format ; I post parameters into an URL (URL1) and I get the JSON response from another URL (URL2)
Currently i cant access the JSON data from the second URL.
My code is ;
function proceed_payment(){
var cardholder_= $('#input_Cardholder_name_').val();
var card_num_ = $('#input_CreditCard_').val();
var payment_ =$('#card_type_').val();
var cvv2_=$('#input_cvv2_').val();
var url;
url='https://www.sample.com/json/save_pament.php?json=1&rcg_mobile=2&reserv_num='+reservation_number+'&callback='+reservation_carcompany+'&cardholder='+cardholder_+'&payment='+payment_+'&card_num='+card_num_+'&card_cvv2='+cvv2_+'&card_expire_mon='+expire_month+'&card_expire_year='+expire_year+'&org_deposit='+sCarDeposit+'&org_cur='+currency+'&mond='+company_Show_mond+''
$.ajax({
url:url,
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success:function(data)
{
alert(data.Status);
$.mobile.changePage( "#reservation_status", {reverse: false, changeHash: true});
event.preventDefault();
},
error: OnError
});
};
Here I Post the parameters to URL1 : - https://www.sample.com/json/save_pament.php?
and get the JSON result in URL2 : https:// www.sample.com /result_bank_eup6.php?app=1
But My problem is i cant access the result from URL2.
Is there any method for solve this?
Please HELP :-(
Ullas Mohan V.
As per our discussion in comments and the error you mentioned
( [object Object]-parseerror-SyntaxError: Unexpected token < ).
The issue is related to web service/server side
Web service is not sending the desired response.
So client side/$ajax is not able to parse it.
You can check the actual response using Google Chrome's Advance REST Client.
To resolve this issue, you should contact the company
which is developing server side for you.

how to return json format from ODATA?

I know ODATA can return json but not sure if I have to use an attribute or interface to do so.
I want it to do just like http://odata.netflix.com/Catalog/Titles?$format=JSON but my odata service doesn't return JSON. When I call it like www.foo.com/service?$format=json, it just returns XML.
What do I need to do to return json with ODATA?
Download and install Fiddler.
http://www.fiddler2.com/fiddler2/
Once installed, open it, click on the "Request Builder" tab located in the right side of Fiddler.
Insert this URL:
http://test.com/feed2/ODataService.svc/results
Note that you DO NOT NEED THE ?$format=JSON
In the "Request Headers" section, insert the following line:
accept: application/json
Hit the Big "Execute" button at the top right of Fiddler.
You'll see the results of the request added to the list on the left side of Fiddler.
Double click on the request. The right side of Fiddler will change to the "Inspectors" tab where you can see the results of your request.
Also, since you are working with Json, you probably want to download and install the Json viewer plugin for Fiddler:
http://jsonviewer.codeplex.com/
Newer versions of WCF Data Services support JSON by default and you must have
Accept: application/json;odata=verbose
in the request header.
Accept: application/json
is no longer sufficient. More info here.
No-one seems to be answering your question very cleanly here!
From an HTML page you can use the following Javascript / JQuery code to have a WCF Data Service return data in JSON format;
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var sURL = "http://YourService.svc/Books(10)";
function testJSONfetch() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: sURL,
error: bad,
success: good,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
}
});
}
function good(response)
{
}
function bad(response)
{
}
</script>
You need to add “Accept: application/json” into the request header section.
Check out this link
If you're using the ODATA provider from Data Services you can easily return ODATA as JSON by specifying it in the URL as in the sample you gave - http://odata.netflix.com/Catalog/Titles?$format=JSON
To do this use the JSONp and URL-controlled format support for ADO.NET Data Services download from MSDN http://code.msdn.microsoft.com/DataServicesJSONP and add the JSONPSupportBehavior decorator to your DataService class like below.
[JSONPSupportBehavior]
public class MyDataService : DataService<MyContextType>
{
...
"...but I get "The webpage cannot be found" using http://test.com/feed2/ODataService.svc/results?$format=JSON ..."
you dont need the $format=JSON in the Uri.
Just use "http://test.com/feed2/ODataService.svc/results"
(with Accept: application/json in the request header)
Late answer, but I've been spending the last hour trying to figure out how to curl OData APIs and return the result as json. The following code fetches the document in json and writes it to a file:
-o myfile.html -H "Accept: application/json" http://example.com/api/data?$filter=name eq 'whatever'
... just use lower case letters:
"format=json"
It's not pretty but this is how I forced JSON output without using $format in the request string:
Request r = new Request(Method.GET, "http://XXXXXXX.svc//Login"
+ "&UserId=" + "'" + "user" + "'"
+ "&Password=" + "'" + "password" + "'");
ClientInfo ci = r.getClientInfo();
ArrayList<Preference<MediaType>> accepted = new ArrayList<Preference<MediaType>>();
accepted.add(new Preference<MediaType>(MediaType.APPLICATION_JSON));
ci.setAcceptedMediaTypes(accepted);
Client client = new Client(Protocol.HTTP);
Response response = client.handle(r);
Representation output = response.getEntity();