Setting an API key as a header for a XMLHttpRequest - javascript

Attempting to work with a Fortnite API (https://fortnitetracker.com/site-api) and it requires me to pass the API key in the header along with my requests. I've tried using .setRequestHeader but haven't had any luck.
function getInfo(){
var xhr = new XMLHttpRequest();
xhr.open('GET','https://api.fortnitetracker.com/v1/profile/pc/ninja',true);
xhr.onload = function(){
if(this.status == 200){
console.log("Worked");
} else {
console.log(this.status);
}
}
xhr.onerror = function(){
console.log("Request Error");
}
// Fake API Key
xhr.setRequestHeader("Authorization","12345678910");
xhr.send();
}
Hope someone can help and thanks for reading.

I think you are looking for this:
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
While you are getting to grips working with APIs, play with a REST client:
https://www.getpostman.com/
https://insomnia.rest/
They will help you see what these requests are supposed to look like. Basically, first figure out what the API needs with postman/insomnia and only after that you write your code.
Hope that helps!

For API Key authentication you would call it like this... .setRequestHeader "ApiKey", "MyKey".

Related

FEDEX API Oauth token - Missing or duplicate parameters. Please modify your request and try again. Javascript

The title says it all. I'm messing with the FEDEX API trying to get my token but it's not letting me. I have coded this in python and tried it in postman and both ways work fine, I'm new to JS and can't get it to work.
I get the error:
[{"code":"BAD.REQUEST.ERROR","message":"Missing or duplicate parameters. Please modify your request and try again."}]
What's wrong? Did I possibly spell something wrong or is the formatting wrong?
var input = {
"grant_type": "client_credentials",
"client_id": "*****",
"client_secret": "*****"
}
var data = JSON.stringify(input)
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://apis-sandbox.fedex.com/oauth/token");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
})

How to make a GET Request in XMLHttpRequest?

I'd like to make this GET request to GitHub API: https://developer.github.com/v3/repos/#list-all-public-repositories
I have no idea how to do this however. I've done some curling, but this is the first time I'll be using HTTP and API requests.
I've tried some online tutorials, but they don't exactly show how to make a specific GET request.
Here's what I have so far:
function reqListener () {
console.log(this.responseText);
}
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://api.github.com/");
oReq.send();
Instead of a JSON with Repository information from GitHub, I'm getting the following:
{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}
Edit: I've been able to get the first page, but I'd like to keep iterating through the pages. I don't understand the docs on how to do this. So far my code is this:
<script type="text/javascript">
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
console.log("Something went right!");
var json_results = JSON.parse(xhr.responseText);
json_length = Object.keys(json_results).length
var str = "";
for(var i = 0; i < json_length; i++)
{
str += JSON.stringify(json_results[i].description) + "\n";
}
document.getElementById('api-content').textContent = str;
}
else if(xhr.status == 404)
{
console.log("404 NOT FOUND!");
}
else
{
console.log("Something went wrong!");
}
}
};
xhr.open("get", "https://api.github.com/repositories", true);
xhr.send();
</script>
Try this:
function reqListener (response) {
console.log(response);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://api.github.com/repositories");
oReq.send();
Please refer to the documentation for proper usage of Github API.
XMLHttpRequest get works fine here, it is the URL which you are making the request.
Check github api docs to get the link and params required for what you need.
https://developer.github.com/v3/
Making a GET request to https://api.github.com/ does NOT give you result of: a JSON with Repository information from GitHub. You'll get a page showing a JSON of URLs to the relevant pages / information.
solution:
Instead of a JSON with Repository information from GitHub, I'm getting the following:
{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}
Decide which "Repository information" you want and get it from the above (JSON) listed URLs.
For example: (if Github user is: VCone)
"user_url": "https://api.github.com/users/{user}" means go to URL: https://api.github.com/users/VCone.
"user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}" means go to URL: https://api.github.com/users/VCone/repos.
or can be https://api.github.com/users/VCone/repos?type=xxxx,sort=xxxx,page=xxxx
etc.

Cross Domain access to USPS API

I am trying to make a CORS request to USPS website with jquery, I have gotten it to work on my work pc, with internet explorer only for some reason. and I get a CORS error on the newer version of IE and also Firefox and Chrome.
In a question I wasn't allowed to comment on due to not having a rep, they suggested sending it to a server first then making the request instead of from the browser, Can somebody explain this to me? How can I host a server with javascript, I simply need to use this API to get tracking information and this stupid CORS restriction is a pain in my rear every time I try to do something like this.
Please help.
function sendTrackingRequest(x) {
var requestURL = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML="
var request = new XMLHttpRequest();
request.open( "GET", requestURL + trackNumberToBeTracked, true);
// various sanitizations should be employed on the backend when dealing with user input
request.responseType = "text/xml";
request.setRequestHeader( "Content-Type", "xml" );
request.addEventListener( "readystatechange", function() {
if ( request.readyState == 4 ) {
if ( request.status == 200 ) {
// process response
var trackingStatus = request.response
showResult(trackingStatus);
console.log(trackNumberToBeTracked);
} else {
alert("error")
}
}
}, false );
request.send();
}
});
Okay everyone.
Please bear with me I have made a huge beginner mistake and figured out what was wrong with Slakes help.
So in my code, I had a function with a similar name which was a .response not defined. I got this error after I listened to the first helper who said a contenttype was not necesarry for a Get request which he was right after further research.
After i removed all the bad functions which i was testing, I finally got my response to work. here is my code
$(document).ready(function() {
$('#trackButton').click(function() {
var enteredNumber = $('#trackingNumbers').value;
var trackNumberToBeTracked = '<TrackRequest USERID="648FOOTL0638"> <TrackID ID="9405510200839104436417"></TrackID></TrackRequest>'
sendTrackingRequest();
function sendTrackingRequest(x) {
var requestURL = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML="
var request = new XMLHttpRequest();
request.open( "GET", requestURL + trackNumberToBeTracked, true);
// various sanitizations should be employed on the backend when dealing with user input
request.addEventListener( "readystatechange", function() {
if ( request.readyState == 4 ) {
if ( request.status == 200 ) {
// process response
var trackingStatus = request.response
alert(trackingStatus);
console.log(trackNumberToBeTracked);
} else {
alert("error")
}
}
}, false );
request.send();
}
});
Here is the code that was below it, giving me the error after I took out set header type (which solved my CORS issue as POST requests are not allowed on the api)
function showResult(request) {
var xmlDoc = request.response.documentElement;
removeWhitespace(xmlDoc);
var outputResult = $("#BodyRows");
var rowData = xmlDoc.$("#Employee");
addTableRowsFromXmlDoc(rowData,outputResult);
};
});

Any way to make AJAX calls to Gmail API without going through JS library?

A simple guide to making a GET request to get a user's messages through Gmail API can be found here.
But the way we are instructed to do the request is in the following manner:
function getMessage(userId, messageId, callback) {
var request = gapi.client.gmail.users.messages.get({
'userId': userId,
'id': messageId
});
request.execute(callback);
}
Is it possible to make the request using the good ol' XMLHttpRequest object on the client side? If so what parameters should be passed into the call?
I have tried this:
var getMessages = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
console.log(xhr.responseText);
}
xhr.open( "GET", "https://www.googleapis.com/gmail/v1/users/me/messages", true );
xhr.send();
}
But I get a 401, even after authenticating.
As it states in this answer, you should pass the access token as a query parameter with the name access_token, or prefix the authorization header value with "Bearer", like so:
xhr.setRequestHeader("authorization", "Bearer " + userToken.access_token);

Basic Authentication Using JavaScript

I am building an application that consumes the Caspio API. I am having some trouble authenticating against their API. I have spent 2-3 days trying to figure this out but it may be due to some understanding on my end. I have read countless articles on stackoverflow post and otherwise but have not solved the issue. Below is a code example of my solution based on what i have looked at and i am getting a 400 Status code message; What am i doing wrong here? (Please provide well commented code example and i would prefer to NOT have links posted here referencing other material as i have looked at these extensively. Thanks!):
Some references i have looked at:
1) Pure JavaScript code for HTTP Basic Authentication?
2) How to make http authentication in REST API call from javascript
I would like to use this authentication method as described by caspio below:
As an alternative to including credentials in the request body, a client can use the HTTP Basic authentication scheme. In this case, authentication request will be setup in the following way:
Method: POST
URL: Your token endpoint
Body: grant_type=client_credentials
Header parameter:
Authorization: Basic Basic authentication realm
Below are my Javascript and HTML code.
JavaScript:
var userName = "clientID";
var passWord = "secretKey";
function authenticateUser(user, password)
{
var token = user + ":" + password;
// Should i be encoding this value????? does it matter???
// Base64 Encoding -> btoa
var hash = btoa(token);
return "Basic " + hash;
}
function CallWebAPI() {
// New XMLHTTPRequest
var request = new XMLHttpRequest();
request.open("POST", "https://xxx123.caspio.com/oauth/token", false);
request.setRequestHeader("Authorization", authenticateUser(userName, passWord));
request.send();
// view request status
alert(request.status);
response.innerHTML = request.responseText;
}
HTML:
<div>
<div id="response">
</div>
<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />
After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:
var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint
var request = new XMLHttpRequest();
function getToken(url, clientID, clientSecret) {
var key;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/json");
request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
request.onreadystatechange = function () {
if (request.readyState == request.DONE) {
var response = request.responseText;
var obj = JSON.parse(response);
key = obj.access_token; //store the value of the accesstoken
token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
}
}
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);
If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;
NOTE: encodedParams is NOT used in this example but was used in my solution.
Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application
function CallWebAPI() {
var request_ = new XMLHttpRequest();
var encodedParams = encodeURIComponent(params);
request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
request_.setRequestHeader("Authorization", "Bearer "+ token_);
request_.send();
request_.onreadystatechange = function () {
if (request_.readyState == 4 && request_.status == 200) {
var response = request_.responseText;
var obj = JSON.parse(response);
// handle data as needed...
}
}
}
This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...
Today we use Bearer token more often that Basic Authentication but if you want to have Basic Authentication first to get Bearer token then there is a couple ways:
const request = new XMLHttpRequest();
request.open('GET', url, false, username,password)
request.onreadystatechange = function() {
// D some business logics here if you receive return
if(request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
}
}
request.send()
Full syntax is here
Second Approach using Ajax:
$.ajax
({
type: "GET",
url: "abc.xyz",
dataType: 'json',
async: false,
username: "username",
password: "password",
data: '{ "key":"sample" }',
success: function (){
alert('Thanks for your up vote!');
}
});
Hopefully, this provides you a hint where to start API calls with JS. In Frameworks like Angular, React, etc there are more powerful ways to make API call with Basic Authentication or Oauth Authentication. Just explore it.
To bring this question up to date, a node.js solution (using node-fetch) would be as follows:
const auth = Buffer.from(`${clientId}:${clientSecret}`).toString("base64");
fetch("https://some-oauth2.server.com/connect/token", {
method: "POST",
body: "grant_type=client_credentials",
headers: {
"Content-type": "application/x-www-form-urlencoded",
Authorization: `Basic ${auth}`,
},
})
.then((response) => response.json())
.then((response) => {
console.log(response); //response.access_token is bearer token, response.expires_in is lifetime of token
});
Sensitive requests like this should be server-to-server, and keeping the credential details in the Header rather than QueryString means it's less likely to be visible in web server logs
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
change var to const for the username, password, token_, and key variables.

Categories