So I've a dumb problem who is ruining my day so far.
I'm actually developing a React/Node app for fun. My goal is to manage a project from a unique dashboard.
I'm hoping to upload files to a google drive folder from this dashboard. So I worked on the thing with the help of the documentation https://developers.google.com/drive/api/v3/simple-upload
So far I can manage to upload files directly by hitting the endpoint with a POST method:
await Axios.post(`https://www.googleapis.com/upload/drive/v3/files`, file, {
headers: {
Authorization: `Bearer ${data.accessToken}`,
'Content-Type': file.type
}
});
but problem comes when I try to update the file with the PUT method.
To explain quickly:
I want each file that I upload to be uploaded to a specific folder on my drive. So I tought I'll make 2 calls, one to set the metadata on my API side:
API side
And once it's done return the data to my client side to update the endpoint with the ID (and a put as mentionned in the documentation)
Client side
So my question is how to PUT on this upload endpoint ? Where do I specify the ID ?
If anyone knows it would be a great help !!!
Have an awesome day all of you !
Google Drive API v3 uses PATCH rather than PUT. Change PUT to PATCH and things should work fine.
Reference: https://developers.google.com/drive/api/v3/reference/#Files
Related
I'm a teacher and have been teaching myself enough code in order to use Apps Script. I have read about and somewhat understand the idea of OAuth and see in principle how it should be able to be used to connect the Zoom API and Sheets API in order to make an attendance taking app. However, I don't get how to do some of the basics. For example, what to put in the OAuth redirect URL when making my App. Or even how to call the Zoom API from Sheets. Can I even use Javascript in order to call it? I haven't found much online that doesn't assume the basic knowledge. Also, most of the stuff online uses JWT, but I want to be able to share it far and wide so I think I need OAuth. Anyone know of a guide or something I can use to get started?
Based on answer's suggestion, I got the following code to work on Postman. Not sure how to change it for Apps Script.
function myFunction() {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer eyJ0eXAiOiJKVMTIzNn0.9Ol6oPrmbzvby5ch5-okkl7FMRG465Nu_zM0MVd91Ig");
myHeaders.append("Cookie", "_zm_date_format=dd/mm/yy; cred=2AFAF4FB9881D6BE9A38BD86B63DF1CC");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
UrlFetchApp.fetch("https://api.zoom.us/v2/report/meetings/92672781820/participants?page_size=30", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
Note: Bearer changed and switched it to UrlFetchApp
I'm not familiar with the Zoom API, but in taking a quick read of the documentation it appears they support both public and private apps. If you are new to this, my recommendation would be to first create a private app using JWT and get it working for yourself; after that, you can create a public app and employ OAuth so that others can install it. If you want to stick with Apps Script, you can look into the Google Apps Script OAuth library.
After you create your app within Zoom and select JWT, it will provide you with an api key as well as app secret for your app - these are the credentials you will use in your API requests. Check out their documentation for how to make simple requests to the API using your credentials.
If you are new to APIs in general, a good place to start is to download Postman. This will enable you to test your API requests using your credentials and confirm everything is working. After you have a working request created in Postman, you can click on 'code' on the right and it will generate the Javascript code you can use to make calls to the Zoom API within Apps Script. Use Javascript - Fetch as it's the most similar to Apps Script's own UrlFetchApp class. You will have to make some minor modifications to the pasted code from Postman to get it working in Apps Script.
For writing attendance to the Google Sheet, there should be some examples online of how to parse a JSON response from an API, push it to an array, and then setValue() within the Sheet. Hopefully the above is enough to get you started.
I am new to API usage. I have properly managed to utilize Google Page Insights V.5 API through javascript code, but I cannot for the life of me succeed in doing so for GTMetrix. It seems the only information relating to GTMetrix API & Javascript is a link to the RapidApi website. I simply wish to achieve the same simple retrieval of data from GTMetrix as I have from Google. Is this possible?
Am I simply structuring my request incorrectly when I set it as:
https://gtmetrix.com/api/0.1/?login-user=myemail#email.com&login-pass=MyRanDomApIKeY&location=2&url=https://sitetotest.com
Because when I set my Google Page Insights Request URL as the following it works.
https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://websitetotest.com&category=performance&strategy=desktop&key=MyRanDomApIKeY
The below code works for Google Page Insights and I am even able to retrieve JSON data in a browser window with a URL such as:
<div id="firstmetric"></div>
<br>
<div id="domSize"></div>
<button>Click Me</button>
<script>
$('button').click(function(){
var baseUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=";
var fieldUrl = "https://websitetotest.com";
var trailing = "&category=performance&strategy=desktop&key=MyRanDomApIKeY";
$.getJSON(baseUrl + fieldUrl + trailing, function(data){
console.log(data);
var item = data.lighthouseResult.categories.performance.auditRefs[0].weight;
var domSize = data.lighthouseResult.audits['dom-size'].displayValue;
$("#firstmetric").html( item );
$("#domSize").html( domSize );
});
});
I truly need it spelled out for me because anything less is going to lead me to ask follow up questions and put us in a tail spin. :/
As a newbie, JSFiddle has been a life saving resource for testing and trying, breaking, and building in my learning process. If it wouldn't be too much to ask for, a fiddle would help me get my brain around things.
The parameters that you are using: login-user and login-pass refer to HTTP authentication on the page you are analyzing (as in, GTmetrix will pass these parameters on your analysis) not your GTmetrix API credentials.
The authentication used for the GTmetrix API is your e-mail for the username and your API key as the password, as pointed out by the API docs.
Another thing to keep in mind is that GTmetrix will not allow you to do API calls through your web application frontend, since they disallow CORS requests. If you do it through your Web application on a normal website, you would be exposing your GTmetrix API key, which is probably not a good idea.
So, you would then do it through your backend code. For example if done through Node JavaScript:
fetch("https://gtmetrix.com/api/0.1/locations", {
headers: new Headers({
"Authorization": 'Basic ' + btoa("[YOUR E-MAIL]" + ":" +"[YOUR API KEY]"),
}),
}).then(res => res.json())
.then(response => console.log(response));
would print me the array of locations.
Note that whichever backend code you choose, you need to add the basic authorization header request for you API call and encode it properly (that is what the btoa function call does).
I can't for the life of me figure this out, it seems like it should be straight forward but it's just not clicking.
I have an ES6 app that I created using create-react-app. I've got all the templates and layouts set up for the project and came to trying to pull in data from an API that I want to sit inside the app - like a botched MVC where React handles the views and I run the models and controllers in PHP.
So I have a function in one of my components that I want to fetch some data. I use the fetch() function (I know this isn't yet compatible with a number of browsers but that's a problem for another day) to fetch a relative path from the component to the model I want to load, however the fetch function treats my path as a call to the base URL followed by the request. So with the site running on localhost:3000, I run the following code in my getData() function...
let test = fetch('../models/overall-stats.php').then(function(response) {
console.log(response);
return response;
});
...the URL that fetch hits is then http://localhost:3000/models/overall-stats.php which simply resolves back to the index.html file and loads the app, rather than the PHP file I'm requesting.
If I need to hit that PHP file to get my data, am I wrong in using fetch? Or am I just using it incorrectly? If I shouldn't be using fetch what's a better approach to this problem I'm having?
When I run this on an apache server (after building and deploying) I can get the fetches to work fine (apache recognizes the structure of the URL and hits it as I am expecting) and I hit the file no issues, but I need to be able to work in a local development environment and have the same functionality. The app will end up being deployed live on an apache server.
Any help would be greatly appreciated.
I knew after sleeping on this it would be very straight-forward... I simply had to move my models and controllers into the public directory for them to be accessible. I'll be putting in authentication to the models so that they can't be hit directly, but only through GET requests.
Why don't you just use something like ${baseUrl}/models/... ?
Also for solving browsers problem with fetch you can import the Polyfill or simply use axios (my choice)!
Maybe you can try to use ajax to get or post the data from server, just like this:
$.ajax({
url: '../models/overall-stats.php',
data: {
},
type: 'GET',
dataType : 'json',
success : function(res){
let obj = parseJSON(res)
}
})
or add this on top in your php file because the CORS :
header('Access-Control-Allow-Origin: *');
I am trying to download a file from Google Drive to my harddrive. The entire authentication is done in JavaScript and I am receiving a response from the server:
request = gapi.client.drive.files.get({'fileId': id});
request.execute(function(resp) { ........ }
I have the correct scope in order to be allowed to download files:
https://www.googleapis.com/auth/drive
Also the request above is returning me a downloadUrl.
I am trying to send the downloadUrl to PHP, but the download process is failing with a 401 error.
Any suggestion? I have tried to download the file directly in Javascript, but I didn't find a good solution yet.
Thanks and let me know if you have any question.
It is my first question here since this one is killing me :D
Is this a public file or a private file? Are you sending the right auth token to GDrive within PHP? Are there any other warnings/errors along with the 401?
401 with the GDrive API means that you are providing invalid credentials. You must not be supplying the right auth within PHP, or at least not the same auth as you did with JS.
Thank you everyone for your help. This topic help me a lot :
Newbie Google Drive API (PHP) confusion - what guide/library to use?
The problem was indeed auth in PHP, or better, the lack of it.
I am working on html & js in which i display yahoo finance stock in table format. The data get in csv. I want js directly read data from url
The url is http://ichart.finance.yahoo.com/table.csv?s=RIL.BO
The code i try which i get from stackoverflow is working in localhost url.
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://ichart.finance.yahoo.com/table.csv?s=RIL.BO", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
alert(allText);
}
}
}
Thanks
In order to get around the Cross Domain request restrictions put in place by the Same Origin Policy, you need an endpoint that allows you to do a JSONP request or that has enabled CORS. Unfortunately, the Yahoo! Finance endpoint has neither.
So, as James mentioned, you ned a middle man.
Usually, my recommendation for this is to use YQL, which allows you to quickly and easily build a server that sits between you and the finance site. In fact, they already have a Yahoo! Finance endpoint for exactly the data you're trying to get: link
However, as that can be unreliable, I also have a website scraper that I've used in various projects. It's hosted on Heroku and allows you to fetch almost any content from any site. I don't recommend using it for high volume projects, but for occaisional data fetches it's great. In your case, you would use it like this:
http://websitescraper.herokuapp.com/?url=http://ichart.finance.yahoo.com/table.csv?s=RIL.BO&callback=jsCallback
Edit: ichart.finance.yahoo.com has been deprecated, so this fails. Keeping it here for reference
Now that you have that out of the way, I recommend using jQuery and the csv-to-array plugin:
jQuery.getJSON('http://websitescraper.herokuapp.com/?url=http://ichart.finance.yahoo.com/table.csv?s=RIL.BO&callback=?', function (csvdata) {
console.log(csvdata.csvToArray());
});
Also, if you want to launch your own middle man, you can use the website-scraper that I've built. The source code is on GitHub and it's released under the MIT license.
You are trying to do a cross domain request so its being blocked.
You will need to write a server side script to fetch the data for you.