How to use GTMetrix Api using Javascript? - javascript

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).

Related

How to fix SoundCloud player since API updates?

I've been working with this code that builds a custom SoundCloud player from hrefs to the tracks via their API:
https://codepen.io/nicholaspetersen/pen/yyVYMY
It was working fine until SoundCloud changed the way their API authorises as described here:
https://developers.soundcloud.com/blog/security-updates-api
They said in that post:
Currently, to access the public resources of the platform, server-side integrations with our API only require a client_id in the URL’s query parameter. We’ll be strengthening our authorization here by making all public resources on the API only accessible to apps that have been authorized with the client_credentials grant. This will enable the app to capture both the access_token and the refresh_token to then fetch the resources from the API. Please note that the use of client_id will be deprecated and deleted soon (from July 2021). Developers should provide the Authentication header for all their requests to the SoundCloud API going forward.*
So, my understanding from the above is that I need to update the Authentication header as currently the code above is authenticating using this code:
// convert a SoundCloud resource URL to an API URL
scApiUrl = function(url, apiKey) {
var resolver = ( secureDocument || (/^https/i).test(url) ? 'https' : 'http') + '://api.' + domain + '/resolve?url=',
params = 'format=json&consumer_key=' + apiKey +'&callback=?';
However, I'm completely stuck as to how to do that... can anyone take a look at the JS in that codepen and let me know what I should be doing to fix the issue? I thought it might involve updating the code above to include a callback URL, but then that blog post says the use of client_id is now deprecated.
Any help / pointers hugely welcome.
After the SoundCloud security updates, the playlist on my website also stopped working. It wouldn't load any of the tracks in my playlist. I did a lot of research, finally realizing that I would need to register an app on SoundCloud to get access to the API. This was not possible due to the app registration page being down since early this year and with no promises of it ever going back up. So, I needed to find an alternative. Which brought me to the Widget API page.
https://developers.soundcloud.com/docs/api/html5-widget
The Widget API allows you to externally control the widget that is embedded on your website through javascript. You set the width and height of the widget to 0 and it hides the widget. I tinkered with this on codepen this week and I am pleased that I now have a working playlist ready to be utilized on my website. See the link below.
https://codepen.io/mdcrowcodes/pen/eYEMyzY
enter code here

How to get started with an OAuth App for Zoom API connected to Apps Script

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.

How to POST an issue stub on GitHub using the GitHub API using the logged in user, without authentification keys?

Users of my web application are expected to provide bug reports as a GitHub issue, with a pregenerated title and body.
This works perfectly fine using GET for small bodies:
const title = getLastErrorTitle();
const body = getAllTheLogMessages();
window.open(`https://github.com/theuser/therepo/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}`);
If the user is logged in, GitHub presents the user with a new issue with the title and body already filled out, perfect. If not, GitHub prompts the user to log in and it works the next time.
However, if the body is too large, the GET request fails because the URL becomes too long.
After consulting the manual I tried doing the same with POST but I get a 404 from GitHub with the following test request (jQuery for brevity):
$.ajax({
type: "POST",
url: "https://api.github.com/repos/theuser/therepo/issues",
data: data = {title: "Test", body: "Test Body"},
});
My suspicion is, that the GitHub API was not designed with my use case in mind, but that POST always requires authentication and creates the full issue in one go, without letting the user change it beforehand like it is possible with GET.
How can I transfer the functionality of the GET method over to the POST method? I just want GitHub to present the user, that is currently logged in inside the browser, with a prefilled issue, without needing a token.
You can't. Otherwise, it would be a major CSRF exploit.
However, you can use OAuth authentication that will allow your application to use some features : https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/
Or simply, redirect the user to a new issue page (for exemple with a simple HTML link <a>) with some automatic content, using this pattern :
https://github.com/{theUser}/{theRepo}/issues/new?body={theContentYouWhant}&title={theTitleYouWhant}
Example : https://github.com/CristalTeam/php-api-wrapper/issues/new?body=Hi,%20this%20is%20the%20body%20you%20want&title=Hello,%20this%20is%20a%20prefill%20issue
What I would suggest here is to generate a personal_auth_token at gihub and pass this token in the headers under Authorization field.
To generate personal_auth_token, login to github.com, go to settings -> developers settings -> Personal access tokens and generate one.
Pass this token in headers under Auhtorization: token. So in your AJAX request, it could look something like this:
$.ajax({
url: *yourUrl*
...
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', *token*));
},
});
One thing to note here is each of the developers POSTing to the repo will be requiring to generate their access token and you can't push this token on to a public Github repository because of obvious security breach. If you accidentally do so, the token is revoked immediately and you'll be required to create a new one.

facebook graph api node.js invalid appsecret_proof

this is my first post so please go easy on me!
I am a beginning developer working with javascript and node.js. I am trying to make a basic request from a node js file to facebook's graph API. I have signed up for their developer service using my facebook account, and I have installed the node package for FB found here (https://www.npmjs.com/package/fb). It looks official enough.
Everything seems to be working, except I am getting a response to my GET request with a message saying my appsecret_proof is invalid.
Here is the code I am using (be advised the sensitive info is just keyboard mashing).
let https = require("https");
var FB = require('fb');
FB.options({
version: 'v2.11',
appId: 484592542348233,
appSecret: '389fa3ha3fukzf83a3r8a3f3aa3a3'
});
FB.setAccessToken('f8af89a3f98a3f89a3f87af8afnafmdasfasedfaskjefzev8zv9z390fz39fznabacbkcbalanaa3fla398fa3lfa3flka3flina3fk3anflka3fnalifn3laifnka3fnaelfafi3eifafnaifla3nfia3nfa3ifla');
console.log(FB.options());
FB.api('/me',
'GET',
{
"fields": "id,name"
},
function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res);
console.log(res.id);
console.log(res.name);
}
);
The error I am getting reads:
{ message: 'Invalid appsecret_proof provided in the API argument',
type: 'GraphMethodException',
code: 100,
fbtrace_id: 'H3pDC0OPZdK' }
I have reset my appSecret and accessToken on the developer page and tried them immediately after resetting them. I get the same error, so I don't think that stale credentials are the issue. My
console.log(FB.options())
returns an appropriate looking object that also contains a long hash for appSecretProof as expected. I have also tried this code with a number of version numbers in the options (v2.4, v2.5, v2.11, and without any version key). Facebook's documentation on this strikes me as somewhat unclear. I think I should be using v2.5 of the SDK (which the node package is meant to mimic) and making requests to v2.11 of the graph API, but ??? In any case, that wouldn't seem to explain the issue I'm having. I get a perfectly good response that says my appSecretProof is invalid when I don't specify any version number at all.
The node package for fb should be generating this appSecretProof for me, and it looks like it is doing that. My other info and syntax all seem correct according to the package documentation. What am I missing here? Thank you all so much in advance.
looks like you have required the appsecret_proof for 2 factor authorization in the advance setting in your app.
Access tokens are portable. It's possible to take an access token generated on a client by Facebook's SDK, send it to a server and then make calls from that server on behalf of the client. An access token can also be stolen by malicious software on a person's computer or a man in the middle attack. Then that access token can be used from an entirely different system that's not the client and not your server, generating spam or stealing data.
You can prevent this by adding the appsecret_proof parameter to every API call from a server and enabling the setting to require proof on all calls. This prevents bad guys from making API calls with your access tokens from their servers. If you're using the official PHP SDK, the appsecret_proof parameter is automatically added.
Please refer the below url to generate the valid appsecret_proof,and add it to each api call
https://developers.facebook.com/docs/graph-api/securing-requests
I had to deal with the same issue while working with passport-facebook-token,
I finally released that the problem had nothing to have with the logic of my codebase or the app configuration.
I had this error just because I was adding intentionally an authorization Header to the request. so if you are using postman or some other http client just make sure that the request does not contain any authorization Header.

Twitter OAuth Pin based authorization 'oob' in Google Apps Script

I am trying to use Twitter Pin-based authorization in my Google Apps Script to eventually send tweets on behalf of other uses.
I freely admit that I don't relay know what I'm doing but I have read a lot of info on the internet and feel I have tried everything.
My current Google Apps Script JavaScript code:
var method = 'post';
var url = 'https://api.twitter.com/oauth/request_token';
var consumerKey = '[my consumer key]';
var ticks = '1422745454';
var nonce = '6826266';
var options = {
'method': method,
'oauth_callback': 'oob',
'oauth_consumer_key': consumerKey,
'oauth_nonce': nonce,
'oauth_signature': 'cIFeptE5HjHp7xrp%2BZt9xFhHox4%3D',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': ticks,
'oauth_version': '1.0'
};
var response = UrlFetchApp.fetch(url, options);
For testing I set the ticks just before each test run to the value here
The nonce is a random number between 111111 and 9999999 which is regenerated before each test run.
The oauth signature I have been generating with some c# code lifted from the linq2twitter project
I suspect the problem is the signature. I have read the twitter documentation on creating a signature and I think the C# code is doing it correctly but I am not sure.
The problem is that whatever I try I always get this error:
"Request failed for https://api.twitter.com/oauth/request_token returned code 401. Truncated server response: Failed to validate oauth signature and token (use muteHttpExceptions option to examine full response)"
I have been trying to find an example of Twitter Pin-based authorization in a Google Apps Script but have so far not found anything.
My attempts to translate examples in C#, PHP, etc. have also failed.
Please help.
Apps Script provides an Oauth API that works with UrlFetchApp, they even use twitter in their examples. Work with those if at all possible, troubleshooting signature generation is a real hassle.
https://developers.google.com/apps-script/reference/url-fetch/o-auth-config
https://developers.google.com/apps-script/articles/twitter_tutorial
If you absolutely must do it from scratch, the best approach is to get requests working with an existing library (like the c# one you mention), then work on getting your apps script to generate the exact same request.
I get the sense that is what you are doing now, so it may just be a matter of base64 encoding your Signature in the outgoing request:
https://developers.google.com/apps-script/reference/utilities/utilities#base64Encode(String)
Ultimately, it's very difficult to do the whole Oauth process manually in Apps Script. When I tried something like this from scratch about a year ago I ultimately gave up and used a Python application deployed to Google App Engine instead. I submit requests from Apps Script to the App Engine application, and the App Engine application handles Oauth and relays my requests on to the external service, before returning requests to my Apps Script. This approach comes with complications of it's own.

Categories