How to use an API Key for an Ajax call? - javascript

I am trying to include an API key for the first time from New York Times API ( http://developer.nytimes.com/) and use ajax to fetch news from it to populate a local website but I'm not seeing any results. I was told to Make sure your API key is set in the URL's query parameters but I'm not sure how to do it.
?api-key=your-key
Here is what I have done:
// Built by LucyBot. www.lucybot.com
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "111111111111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
I need to see the url in json format for various stories such as business, technology, etc and use them for an ajax call.

Try this I am getting data from this
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "11111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can also try like as follows
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
data: {
'api-key': '11111111111111111'
},
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Its not a good practice expose API Key directly in client-side context.
I strongly recommend to create an abstraction layer between the browser and the API.
The idea is target the AJAX request to one own backend action, like:
var url = "www.mydomain.com/api/articlesearch";
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
And inside the backend (/api/articlesearch) we place the request that target to NY Times, using the API Key
This way you get a more suitable code for javascript, keeping the responsibilities correctly distributed.
PS: If you want it even more safe, you can define the API Key using env variables. Here is an example made in Ruby (just for figure it):
# Inside ApisController
def articlesearch
response = RestClient::Request.execute(
method: :get,
url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
headers: {api_key: ENV['API_KEY']})
render json: response
end
Using this approach the API Key will also not be present in GIT repository :)

Well, you should try it this way. It should give you a result without cross-origin errors:
$.ajax({
type: 'GET',
url: 'http://api.nytimes.com/svc/search/v2/articlesearch.json',
data: {
'q': queryString,
'response-format': "jsonp",
'api-key': nytApiKey,
},
success: function(data) {
// passed function object for data processing
console.log(data);
},
error: function(err) {
console.log('error:' + err)
}
});

Related

How to make a REST API Request with Ajax and session token?

I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});

Github API v3: Update file not working (404)

I'm trying to update a file using the Github v3 api. Most of the documentation I could find was based on the older API. I want to utilize: https://developer.github.com/v3/repos/contents/#update-a-file
I first grab the file using:
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var jsonFile = data.content;
sha = data.sha;
var decodedJson = atob(jsonFile);
var parsedDecodedJson = JSON.parse(decodedJson);
parseData(parsedDecodedJson);
},
error: function(error){
alert.addClass('alert-danger').removeClass('hidden').html('Something went wrong:'+error.responseText);
}
});
Which works perfectly.
After editing the file, I try to update the file.
On my submit I post the following using jQuery:
var postData = {
"message": "Update",
"content": btoa(obj),
"sha": sha,
"branch":"gh-pages"
};
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'PUT',
data: postData,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log("Success!!!", data);
},
error: function(error){
console.log("Cannot get data", error);
}
});
All the variables contain the expected values. Regardless, I keep getting a 404.
I know the API more often than not returns a 404 instead of something like a 403 as stated here: https://developer.github.com/v3/#authentication But it makes debuggin nearly impossible in my opinion. I have no clue what I'm doing wrong here. Thanks!
The only way I was able to do it is to make the entire round trip.
I used a javascript Github API wrapper
Luckily I found this article in which the bulk of the work was already been done. Props to Illia Kolodiazhnyi.
In the end. I ended up with this:
Handler on top of github api plugin
Usage:
var api = new GithubAPI({ token: token});
api.setRepo(owner, repo);
api.setBranch(branch).then(function () {
return api.pushFiles(
'CMS Update',
[
{
content: JsonData,
path: path
}
]
);
}).then(function () {
console.log('Files committed!');
});

Jquery request always fails

I am currently using the dark sky forecast api https://developer.forecast.io/ to retrieve json object via jquery get request.the required url parameters format is (api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE") while the valid format with the parameters is:
https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115
inputting this url in your browser will show you a json object.
First thing i tried was a jquery get request :
$.ajax({
type: 'GET'
, data: ''
, url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115"
, success: function (data) {
alert("works");
}
, datatype: 'json'
, error: function (err) {
alert("Could not get forecast");
}
});
this is not succesful- it triggers the error function. i try again using a post request it doesnt work either.please help
This is a simple CORS issue which can be easily resolved by using jsonp datatype:
$.ajax({
url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115",
dataType: "jsonp",
success: function(data) {
console.log(data.latitude, data.longitude);
console.log(data.timezone);
console.log(data.daily.summary);
},
error: function(err) {
console.log("Could not get forecast");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<em>Loading . . .<em>

Is it possible to use conditions within an AJAX call to avoid duplicate code?

For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);

Cross Domain AJAX POST / HTTPS / Header Authentication?

I have to issues:
1) I've tried using JsonP, but can't get POSTing to work. Essentially, I'm trying to authenticate with an API, passing a Base64-encoded namevaluepair in the header over HTTPS.
2) How do I pass this key/value in the header? Any help would be appreciated! Here is an example of what I want, though this obviously doesn't work:
// where does this go?
var headerString = 'user=' + encodeURIComponent(username + ':' + password);
$.ajax({
type: "POST",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
success: function(data) {
},
error: function(data){
}
});
add headers to ajax call:
var headerObj = {'user': encodeURIComponent(username + ':' + password)};
$.ajax({
type: "GET",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
headers: headerObj,
success: function(data) {
},
error: function(data){
}
});
The best way to do this is probably through a server side proxy on your own domain.
See this page for tips.
This way you will be able to get the response from the other server

Categories