API request Google Apps Scripts - google-apps-script

I need to request information from api.I tried to make a request with UrlFetchApp.fetch and fetchAll.In both cases i got nothing.Here s my code:
var request1 = {
url: "https://seo-fast-audit.p.rapidapi.com/?url=" + url,
method : 'GET',
params: {url: 'https://docteurseo.fr/'},
headers: {
"x-rapidapi-host": "seo-fast-audit.p.rapidapi.com",
"x-rapidapi-key": "KEY"
}
};
let response = UrlFetchApp.fetchAll([request1])
(here i replaced key)
So what is my problem?Is that problem in async functions or am i requesting not correctly?
Here s API i am using
https://rapidapi.com/DocteurSEO/api/seo-fast-audit

If you want to convert the following javascript to Google Apps Script, Ref
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://seo-fast-audit.p.rapidapi.com/',
params: {url: 'https://docteurseo.fr/'},
headers: {
'x-rapidapi-host': 'seo-fast-audit.p.rapidapi.com',
'x-rapidapi-key': 'SIGN-UP-FOR-KEY'
}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
how about the following modification?
function myFunction() {
var url = "https://seo-fast-audit.p.rapidapi.com?url=" + encodeURIComponent('https://docteurseo.fr/');
var option = {
headers: {
"x-rapidapi-host": "seo-fast-audit.p.rapidapi.com",
"x-rapidapi-key": "KEY"
}
};
let response = UrlFetchApp.fetch(url, option);
console.log(response.getContentText())
}
In your script, params is not included in the object for fetch and fetchAll. And, I thought that in your situation, url is required to do the URL encode, and com/?url= is com?url=.
Note:
I think that the request of the above Google Apps Script is the same as the top of Javascript. But if an error occurs, please check your KEY again.
If an error of 403 forbidden occurs, the site might not be accessed from the Google side. I'm worried about this.
Reference:
fetch(url, params)

Related

Google Apps Script and Google Search Console API

I need to access datas from Search Console using Apps Script.
I tried a loads of things but nothing worked.
I'm using this doc : https://developers.google.com/webmaster-tools/v1/searchanalytics/query
Here are some things I tried :
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/webmasters https://www.googleapis.com/auth/webmasters.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); })}
function loadClient() {
gapi.client.setApiKey("YOUR_API_KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/searchconsole/v1/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); })}
function execute() {
return gapi.client.webmasters.searchanalytics.query({
"resource": {}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); })}
Other try:
function searchConsoleQuery() {
var service = getService();
var apiURL =
'https://www.googleapis.com/webmasters/v3/sites/[SITE_URL]/searchAnalytics/query';
var headers = {
'Authorization': 'Bearer ' + service.getAccessToken(),
'contentType':'application/json',
'startDate':'20019-10-01',
'endDate':'2019-10-10'};
var options = {
'payload': JSON.stringify(headers),
'method' : 'POST',
'muteHttpExceptions': true};
var response = UrlFetchApp.fetch(apiURL, options);
var json = JSON.parse(response.getContentText());
Logger.log(json)}
Modification points:
In your script, headers is used to payload.
'startDate' is 20019-10-01.
When these points are reflected in your script, it becomes as follows.
Modified script:
function searchConsoleQuery() {
var siteUrl = "###"; // Please set your site URL.
var service = getService();
var apiURL = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(siteUrl)}/searchAnalytics/query`;
var options = {
'method': 'POST',
'muteHttpExceptions': true,
'headers': { 'Authorization': 'Bearer ' + service.getAccessToken() },
'contentType': 'application/json',
'payload': JSON.stringify({
'startDate': '2019-10-01',
'endDate': '2019-10-10'
})
};
var response = UrlFetchApp.fetch(apiURL, options);
var json = JSON.parse(response.getContentText());
Logger.log(json)
}
Note:
In this modification, it supposes that Google Search Console API has already been enabled at API console and also siteUrl and your access token of service.getAccessToken() are the valid values for using the API. Please be careful about this. When I tested this modified script with my site URL, I confirmed that the values are returned without error. So, if an error occurs, please confirm the condition of API in your API console and your values again.
If no values are returned, please modify 'startDate': '2019-10-01' and 'endDate': '2019-10-10' and test it again.
References:
Search Analytics: query
fetch(url, params)

Send POST request in Google Apps Script with Headers and Body

I am trying to send a POST request in order to receive an Access Token in return.
The documentation is as follows:
Client Credentials
This is your first route to obtain an access_token to communicate with the API.
Route : POST https://api.helloasso.com/oauth2/token
Headers
Content-Type = application/x-www-form-urlencoded
Body
client_id = Your Client Id
client_secret = Your Client Secret
grant_type = client_credentials
Solution I tried
Based on this post, I tried the following code:
function qwe()
{
const url = 'https://api.helloasso.com/oauth2/token';
const headers = {
"client_id": "Your Client Id",
"client_secret": "Your Client Secret",
"grant_type": "client_credentials"
};
const options = {
'method' : 'post',
'contentType': 'application/x-www-form-urlencoded',
'headers': headers
};
const response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response);
Logger.log(data);
}
Upon running this, I get an error "Exception: Request failed for https://api.helloasso.com returned code 400. Truncated server response: {"error":"unauthorized_client","error_description":"client_id is not set"}".
I am a beginner, and would appreciate any help on this! Thank you in advance
Modification points:
In the case of UrlFetchApp, the default content type is application/x-www-form-urlencoded.
From your question and situation, I guessed that your Body might be required to be sent as form data.
If those points are reflected in your script, it becomes as follows.
Modified script:
function qwe() {
const url = 'https://api.helloasso.com/oauth2/token';
const data = {
"client_id": "Your Client Id",
"client_secret": "Your Client Secret",
"grant_type": "client_credentials"
};
const options = {
'method': 'post',
'payload': data
};
const response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText())
}
Note:
If you tested this modified script, when an error occurs, please show the detailed error message and provide the official document. By this, I would like to confirm it.
Reference:
fetch(url, params)
Need to make it stringify first
'payload' : JSON.stringify(data)

How can I add parameters in an HTML GET call using Electron.Net

I have the following function working from an Angular component (in an Electron application) using HttpClient:
var auth = "Bearer" + "abdedede";
let header = new HttpHeaders({ "Content-Type": 'application/json', "Authorization": auth});
const requestOptions = {headers: header};
const url = 'https://reqres.in/api/users?page=1';
this.http.get<any>(url, requestOptions).toPromise()
.then(response=> {
//...
alert(JSON.stringify(response));
});
}
Now, here is a call from the electron side which calls the same endpoint but without the Authorization and Content-Type in the header:
let buffers:any = [];
const { net } = require('electron')
const request = net.request({
method: 'GET',
url: 'https://reqres.in/api/users?page=1'})
request.on('response', (response) => {
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
buffers.push(chunk);
})
response.on('end', () => {
let responseBodyBuffer = Buffer.concat(buffers);
let responseBodyJSON = responseBodyBuffer.toString();
responseBodyJSON = responseBodyJSON;
})
})
request.end()
(This latter function is thanks to a poster replying here: In an Electron Application I am successfully making an HTTP GET request from an Angular component. How can I do the same thing from the Electron side?)
My question is, could anybody please advise\show me how to add in the Authorization and Content-Type Header info to this call so that it replicates what the Angular version does - i.e. by passing the requestOptions data in the GET call?
Thanks.
I have found it. I needed to add:
request.setHeader("content-type", "application/json"); request.setHeader("Authorization", auth);
before I call:
request.on('response', (response) => {

Requesting access token to Zoom API via Oauth - error 'missing grant type'

I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});

How can I send parameters through the fetch api?

I'm currently trying to export a file from the Google Drive API. However, I don't know how to pass the mimeType parameter correctly using fetch. I tried the code below:
function getFile (access_token) {
const fileUrl = "https://www.googleapis.com/drive/v3/files/" + imageID + "/export";
let fileRequest = {
method: "GET",
mimeType: 'image/png',
headers: new Headers({
Authorization: "Bearer " + access_token
})
}
fetch(fileUrl, fileRequest).then( response => {
return(response.json());
}).then( file => {
console.log(file);
});
The error I'm getting is:
Required parameter: mimeType
In normal circumstances:
You should attach the headers using the Headers class:
function getFile(token, id) {
const url = "https://www.googleapis.com/drive/v3/files/" + id + "/export"
const headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)
headers.append('Content-Type', 'image/png')
let options = {
method: "get",
headers
}
fetch(url, options).then(response => {
// do stuff with response
})
}
However:
As per the Files: export documentation:
Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB.
So images are not supported by this endpoint. You will need to use Files: get instead. You can do this simply by removing the '/export from the end of the URL.