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.
Related
This is how I setup my ajax with Bearer token for Authorization Header:
let headerParams = {
Authorization: "Bearer " + accessToken,
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
};
let url = "url.com";
$.ajax({
type: "GET",
url: url,
headers: headerParams,
success: function (data) {
},
error: function (error) {
},
});
However on the test server, we also use Basic Auth to access the site. How should I add both Basic and Bearer token in the ajax?
Below is the ajax that works when I only use Basic Authorization Header
let headerParams = {
Authorization: "Basic " + btoa(username + ": " + password),
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
};
let url = "url.com";
$.ajax({
type: "GET",
url: url,
headers: headerParams,
success: function (data) {
},
error: function (error) {
},
});
I tried adding the Bearer and Basic in headerParams like below:
let headerParams = {
Authorization: "Basic " + btoa(username + ": " + password),
Authorization: "Bearer " + accessToken,
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
};
But it does not really work since this will overwrite the previous Authorization. I also added Bearer in headerParams while the Basic auth in beforeSend callback, the same error 401 for missing basic auth and 500 in the backend since backend is unable to authenticate user. Most of the SO questions that I have read only uses one or the other.
You may try sending the header as:
Authorization: Bearer <accessToken>, Basic <btoa(username + ": " + password)>
It actually depends more on the server than the client and whether it accepts the multi value. So, please try it out.
According to the spec RFC7230, section 3.2.2, Field Order:
A sender MUST NOT generate multiple header fields with the same field
name in a message unless either the entire field value for that header
field is defined as a comma-separated list [i.e., #(values)] or the
header field is a well-known exception (as noted below).
A recipient MAY combine multiple header fields with the same field
name into one "field-name: field-value" pair, without changing the
semantics of the message, by appending each subsequent field value to
the combined field value in order, separated by a comma. The order in
which header fields with the same field name are received is therefore
significant to the interpretation of the combined field value; a proxy
MUST NOT change the order of these field values when forwarding a
message.
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.
My code can get an auth2.0 token...but the examples I've found don't show the final piece of taking a GET, provided here, and turning it into a working request.
Here is the specific URL from that link:
GET https://www.googleapis.com/drive/v3/files/fileId
Here is my AJAX call with the attempt at getting the token (that works) into a hardcoded fileId that I know my Google account has access to.
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer" + token);
},
// url: "https://www.googleapis.com/drive/v2/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI/permissions",
url: "https://www.googleapis.com/drive/v3/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI",
dataType: 'application/json',
processData: true,
success: function(msg) {
console.log('Got File Metadata: ' + msg) + console.log(msg);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Error: ' + errorThrown + ' / ' + textStatus) + console.log(jqXHR);
}
});
I don't understand how to include the token and the pages and pages of Google documentation do not include any examples of going this route.
I get "invalid credential" errors in the server response.
I don't want to use GAPI because I ran into invalid cookie issues running locally and my code is in a Chrome Extension and it isn't clear whether that approach will work there.
Thank you for any help or direction.
In your code, this line:
request.setRequestHeader("Authorization", "Bearer" + token);
You should have a space after Bearer
request.setRequestHeader("Authorization", "Bearer " + token);
I already set the Authorized redirect URI on Google API Concole as below show.
Google console API Setting
I used localhost:64420/index to get the code, and send the code to localhost:64420/Auth to used ajax post parameter try to get the access token.
Sadly, I got the error message:
{error: "redirect_uri_mismatch", error_description: "Bad Request"}
Here is the script:
<script>
var code = code;
var clientID = client_ID;
var clientSecret = client_Secret;
var redirect_uri = "http://localhost:64420/Report.aspx";
var searchurl = "https://www.googleapis.com/oauth2/v4/token";
$.ajax({
dataType: "json",
url: searchurl,
data: { code: code, client_id: clientID, client_secret: clientSecret, redirect_uri: redirect_uri, grant_type: 'authorization_code' },
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
crossDomain: true,
cache: true,
success: function (data) {
alert(data);
},
error: function (jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
</script>
The redirect URL in your app and the redirect URL you configure in the API console must be an exact character-for-character match. Remember you can configure multiple redirect URLs in the APi Console, so don't be shy and add all possible variants, eg with both http and https. You should really be using https for a redirect URL and I wouldn't be surprised if a future change disallowed plaintext URLs.
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/