Access Django Rest Framework API using Javascript - getting a Token - javascript

I have an API setup using Django Rest Framework. It works fine when accessing via cURL or HTTPie or even the browsable API. The API has token authentication so initially you have to supply credentials which will return a token. Using HTTPie (or even curl) you would do this:
http POST http://127.0.0.1:8000/api/v1/api-token-auth/ username="user1" password="testpassword"
This would return a response e.g.:
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Sun, 03 Sep 2017 16:57:38 GMT
Server: WSGIServer/0.2 CPython/3.6.1
X-Frame-Options: SAMEORIGIN
{
"token": "fgfdgfdgfdgfdgd45345345lkjlj"
}
You would then take the token and perform a GET/PUSH/etc like so:
http --json POST http://127.0.0.1:8000/api/v1/test/ test_text="Testing" 'Authorization: Token fgfdgfdgfdgfdgd45345345lkjlj'
I have been Google searching for a while now and cannot find any clear answers as to how the above two lines would translate into Javascript? How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?

I agree you should use Ajax.
You need an ajax call in the very beginning of you app:
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
Haven`t tested, but idea is use an Ajax call to get the token and use .ajaxSetup to save the token to a header for all following ajax requests.
The you can do this:
var data = {test_text="Testing"}
$.ajax({
type: 'POST',
data: data,
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Or this:
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/api/v1/ANOTHER_TES/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Change type parameter of the call to change your request.

See #Tico's answer.
How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?
$.ajax({
type: 'POST',
data: {
username: "user1",
password: "testpassword"
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
$.ajaxSetup({
headers: {
"token": res.token
}});
$.ajax({
type: 'POST',
data: {
test_text: "Testing"
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
alert(res);
}});
}
});

as post, get or any other url calls are asynchronous calls. So in order to maintain the program flow and make the post request you need to use promise feature of js, which will make your post call synchronous.
js promise description
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
this code will work fine if you use this at the starting of your program, but this is asynchronous, to make it synchronous with your program you need to use promise.
And for the third part of your question you need to do this...
$.ajax({
type: 'GET',
url: 'http://your_url' + "/token=" + your_token,
success: function(res){
console.log(res)
},
error: function(error) {
callbackErr(error,self)
}
})

Related

How to convert a Raw body data request for an API to ajax request

I am currently using postman to make an API request that pushes body data. I can get this to work either using "x-www-form-urlencoded" or "raw". See examples below:
I'm trying to convert this to an ajax javascript request but unsure on how to format the body/data text. Here is my script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {
" grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "
},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});
Any help would be appreciated
There's a mismatch here as you're setting the Content-Type header to JSON, yet you're sending form-urlencoded. You need to use one or the other consistently.
If you want to explicitly use JSON, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***'
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
If you want to use a form-urlencoded string, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
Note in the above examples that the first argument to the error handler is not the request or response data as your example seems to expect. I've amended that part to accept the correct arguments.

Call REST API in Jquery Ajax POST Method return 403 error

This below code is for calling a Login rest api through jquery ajax but it returns 403 error. I want to know if I missed any necessary parameter in ajax call or it's server side error. That source(HTML file) and destination(API) both in same cloud server.
But the api works fine in postman without any error
$.ajax({
type: "POST",
url: 'https://mzzzzcloudx.am.co.in/login',
dataType: 'json',
data: {
"login": "abcd#gmail.com",
"password": "12345"
}, //{"login":$("#login").val(), "password":$("#pass").val()},
contentType: "application/json",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*"
},
success: function(data) {
console.log(data);
},
error: function(err) {
alert(err); //returns 403 error
console.log(err);
}
});
Do you try to remove the quote in the field names (login, password) of the data section?
data: {
login: "abcd#gmail.com",
password: "12345"}
And also, do you confirm that the field names (login, password) are the same in the REST method login()?

How to send a valid request to your own TFS server?

I'm trying to write a plugin for TFS 2015 (its important). I read a couple of manuals. the examples all turns out simply, but it is more difficult with a real plugin. my problem: i cant send any get/post request from my tfs server to same server. I always get the same response: 401 Unauthorized. I looked at examples that sending Ajax requests (https://github.com/ALM-Rangers/Work-Item-Details-Widget-Extension/blob/master/src/scripts/menu.js) and add auth token to request, but i get same error 401.
my code:
VSS.require(["VSS/Authentication/Services"], function(Services) {
var authTokenManager = Services.authTokenManager;
VSS.getAccessToken().then(function(token) {
var header = authTokenManager.getAuthorizationHeader(token);
$.ajaxSetup({
headers: { 'Authorization': header }
});
$.ajax({
url: "http://myTFSServ:8080/tfs/_api/_common/GetCollectionJumpList?__v=5&navigationContextPackage=%7B%22Action%22%3A%22index%22%2C%22Area%22%3A%22%22%2C%22Level%22%3A8%2C%22Controller%22%3A%22workItems%22%7D&selectedHostId=6e60eeec-39b3-4902-a864-172cd27dea91&api-version=3.0-preview.2",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(c) {
debugger;
// do something...;
},
error: function(e) {
debugger;
var error = e;
}
});
});
});
how can i send any valid get/post request from my tfs server to same server??

jQuery - AJAX Request

I am working on an app that sends a POST request to a web service. My POST request looks like this:
$.ajax({
type: 'POST', url: getEntityUrl(), cache: 'false',
contentType:'application/json',
headers: {
'api-key':'myKeyHere',
'Content-Type':'application/json'
},
data: {
firstName:'Jon',
lastName:'Smith'
},
success: function() { alert('good job'); },
error: function() { alert('oops'); }
});
When I execute this, I'm getting a 400 Bad Request. I watched the request in Fiddler. I noticed that the parameters I sent are being sent as "firstName=Jon&lastName=Smith". However, they need to be sent across as JSON like I have them defined in the data parameter. I confirmed this is the problem by modifying the request in the composer in Fiddler. What am I doing wrong?
Thanks
If you pass jQuery a plain object through the data parameter (as you do here) then it will encode the data as application/x-www-form-urlencoded.
Just setting the contentType is insufficient.
If you want to send JSON then you must encode it yourself. You can use JSON.stringify for that.
data: JSON.stringify({
firstName:'Jon',
lastName:'Smith'
}),
You need to stringify the data like following.
$.ajax({
type: 'POST',
url: getEntityUrl(),
contentType: 'application/json',
headers: {
'api-key': 'myKeyHere',
'Content-Type': 'application/json'
},
data: JSON.stringify({ firstName: 'Jon', lastName: 'Smith' }), //change here
success: function () { alert('good job'); },
error: function () { alert('oops'); }
});

Setting request header in ajax

I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});

Categories

Resources