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.
Related
Here is my code
function notifyTeamMembersOfNewRequest(event) {
const response = event.values
console.log(`response values: ${response}`)
let payload = {
text: response,
channel: 'C04AZ4GT2UU'
}
requestSlack('POST', `chat.postMessage`, payload)
}
function requestSlack(method, endpoint, params) {
const base_url = "https://slack.com/api/"
const headers = {
'Authorization': "Bearer " + 'YOUR_SLACK_API_KEY',
'Content-Type' : 'application/json'
}
const options = {
headers: headers,
method: method
}
let request_url
if (method == 'POST') {
request_url = base_url + endpoint
options.payload = JSON.stringify(params)
} else {
request_url = base_url + endpoint + params
}
const response = UrlFetchApp.fetch(request_url, options).getContentText();
const json = JSON.parse(response)
return {
response_code: json.ok,
response_data: json
}
}
Basically I want it to send a new response on a form to a slack channel with the mentioned ID - however while on the executions tab it gives me the desired response; it doesn't send it to the slack channel. Can someone please help?
I have used quite a few Google searches however, no luck.
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)
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) => {
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),
},
});
I'm trying to make calls to Basecamp's new API through Google Apps Script. GET, I can do. POST, not so much.
Starting with the path
https://basecamp.com/xxxxxxx/api/v1/projects/xxxxxxx/todolists.json
My code:
var headers = {
'User-Agent' : BCuseragent,
'Authorization' : 'Basic ' + Utilities.base64Encode(BCuser + ':' + BCpass),
'Content-Type' : 'application/json',
'Accept' : 'application/json',
'validateHttpsCertificates' : false
}
function getBC(path) {
var url = BCurl + path;
var opt = {
'headers' : headers,
'method' : "GET"
};
var response = UrlFetchApp.fetch(url, opt);
return response;
}
function postBC(path, payload) {
var url = BCurl + path;
var opt = {
'headers' : headers,
'method' : "POST",
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, opt);
return response;
}
The payload I'm passing as a parameter:
{name: "foo", description: "bar"}
The getBC function works (200 OK), the postBC function returns a 403 error. Yet I am the owner of the project, and I've used curl and a Chrome REST client to confirm I can in fact POST new todolists to this project with the same authorization.
Obviously, my headers are malformed somewhere, but I can't see how.
This is a quirk of UrlFetchApp. You can't set the Content-Type using the general "headers" parameter, instead you must use the "contentType" parameter.
See the "Advanced Parameters" table here:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)