I'm using googles drive API to download files of spreadsheet type. This works just fine except for when I try to download it in text/csv.
Is should be supported according to this page:
https://developers.google.com/drive/v3/web/manage-downloads
So this code works fine:
var request = gapi.client.drive.files.export({
'fileId': fileId,
'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
request.then(function(response) {
console.log(response);
}, function(err) {
console.log('Error');
console.log(err.result.error);
});
This code doesn't:
var request = gapi.client.drive.files.export({
'fileId': fileId,
'mimeType': 'text/csv'
})
request.then(function(response) {
console.log(response);
}, function(err) {
console.log('Error');
console.log(err.result.error);
});
The error I get from the server is:
domain: "global"
message: "Internal Error"
reason: "internalError"
Does anyone know what could be the reason for this?
This is a known issue with the Drive API v3, and it has been raised with the engineering team. Please follow this issue for updates.
Related
What I want to do is make a curl request which has an authorization token as a header and then I want to save the file in the local directory.
I am trying to use request function trying to achieve that but don't have much success of it.
it('Testing something', () => {
cy.request({
method: 'GET',
url: 'http://google.com/request',
auth: {
bearer: token
},
encoding: 'binary'
}).then((response) => {
//Validate the response
});
});
const options = {
url: `http://google.com/request/download`,
headers: {
'Authorization': `Bearer token`
},
method: 'GET'
};
const result = https.get(options, response => {
if(response.statusCode == 200){
const fileStream = fs.createWriteStream(destinationFolder);
request(response.request).pipe(fileStream);
}
});
});
Problem: When I run above code the file is not downloaded in the destination folder. I just want to download the file and that will make my test complete. I can download the file using curl request. Is there a way that we can mimic curl request in cypress test.
Note: This is a part of cypress test.
Well I figure it out how to acheive it, I am not sure if it is a right approach or not but following is my solution.
I used location in my curl request in order to download the file.
In order to make a curl request from cypress, I used cy.exec :
cy.exec{'curl request', (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
I'm trying attach an image using the bot emulator tool and sending this image off to the microsofts customvision api, the issue I'm having is that I get
{ Code: 'BadRequestImageFormat', Message: '' }
back from custom the custom vision api call.
I'm using the the request module from npm to handle the calls
// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'xxx',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/octet-stream',
'Prediction-Key': 'xxx'
},
body: session.message.attachments[0]
}, function(error, response, body){
console.log(body);
});
}
});
I believe that I may be sending the wrong format through to custom vision however I have been unable to figure it out as of yet.
I replicated your issue and it looks like the problem is your 'Content-Type'. You're attempting to pass JSON in your request, but setting the content-type as octet-stream. See my modified code below:
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'https://northeurope.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'Your API Key...'
},
body: session.message.attachments[0]
},
function (err, response, body) {
if (err) return console.log(err)
console.log(body);
});
}
});
When I run this, I get the error InvalidImageUrl which is to be expected as it's looking for a content on localhost. You could get round this by exposing your localhost using Ngrok.
Previously I was using the Dropbox API V1 within my web app to upload files my dropbox account. Please note that the app uses only one dropbox account (mine) to upload files.
So Previously:
I created an app on the dropbox developers console
Generated my token from the developers console
Hard coded that token into my server to upload all file to a specific folder within my Dropbox.
This worked perfectly before but as the dropbox API v1 has been deprecated it does not work anymore.
Dropbox V1 Code:
function fileupload(content) {
request.put('https://api-content.dropbox.com/1/files_put/auto/my_reports/report.pdf', {
headers: {
Authorization: 'TOKEN HERE',
'Content-Type': 'application/pdf'
},
body: content
}, function optionalCallback(err, httpResponse, bodymsg) {
if (err) {
console.log(err);
}
else {
console.log("File uploaded to dropbox successfully!");
fs.unlink(temp_dir + 'report.pdf', function(err) {
if (err)
throw err;
else {
console.log("file deleted from server!");
}
})
request.post('https://api.dropboxapi.com/1/shares/auto/MY_reports/report.pdf' + '?short_url=false', {
headers: {
Authorization: 'TOKEN HERE'
}
}, function optionalCallback(err, httpResponse, bodymsg) {
if (err) {
console.log(err);
}
else {
console.log('Shared link 2 ' + JSON.parse(httpResponse.body).url);
}
});
}
});
}
Dropbox V2 Code:
function fileupload(content) {
request.post('https://content.dropboxapi.com/2/files/upload/my_reports', {
headers: {
Authorization: 'TOKEN HERE',
'Content-Type': 'application/pdf'
},
body: content
} ......... (rest of the code is similar to above)
Issue:
What I have tried does not work. I can't seem to upload a file to my dropbox account from within my app. I have tried re-generating my TOKEN from the Dropbox App console but no luck.
Can anyone tell me what am I doing wrong?
Update:
I updated my code to similar structure for v2 of the API but still unable to resolve it.
request.post('https://content.dropboxapi.com/2/files/upload/', {
headers: {
Authorization: 'Bearer TOKEN',
'Dropbox-API-Arg': {"path": "/Homework","mode": "add","autorename": true,"mute": false},
'Content-Type': 'application/pdf'
//'Content-Type': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
},
body: content
} .... similar code
I encourage you to use existing nodejs dropbox packages, which hides abstraction of an authentication process, etc. under the hood.
Check official dropbox-sdk-js or try my tiny package dropbox-v2-api. Quick example:
const dropboxV2Api = require('dropbox-v2-api');
//create session
const dropbox = dropboxV2Api.authenticate({
token: 'TOKEN HERE'
});
//create upload stream
const uploadStream = dropbox({
resource: 'files/upload',
parameters: {
path: '/dropbox/path/to/file.txt'
}
}, (err, result) => {
// upload completed
});
//use nodejs stream
fs.createReadStream('path/to/file.txt').pipe(uploadStream);
My recommendation is also to use a SDK which abstracts over authentication. CloudRail for Node.js could be very useful here. It's quite easy to use and works for other providers like OneDrive as well.
const cloudrail = require("cloudrail-si");
const service = new cloudrail.services.Dropbox(
cloudrail.RedirectReceivers.getLocalAuthenticator(8082),
"[Dropbox Client Identifier]",
"[Dropbox Client Secret]",
"http://localhost:8082/auth",
"someState"
);
service.upload(
"/myFolder/myFile.png",
readableStream,
1024,
true,
(error) => {
// Check for potential error
}
);
Here is also a short article about the {“error”: “v1_retired”} issue.
I am trying to POST an image from my Node JS app to another REST API. I have the image in Mongo DB (as binary array data) that is read by Node JS and then is supposed to be POSTed to another API.
The problem I face is how do I send request data along with the image? I have this raw data (that is in JSON format) that should be POSTed along with image:
{"data":{"client":"abc","address": "123"},"meta":{"owner": "yourself","host": "hostishere"}}
I am required to do this using the 'request' module. I can use 'multer' if that helps better. But, I am stuck on how do I send the above request data along with the image stream. Below is my current code. Could you please help me finish it?
var options = {
host: 'hostname.com',
port: 80,
path: '/api/content',
method: 'POST',
headers:{
'Content-Type' : 'multipart/form-data'
}
};
var request = http.request(options, function(response) {
var str = '';
var respTime ='';
response.on('data', function (chunk) {
str = str.concat(chunk);
});
response.on('end', () => {
console.log('No more data in response.');
});
setTimeout(function() {
res.send(JSON.stringify(
{
'imageURL': IMG_URL,
'imageId': IMG_ID,
'body': JSON.parse(str)
}
));
}, 1000);
});
request.on('error', (e) => {
console.error('**** problem with request: ', e);
});
request.write(image.IMG_STR); //image.IMG_STR is the binary array representation of the image.
request.end();
UPDATE: 06/06/2017
So, I happened to talk to the REST team that provides the end point and found out that the data should be sent in the following specific format. Below is a snapshot of the request that succeeded. Could someone help me with the Node code that I should use? I have tried form-data package but have been getting the same error:
if you have control over "the other API" too, you could include the image as base64 representation of the binary data in the post-body (and decode it on the API side)
answer to the update 06/06/2017:
according to the screenshot the API requires multipart/formdata.
such requests with the "request"-module are documented in https://github.com/request/request#multipartform-data-multipart-form-uploads
quick example (not tested):
var formData = {
Data: {data: {client: "abc" ...},
file: fs.createReadStream('testImage_2.jpg'),
};
request.post({url:'<YourUrl>', formData: formData}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
If you add the body to your request with the JSON data, you should be able to send it:
var options = {
host: 'hostname.com',
port: 80,
path: '/api/content',
method: 'POST',
headers:{
'Content-Type' : 'multipart/form-data'
},
body: {
"data": {"client":"abc","address": "123"},
"meta":{"owner": "yourself","host": "hostishere"}
}
};
What I don't understand is why you have a setTimeout with res.send when there is no res variable defined anywhere.
I want to get all public github repositories of given user from github.
I tried to make it with GET request I read from here. When i try it with curl or in the browser everything is fine, but when I run this code is gives me http 403 status code
var request = require('request');
request.get("https://api.github.com/users/:user")
.on('response', function (response) {
console.log(response.statusCode);
console.log(JSON.stringify(response));
});
I tried using this github api library, but couldn't work around the authetication
var GithubApi = require("github");
var github = new GithubApi({});
github.authenticate({
type: "oauth",
token: "GIT_TOKEN"
});
var getUsersRepos = function (user) {
github.repos.getAll({
username: user
}, function (err, res) {
res.forEach(function (element) {
console.log(`${element.name} - language: ${element.language} - issues: ${element.open_issues} - url: ${element.url}`);
}, this);
});
}
module.exports = {
getRepos: getUsersRepos
};
But when I enter my token I can get only my user information.
Any ideas what I am doing wrong or some better idea will be appreciated
The Github API requires requests to have a valid User-Agent header:
If you provide an invalid User-Agent header, you will receive a 403
Forbidden response.
Github requests that you use your GitHub username, or the name of your application, for the User-Agent header value:
var request = require('request');
options = {
url: "https://api.github.com/users/:user",
headers: {
"User-Agent": "tabula" // Your Github ID or application name
}
}
request.get(options)
.on('response', function (response) {
console.log(response.statusCode);
console.log(JSON.stringify(response));
});