I've request a API key to get the users playlist. All my code works, but the only problem is that the key block or expires to fast. I use this code:
$.ajax({
url: "https://api.spotify.com/v1/users/" + $("#gebruiker").val() + "/playlists",
headers: {
Authorization: "Bearer " + my key
},
Host: "api.spotify.com",
Accept: "application/json",
type: "GET",
success: function (data){
//code
},
error: function (data) {
//code
}
});
When blocks or expires the API key from Spotify and what can you do about this?
Access tokens are deliberately set to expire after a short time, after which new tokens may be granted by supplying the refresh token originally obtained during the authorization code exchange. As explained in the https://developer.spotify.com/web-api/authorization-guide/
Related
I'm trying to delete my vimeo video by using AJAX request but its always returning 204 status code, and video is not deleting from account. Here is code example.
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: "post",
url: "https://api.vimeo.com/me/videos",
headers: {
"Authorization": "bearer xxxxxxxxxxxxxxx"
},
data: {
url: "https://api.vimeo.com/me"+videoID,
method: "DELETE"
},
dataType: "json"
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
Can anyone please suggest some changes required for this?
Thanks in advance
You are sending
a HTTP POST
to the URL https://api.vimeo.com/me/videos
with the Bearer token as a header
Note that it should be Bearer <token> (uppercase B), not bearer <token>.
with a data packet that contains another URL and HTTP method.
But according to the Vimeo API docs to Delete a Video, the request should be
DELETE https://api.vimeo.com/videos/{video_id}
with a note:
This method requires a token with the "delete" scope.
A jQuery ajax request should look something like this if the bearer token is correct:
$(".js-delete").click(function(){
var videoID = $(this).data("target");// /videos/2332
$.ajax({
type: 'DELETE',
url: 'https://api.vimeo.com/videos/' + videoID,
headers: {
"Authorization": "Bearer xxxxxxxxxxxxxxx"
},
success: function(response){
console.log(response); //will print the whole JSON
},
error: function(){
console.log('Request Failed.');
}
});
});
You should be able to test this request using https://www.getpostman.com/ to verify the request and bearer token works outside of your CF app.
I've been going through the app authorization steps here https://developer.microsoft.com/en-us/graph/docs/authorization/app_authorization, but can't seem to get the request to work. I consistently get errors saying
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access."
This seems weird as I am including that header.
$.ajax({
type: "POST",
url: url,
crossDomain: true,
data: {
'refreshToken': refreshToken,
'client_id': clientId,
'client_secret': clientSecret,
'redirect_uri': redirect_uri,
'resource': resource
},
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', "*");
xhr.setRequestHeader('Access-Control-Allow-Methods', "*");
xhr.setRequestHeader('Access-Control-Allow-Headers', "*");
},
success: function (data, status, headers, config) {
callback(data);
},
error: function (data, status, headers, config) {
console.log('Error getting access token from Microsoft Graph: ' + status + " " + JSON.stringify(data));
}
});
You are using a wrong OAuth2 flow. You should not use the Authorization grand code flow in browser applications, because you cannot keep the client secret safe and the tokens get to the server when a browser requests the redirect URL (the tokens are not in the hash # part of the URL).
That's why Microsoft API doesn't support XHR access to the /token endpoint (by omitting the CORS response headers).
You could consider using the Implicit flow, which is designed for usage in browsers, keeps the tokens safe and doesn't require a client secret.
I'm got the pluggin Postman for Chrome. I'm just wondering how I would get Postman to call my web API.
Current, I'm using this AJAX call written in Javascript:
alert("Getting security token");
// Do AJAX call to get security token:
$.ajax({
url: [security token url],
type: "POST",
headers: {
Accept: "application/json"
},
ContentType: "application/x-www-form-urlencoded",
data: {
grant_type: "password",
username: [username],
password: [password]
}
}).done(function(data)
{
var accessToken = data.access_token;
alert(accessToken);
alert("Getting json string.");
// Now that we have access token, send it along with the request for the json string:
$.ajax({
// meta data sent as URL parameters:
url: [url to get json string]
type: "GET",
headers: {
Authorization: "Bearer " + accessToken // access token
},
contentType: false,
processData: false
}).done(function(data)
{
$("#jsonDiv").html(data);
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
What would I have to do in Postman to accomplish the equivalent of this?
Thanks
There are a few ways to achieve this, but here are some steps to get you started. Create two 2 APIs:
The first to call the "security token url" with the POST method.
Add the header:
Accept: application/json
Then under body, select x-www-form-urlencoded and then add the following keys (and their appropriate values):
grant_type : password
username :
password :
Off the top of my head I think the password grant_type also requires client_id and client_secret, but I don't see that in your code above so maybe you don't need it.
If you hit send you should get an access token back.
In your second API, set the method to GET and supply the appropriate URL. Then in the headers add:
- Authorization : Bearer
If you want to get fancy you can use the test tab to write the access token to an environment variable and then use the result in your second call.
You don't need to get a new access token for each call however so you can just keep using the same token until it expires.
Sorry if you already knew how to do this, I couldn't tell your level of expertise from your question. Hope this helps.
I need to include a header with a refresh token in an ajax call to the YouTube api. I am trying to send a delete request, to delete a movie I have on my account. This is my ajax call that fire on button click
jQuery.ajax({
type: 'DELETE',
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your requst');
}
});
I am receiving a 401 (unauthorized) erorr on return and it seems that I need to include my access token in the call. I was playing around with the google api playground looking at the request and response and this is what shows as the 'Request' being sent out
DELETE https://www.googleapis.com/youtube/v3/videos?id=3242343&key={YOUR_API_KEY}
Authorization: Bearer "access token"
X-JavaScript-User-Agent: Google APIs Explorer
Now from that request it looks like the there are headers that are being sent with the request, which hold the access token. This must be why I am getting a 401 error. How can I include those headers into my ajax request, so that my access token is passed along with the request? Thanks
I was able to pass along a header using this code below:
jQuery.ajax({
type: 'DELETE',
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID +'&key=api_key_here',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer access_token_here');},
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your request');
}
});
You can use beforeSend method and request.setRequestHeader. Take a look at the official documentation here.
P.S. should I post it as a comment?
Try add the paramenter data.
jQuery.ajax({
type: 'DELETE',
data: 'key=' + {YOUR_API_KEY},
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key=904907387177-qe517sq5dmmpebckjbmrhv4gvac9e2d1.apps.googleusercontent.com',
success: function() {
alert('your video has been deleted');
},
error: function() {
alert('error processing your requst');
}
});
I'm trying to authenticate users from Trigger.io, ideally via Facebook.
I authenticate the user via Facebook (using the Parse Facebook module), and pass their access token, acess expiry date, and facebook Id to my call to Parse.
It is here things go wrong. Whenever I try and post this data via Ajax to the Parse REST API, I get an error in my forge/Trigger console reading:
{ type: 'EXPECTED_FAILURE', content: '{"code":107,"error":"This
endpoint only supports Content-Type: application/json requests, not
application/x-www-form-urlencoded."}', statusCode: '400', message:
'HTTP error code received from server: 400' }
The code I used to try and post this data is...
function auth(facebookId,accessToken,expirationDate) {
forge.logging.log('auth started');
forge.request.ajax({
url: 'https://api.parse.com/1/users',
headers: {
'X-Parse-Application-Id': config.parseAppId,
'X-Parse-REST-API-Key': config.parseRestKey,
'Content-Type': 'application/json'
},
type: 'POST',
dataType: 'json',
data: {
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
},
success: function (data) {
forge.logging.log('auth finished 1');
forge.logging.log(data);
},
error: function(error){
forge.logging.log('auth finished 2');
forge.logging.log(error);
}
})//success
} //auth
I can't figure out how to send this as a JSON object/ in the correct format. If anyone has any ideas they'd be much appreciated. Thanks. Josh.
Whenever the data option passed to forge.requests.ajax is an object like in your example, what actually gets posted is a query string that represents the object. The contentType option merely allows you to set the Content-Type header, it does not effect how objects are encoded for the request.
However if the data option is just a string, then this string is used as the body of the request. You can generate a JSON string to use as the body using JSON.parse like so:
forge.request.ajax({
...
contentType: 'application/json',
data: JSON.stringify({
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
})
});