How to change Python to Apps Script get api? - javascript

I want to change python to apps script in apps script have UrlFetchApp function i'm never use but i'm try
I have code python can get api normally
import requests
url = "https://api.aiforthai.in.th/ssense"
text = 'Have a good day'
params = {'text':text}
headers = {
'Apikey': "xxx-xxx-xxx"
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
so now i'm try code apps script like this but notthing came out ;
Api dashboard call me i'm use api.
maybe wrong payload text?
Detail API
Host
https://api.aiforthai.in.th/ssense
Method
GET/POST
Header
Apikey : xxx-xxx-xxx
Content-Type : application/x-www-form-urlencoded
Parameter
text : text for analysis
This my wrong apps script code
function call_api() {
var url = "https://api.aiforthai.in.th/ssense"
var apiKey = "xxx-xxx-xxx";
var response = UrlFetchApp.fetch(
url,
{
"headers": {
"Apikey": apiKey,
"text": "Have a good day"
}
}
)
Logger.log(response)
}
Thank you for solution.

I believe your goal is as follows.
You want to convert the following python script to Google Apps Script.
import requests
url = "https://api.aiforthai.in.th/ssense"
text = 'Have a good day'
params = {'text':text}
headers = {
'Apikey': "xxx-xxx-xxx"
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
You have already been confirmed that your python script worked fine.
When I saw your python script, text is sent as the query parameter. In this case, how about the folloiwng modification?
Modified script:
function call_api2() {
var text = "Have a good day";
var url = `https://api.aiforthai.in.th/ssense?text=${encodeURIComponent(text)}`;
var apiKey = "xxx-xxx-xxx";
var response = UrlFetchApp.fetch(
url,
{ "headers": { "Apikey": apiKey } }
);
Logger.log(response.getContentText());
}
Note:
If you test the above modified script, when an error occurs, please confirm your apiKey again.
If an error like status code 403 occurs, your URL might not be able to be requested from Google side. I'm worried about this.

Try this instead:
function call_api() {
var url = "https://api.aiforthai.in.th/ssense";
var apiKey = "xxx-xxx-xxx";
var response = UrlFetchApp.fetch(
url,
{
"method" : "GET",
"headers" : {
"Apikey" : apiKey,
"text" : "Have a good day"
}
}
);
Logger.log(response)
}
You can check out the UrlFetchApp documentation for future reference.

Related

No data scraping a table using Apps Script

I'm trying to scrape the first table (FINRA TRACE Bond Market Activity) of this website using Google Apps Script and I'm getting no data.
https://finra-markets.morningstar.com/BondCenter/TRACEMarketAggregateStats.jsp
enter image description here
function myFunction() {
const url = 'https://finra-markets.morningstar.com/BondCenter/TRACEMarketAggregateStats.jsp';
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
const $ = Cheerio.load(res);
var data = $('table').first().text();
Logger.log(data);
}
I have also tried from this page and I do not get any result.
https://finra-markets.morningstar.com/transferPage.jsp?path=http%3A%2F%2Fmuni-internal.morningstar.com%2Fpublic%2FMarketBreadth%2FC&_=1655503161665
I can't find a solution on the web and I ask you for help.
Thanks in advance
This page does a lot of things in the background. First, there is a POST request to https://finra-markets.morningstar.com/finralogin.jsp that initiates the session. Then, XHR requests are made to load the data tables. If you grab the cookie by POST'ing to that login page, you can pass it on the desired XHR call. That will return the table. The date you want to fetch the data for can be set with the date URL paramter. Here is an example:
function fetchFinra() {
const LOGIN_URL = "https://finra-markets.morningstar.com/finralogin.jsp";
const DATE = "06/24/2022" //the desired date
let opts = {
method: "POST",
payload: JSON.stringify({redirectPage: "/BondCenter/TRACEMarketAggregateStats.jsp"})
};
let res = UrlFetchApp.fetch(LOGIN_URL, opts);
let cookies = res.getAllHeaders()["Set-Cookie"];
const XHR_URL = `https://finra-markets.morningstar.com/transferPage.jsp?path=http%3A%2F%2Fmuni-internal.morningstar.com%2Fpublic%2FMarketBreadth%2FC&_=${new Date().getTime()}&date=${DATE}`;
res = UrlFetchApp.fetch(XHR_URL, { headers: {'Cookie': cookies.join(";")}} );
const $ = Cheerio.load(res.getContentText());
var data = $('table td').text();
Logger.log(data);
}

Does anyone know how to access an application-restricted endpoint HMRC API using JavaScript?

I'm trying to access the "hello application" endpoint using this tutorial: https://developer.service.hmrc.gov.uk/api-documentation/docs/tutorials . The first thing I've tried to do is request the access token but I'm unable to, I'm not quite sure what code I'm missing.
Here's what I've written so far:
const clientID = "R4c8CigzdVxxxxxxxxxxxxxxxx";
const clientSecret = "7dba1625-32f5-xxxx-xxxx-xxxxxxxxxxxx";
var url = ("https://test-api.service.hmrc.gov.uk/hello/application");
function hmrcApi() {
var oauthClientRequest = {
"tokenLocation": "https://test-api.service.hmrc.gov.uk/oauth/token",
"grantType": "GrantType.CLIENT_CREDENTIALS",
"clientID": clientID,
"clientSecret": clientSecret,
"setScope": "hello",
"redirectUri": "https://developer.service.hmrc.gov.uk/api-documentation/docs/api",
}
var response = UrlFetchApp.fetch (oauthClientRequest);
var result = JSON.parse(response);
Logger.log(response.getResponseCode());
}

fetch() sends the wrong URL Request to server

I have encountered a strange problem, doing a POST request using fetch(). It should have been easy, but I keep having an error code 405 from the server. Furthermore, the request URL should be only "http://localhost:3000/api/teddies/order", but somehow the local Visual_liveserver keeps adding in front of the URL request (the local server is hosted on this with port 5500 : http://127.0.0.1:5500)... In the image below you can see the error code 405 and this strange request URL.
Network inspector of the POST method : fetch()
By following this link, you will be able to access the Git of this projet. Don't hesitate to have a look at it ;) The file that calls these functions is called "pageFillingPanier.js".
But in short find below the code of the function that has the fetch in it:
const sendPurchaseRequest = async function (dataToSend) {
console.log(dataToSend);
try {
let response = await fetch('h​ttp://localhost:3000/api/teddies/order', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(dataToSend)
});
console.log(response.ok); //it shows false...
let responseData = await response.json();
sessionStorage.setItem('memoryResponse', responseData.orderId);
//window.location = 'remerciement.html';
} catch (error){
console.log(error);
}
}
Find below the code that calls the function:
document.getElementById('bttFormSend').addEventListener('click', function (e) {
e.preventDefault();
let formPurchaseOrder = {
contact : {
firstName : document.getElementById('firstName').value,
lastName : document.getElementById('lastName').value,
email : document.getElementById('email').value,
address : document.getElementById('adress').value,
city : document.getElementById('city').value},
products : []
};
for (let index = 0; index < basketToDisplay.length; index++) {
formPurchaseOrder.products.push(basketToDisplay[index].id);
}
//this function send the POST request to the server
sendPurchaseRequest (formPurchaseOrder);
});
As the image suggests, there's a non visible unicode character present in the url. This happens sometimes when you copy and paste the url from some other places.
%E2%80%8B in url encoded form and ​ without encoded.
Remove it and browser will recognize it as a valid url.
console.log(encodeURIComponent('h​ttp://localhost:3000/api/teddies/order'))
The url http://127.0.0.1:5500/ is added because browser doesn't detect the supplied url as a valid url hence consider it as a path and prepend your current url to it.

PayPal's Button Manager API with javascript

What i'd like to achieve is to dynamically create hosted PayPal buttons through the Button Manager API offered by PayPal, preferrably the NVP API. I would like to do so using client side Javascript.
Surprisingly, after extensive searching online I've failed to find a sample of code that achieves that goal.
Reading into the PayPal documentation led me to believe that I can use the API with xmlhttprequests. However, I fail to get a reply from PayPal. I've created a string with some arbitrary parameters which should be correct, and come as far as:
var xmlhttp;
function generateButton()
{
console.log("Function begun") ;
var strUrl= "https://api.paypal.com/nvp";
var strParameters="?METHOD=BMCreateButton&VERSION=204.0&BUTTONCODE=HOSTED&BUTTONTYPE=BUYNOW&BUTTONSUBTYPE=PRODUCTS&L_BUTTONVAR0=amount=15.00&L_BUTTONVAR1=item_name=test_item2USER=***&PWD=***&SIGNATURE=***";
var urlRequest= strUrl+encodeURI(strParameters);
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.open("POST",urlRequest,true);
xmlhttp.onreadystatechange= function(){
alert(xmlhttp.statusText) ;
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText) ;
}
};
xmlhttp.send();
}
My paypal credentials are listed as *** for privacy purposes, and in my code they are proper. Am I going about this the right way? Are my parameters incorrect, or is the issue with my xmlhttprequest? Bear in mind that I am new to web programming, and detailed explanations would be appreciated.
Thank you.
After some further reading, it seems calling the Button Manager API through client side javascript is not a correct approach as it requires a cross domain request (which browsers do not allow for security reasons).
It is possible to bypass this restriction with the CORS mechanism, but as far as I can tell PayPal does not support it. Other solutions exist but are 'dirty'.
I've concluded that it is better to make the request through a server. Requests can be made to your own server, which would invoke the button manager API and forward the reply (your new button's HTML code) back to the client.
Here is a NodeJS program code to create a new hosted button, which you can implement in your server:
var querystring = require('querystring'); // to URL encode for the NVP
var https = require('https'); // to use the NVP API, request must be https
// Prototype for a create button request fields, you can get your input from database, client side user or just hard code it
function CreateButtonRequest(user, pwd, signature, buttonPrice, buttonName){
this.USER =user,
this.PWD = pwd,
this.SIGNATURE = signature,
this.METHOD = "BMCreateButton",
this.VERSION = "204.0",
this.BUTTONCODE = "HOSTED",
this. BUTTONTYPE = "BUYNOW",
this.BUTTONSUBTYPE = "PRODUCTS",
this.L_BUTTONVAR0 = "amount="+buttonPrice,
this.L_BUTTONVAR1 = "item_name="+buttonName
}
// A sample request
// Replace **** with your API certificate specifics, find them in your paypal account
sampleRequestData = {
USER : "****",
PWD : "****",
SIGNATURE : "****",
METHOD : "BMCreateButton",
VERSION : "204.0",
BUTTONCODE : "HOSTED",
BUTTONTYPE : "BUYNOW",
BUTTONSUBTYPE : "PRODUCTS",
L_BUTTONVAR0 : "amount=10.00",
L_BUTTONVAR1 : "item_name=test item2"
};
sampleRequestData = querystring.stringify(postData);
//init your options object after you call querystring.stringify because you need
// the return string for the 'content length' header
console.log(sampleRequestData) ;
var options = {
host: 'api-3t.paypal.com',
port: 443,
method: 'POST',
path: '/nvp',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postBody.length
}
};
var postreq = https.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
postreq.write(sampleRequestData);
postreq.end();
console.log("Message sent...") ;

Fitbit API OAuth 1.0a from Titanium (Appcelerator)

I am using Titanium (Appcelerator) to connect to Fitbit API. (http://www.appcelerator.com)
I have been facing issues of getting "Invalid Signature" when I am trying to request for token.
I'm using HTTPClient from Titanium.Network.HTTPClient class to send the HTTP Request.
I also uses the oauth-1.0a.js library from https://github.com/ddo/oauth-1.0a to assist in getting the nonce and signature value.
Here is the code:
Ti.include('/oauth/ddo/hmac-sha1.js');
Ti.include('/oauth/ddo/enc-base64-min.js');
Ti.include('/oauth/ddo/oauth-1.0a.js');
function FitBitAuth() {
FitBitAuth.signatureMethod = "HMAC-SHA1";
FitBitAuth.clientKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
FitBitAuth.clientSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXX';
FitBitAuth.nonce = "R#nD0m_$tR!nGss";
FitBitAuth.request_token_url = "https://api.fitbit.com/oauth/request_token";
FitBitAuth.callback_url = "http://www.fitbit.com";
}
FitBitAuth.prototype.createConsumerTokenSecretPair = function() {
return OAuth({
consumer : {
public : FitBitAuth.clientKey,
secret : FitBitAuth.clientSecret
},
signature_method : FitBitAuth.signatureMethod
});
};
FitBitAuth.prototype.getRequestTokenRequestData = function() {
return {
url : "https://api.fitbit.com/oauth/request_token",
method : 'POST'
};
};
FitBitAuth.prototype.requestToken = function() {
var oauth = this.createConsumerTokenSecretPair();
var request_data = this.getRequestTokenRequestData();
var authorized_request = oauth.authorize(request_data, '', FitBitAuth.nonce, FitBitAuth.timestamp);
//alert(authorized_request);
return authorized_request;
};
function auth1a() {
var fb = new FitBitAuth();
var rt = fb.requestToken();
var req = Ti.Network.createHTTPClient();
req.open("POST", FitBitAuth.request_token_url);
req.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="'+FitBitAuth.clientKey+'"');
Ti.API.info(rt);
req.send({
oauth_timestamp : rt.oauth_timestamp,
oauth_nonce : rt.oauth_nonce,
oauth_signature : encodeURIComponent(rt.oauth_signature),
oauth_signature_method: rt.oauth_signature_method,
oauth_callback : encodeURIComponent(FitBitAuth.callback_url),
oauth_version : rt.oauth_version
});
req.onload = function() {
var json = this.responseText;
Ti.API.info("HEADER =====================");
Ti.API.info(req.getAllResponseHeaders());
Ti.API.info("END HEADER =================");
Ti.API.info(json);
var response = JSON.parse(json);
//alert(response);
};
}
I have also tried the Fitbit API Debug tool to assist me in getting all the signature right, in fact the signature and base String do match with the one shown by Fitbit API Debug Tool.
However, I keep getting this Invalid Signature, a sample JSON return is shown below:
{"errors":[{"errorType":"oauth","fieldName":"oauth_signature","message":"Invalid signature: rN**ahem**SGJmFwHp6C38%2F3rMKEe6ZM%3D"}],"success":false}
I have also already tested to do the curl way and it works from Terminal, but to no avail it does not give me a success from Titanium.
Any help is appreciated.
I manage to solve it.
I tried to use another way of inserting the parameters through the header.
Such that the setRequestHeader will look like this:
req.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="'+FitBitAuth.clientKey+'", oauth_nonce="'+rt.oauth_nonce+'", oauth_signature="'+rt.oauth_signature+'",...');
Alternatively, we can also use the built in toHeader feature of the oauth library that I'm using:
oauth.toHeader(oauth_data);
The code above will produce the oauth data in key-value pair.
{
'Authorization' : 'OAuth oauth_consumer_key="xxxxxxxxxxxxx"&oauth_nonce="xxxxxx"&...
}
So instead of the long code for setRequestHeader, we can make use of the value of toHeader, code shown below:
req.setRequestHeader('Authorization', oauth.toHeader(oauth_data).Authorization);
Do note that the return result by fitbit is in plaintext.
auth_token=xxxxxxxx&auth_token_secret=xxxxxxxxx&...

Categories

Resources