Django API call from extern Website via AJAX Javascript - javascript

i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs.
We received now an API Token to call for the data on the framework.
I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)".
$.ajax({
type: 'POST',
headers: {
'X-CSRFTOKEN': "XXXXXXXXXXXXXXX",
'Content-Type': 'application/json'
},
url: 'www.service-provider.url/api/...',
success: function () {
console.log("ok");
},
error: function () {
console.log("error");
}
});
Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work.

Okay i got it! Before the token api key there must be "Token ...".
$.ajax({
type: 'GET',
url: 'https://my-url.com/api/1.0/?format=json',
headers:{
"Content-Type": 'application/json',
"Authorization": 'Token XXXXXXXXXXXXXXXXXXXXX',
},
success: function(data){
console.log(data);
}
});

Related

How to update outlook 2.0 API token using refresh-token?

I have next situation:
Main authentication flow happens on server, then client side obtains these data, since that moment I wanna client be able to update token by itself. It's seems there is all needed data on client(access_token, refresh_token), but I can't figure out how to organize request to https://login.microsoftonline.com/common/oauth2/v2.0/token route.
First I tried to get json response:
$.ajax({
url: `https://login.microsoftonline.com/common/oauth2/token?grant_type=refresh_token&refresh_token=refresh_token&scope=openid%20profile%20offline%20access%20user.read%20mail.read%20contacts.read%20calendars.read&client_id=client&client_secret=secret`,
type: 'POST',
cache: false,
processData: false,
contentType: false,
dataType: 'json',
headers: {
'Host': 'https://login.microsoftonline.com',
'Content-Type': 'application/json'
},
success: function(data) {
...
},
error: function(xhr) {
...
}
});
After that I figured out that it's only possible to get this data with redirect, is it correct? If it is, can someone produce an example of how to implement this, looks like it's needed to create an iframe and handle authorization somehow. Thanks.
UPDATED:
as Alina Li pointed in comment to her answer, there is a solution right in the official doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
According to my test, you could using refresh-token through the below code:
var data = "grant_type=refresh_token&refresh_token=refreshToken&client_id=" + appState.clientId;
$http = $http || $injector.get('$http');
$http.post(authUrl + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
}).error(function (err, status) {
});
You don’t need to add scope parameter.
Reference from:
Storing Refresh Token In JavaScript, Getting New Access Token

FCM Sending HTTP Post request gives error code 400()

I am using HTTP POST request to give notification to authors on my web-app that their stories are approved by our admin.
My payload looks like this
var payload = {
"notification": {
"title": "Story Approved!",
"body": "Your story is approved"
},
"to" : to
}
This is my request
$.ajax({
type: 'POST',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization': 'key='+serverKey
},
data: payload,
success: function(response){
console.log(response);
},
});
Whenever I try to send the request it gives me the following error
POST https://fcm.googleapis.com/fcm/send 400 ()
I am kinda new to this and according to Firebase Error Response Codes
Invalid JSON 400 Check that the JSON message is properly formatted and contains valid fields (for instance, making sure the right data type is passed in).
But I cannot figure out where I am wrong. Any help would be appreciated
just convert your payload to json like this:
data: JSON.stringify(msg)
and your code will be like this:
$.ajax({
type: 'POST',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization': 'key='+serverKey
},
data: JSON.stringify(msg),
success: function(response){
console.log(response);
},
});

Error creating communication site in Sharepoint Online via REST and Javascript

I'm trying to create a sharepoint online site collection based on the Communication site template, as described by Microsoft here https://learn.microsoft.com/en-us/sharepoint/dev/apis/communication-site-creation-rest by using javascript on a page in a different sharepoint site
But, I keep getting a response of 403- although I am a tenant admin and so definitely have permission to create sites.
I am running the script below from a page at a url like companyname.sharepoint.com/sites/myTestSite/sitepages/RunSomeJS.aspx
I have tried specifying REST endpoint domain of both
companyname.sharepoint.com
and
companyname-admin.sharepoint.com
but get the same error.
function DoRestCall(){
var body={'parameters':
{
"__metadata":{"type":"SP.Publishing.CommunicationSiteCreationRequest"},
"AllowFileSharingForGuestUsers":false,
"Classification":"MyTest Communication Site",
"Description":"Here is my communication site",
"SiteDesignId":"6142d2a0-63a5-4ba0-aede-d9fefca2c767",
"Title":"MyTest Communication Site",
"Url":"https://companyname.sharepoint.com/sites/testSiteName",
"lcid":1033
}
};
$.ajax({
type: 'POST',
url: "https://companyname.sharepoint.com/_api/sitepages/create",
contentType: 'application/json',
processData: false,
headers:{
"accept":"application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
},
data: JSON.stringify(body),
success: function ()
{
alert('CREATION REQUEST SUBMITTED');
},
error: function(data){
alert('failure:' + data.statusText );
}
});
}
Any suggestions as to what I'm doing wrong here?
You need to make couple of changes as below:
1) Change the metadata as below:
"__metadata":{"type":"SP.Publishing.PublishingSiteCreationRequest"},
2) You need to replace parameters to request
3) Modify the endpoint to create communication site as below:
url: "https://companyname.sharepoint.com/_api/sitepages/publishingsite/create",
3) Ensure that you are running the code from the root site(whose url is like https://companyname.sharepoint.com/sitepages/RunSomeJS.aspx) and you are the site collection admin of that root site.
You final code would be as below:
function DoRestCall(){
var body={'request':
{
"__metadata":{"type":"SP.Publishing.PublishingSiteCreationRequest"},
"AllowFileSharingForGuestUsers":false,
"Classification":"MyTest Communication Site",
"Description":"Here is my communication site",
"SiteDesignId":"6142d2a0-63a5-4ba0-aede-d9fefca2c767",
"Title":"MyTest Communication Site",
"Url":"https://companyname.sharepoint.com/sites/testSiteName",
"lcid":1033
}
};
$.ajax({
type: 'POST',
url: "https://companyname.sharepoint.com/_api/sitepages/publishingsite/create",
contentType: 'application/json',
processData: false,
headers:{
"accept":"application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
},
data: JSON.stringify(body),
success: function ()
{
alert('CREATION REQUEST SUBMITTED');
},
error: function(data){
alert('failure:' + data.statusText );
}
});
}

400 error when converting from ajax to $http?

I am trying to complete a GET request using $http instead of ajax. The call works perfectly with ajax, but when I try to do the same thing with $http I get a 400 (Bad Request) error. I believe I am following the Angular documentation correctly. Any ideas? Hopefully this will also be helpful for others experiencing the same issue.
The ajax code that works:
$.ajax({
type: "GET",
accept: 'application/json',
url: myURL,
headers: {"Authorization": "Basic " + basicKey},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
data: requestPayload,
async: false
}).done(function(serverData) {
console.log(serverData.access_token);
}).fail(function(error) {
console.log(error);
});
The $http code that does not work:
var basicConfig = {
method: 'GET',
url: myURL,
headers: {
'Authorization': 'Basic ' + basicKey,
'Accept': "application/json",
'Content-Type': 'application/x-www-form-urlencoded'
},
data: requestPayload
}
$http(basicConfig).success(function(data, status){
console.log(status);
}).error(function(data, status){
console.log(status);
});
Thanks in advance.
use params instead of data. data is the request body, used for POST requests, whereas params is for query string variables in GET requests.

Paypal Java script integration

Want to integrate Paypal with my mobile web application. I tried to get the access token using client id and secret id but unable to get the access token.
Below is the sample Ajax call with I am making to retrieve the access token.
function getAccessToken(){
$.ajax({
url:"https://api.sandbox.paypal.com/v1/oauth2/token/",
type:"POST",
data : {"grant_type":"client_credentials"},
beforeSend: function (request)
{
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Accept-Language", "en_US");
request.setRequestHeader("Authorization", "abc XXXXX:XXXXXXXXXXXXX");
},
success: function(data) {
alert(data);
},
error: function(e, messgae,type){
alert("Error" + e +" "+messgae+" type "+type);
}
});
I am unable to retrive the access token from the server.
Can anyone please tell me how can I integrate Paypal with my mobile web application using java script?
after a series of try and fail I found the correct AJAX call:
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic "+btoa("**<Client ID>:<Secret>**")
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: "grant_type=client_credentials",
complete: function(result) {
alert(JSON.stringify(result));
},
});
You need to replace Client ID:Secret with the one that you find on your Developer Dashboard, for example AxxhGDh:hudh-X-h8qi
Above example doesn't works, below works for me:
var parameter = {
"grant_type": "client_credentials",
"username": "<username>",
"password": "<password>"
}
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic <your auth key>"
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: parameter,
complete: function (result) {
alert(JSON.stringify(result));
},
})

Categories