I'm using the binance API to get the prices of usdt. The API works on postman but it doesn't work on google script.
function fetchCryptoPricesFromApi() {
const data = {
"page": 1,
"rows": 10,
"payTypes": [],
"asset": "USDT",
"tradeType": "SELL",
"fiat": "LKR",
"publisherType": null,
"transAmount": "2600"
}
const payload = JSON.stringify(data)
const options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
}
let response;
try {
response = UrlFetchApp.fetch('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', options);
} catch (error) {
console.log('Oops Error, ', error);
return
}
const prices = JSON.parse(response)['data'];
console.log(prices)
}
I get the following error when executing this,
Oops Error, { [Exception: Request failed for https://p2p.binance.com returned code 403. Truncated server response: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" ... (use muteHttpExceptions option to examine full response)] name: 'Exception' }
I tried waiting some time as well.
CodePudding user response:
From your showing error message, I confirmed the status code 403
. Ref In this case, it is considered that the site cannot be directly accessed from the Google side. I think that the reason for your issue is due to this.
In this case, as a workaround, I would like to propose access to the URL without directly running the script with the script editor. When I tested this workaround, I confirmed that the value could be returned.
In this workaround, the following flow is used.
- Put the custom function of
=fetchCryptoPricesFromApi()
to a cell. - Retrieve the values from the API.
- Retrieve the values from the cell.
- Parse the value as JSON data.
The sample script of this workaround is as follows.
Sample script:
In this workaround, I use Google Spreadsheet. So please create a new Google Spreadsheet and open the script editor of Google Spreadsheet. And, copy and paste the following script. And, run main()
function with the script editor.
function fetchCryptoPricesFromApi() {
const data = {
"page": 1,
"rows": 10,
"payTypes": [],
"asset": "USDT",
"tradeType": "SELL",
"fiat": "LKR",
"publisherType": null,
"transAmount": "2600"
}
const payload = JSON.stringify(data)
const options = {
"method": "POST",
"contentType": "application/json",
"payload": payload
}
const response = UrlFetchApp.fetch('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', options);
return response.getContentText();
}
// Please run this function.
function main() {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange("A1");
range.setFormula("=fetchCryptoPricesFromApi()");
SpreadsheetApp.flush();
const value = range.getValue();
range.clearContent();
const prices = JSON.parse(value)['data'];
console.log(prices)
}