I am trying to create a ListItem using the Sharepoint REST Api (we just started with the Sharepoint Api so definitly no expert).
According to the Microsoft tutorial the post should look like this:
I implemented the following code
public addItemToList_Test(): void {
var listTitle: string = "DemoHomeWork";
var listItemType: string = "SP.Data." + listTitle + "ListItem";
var listItemTitle: string = "TestItem";
var postBody = { '__metadata': { 'type': listItemType }, 'Title': 'TestItem' };
var $: jQuery = require("jquery");
var call = $.ajax({
url: listsUrl + "/GetByTitle('" + listTitle + "')/items",
method: "POST",
body: postBody,
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
length: JSON.stringify(postBody).length
}
});
return call;
}
However, this keeps returning me Bad Request (400) and figuring out why this happens is tricky to find out. Is there anyone who can tell me what is wrong with the request?
How are you authenticating your request?
As given in documentation you need to pass access_token with your request to make API work. As in you headers, i am not seeing access_token being passed.
You need to first get access_token and then pass it with the request to make API work.
Also in
"'__metadata': { 'type': listItemType }" **listItemType** you are creating it manually but it can be different. Can you check getting it manually (`https://site_url/_api/web/lists/getbytitle(listtitle)`)
and check if ListItemEntityTypeFullName for this list is same as you have created listItemType.
Related
Hi everyone recently i have been trying to do a fetch post in app script, from an api called salesbinder(inventory system), i have managed to fetch and pulls all inventory data down, however i have been struggling to post and add document to it and received an error code ->
"Truncated server response: {"message":"Unauthorized","url":"\/api\/2.0\/documents.json","code":401}"
since I am using the same username and password I can assure that the details are correct for the authentication, would appreciate a lot if anyone could help me to solve the problem.
Here are the api documentaion (https://www.salesbinder.com/api/documents/add/) and the code i have been using.
function posting(){
var Username = "{API KEY}"
var Password = "x"
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(Username+ ':' + Password)
};
var url ='{API URL}'
var data ={
"document":{
"customer_id": 'a93a9e9a-5837-4ec5-9dc7-47cc8cfd84e4',
"issue_date":"2022-05-09",
"context_id":5,
"document_items":[
{
"quantity":2,
"price":134,
"item_id":" b04993fe-7b17-42a1-b5e5-2d34890794c9"
}
]
},
};
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
UrlFetchApp.fetch(url, option);
}
I think that your error message of "message":"Unauthorized" is due to "headers": {headers},. This has already been mentioned in chrisg86's comment.
And also, from this document, it seems that the request body is required to be sent with Content-Type: application/json.
From:
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
To:
var option = {
"method": "post",
"payload": JSON.stringify(data),
headers, // or "headers": headers
"contentType": "application/json"
};
Note:
In this modification, it supposes that the values of "Basic " + Utilities.base64Encode(Username+ ':' + Password), data and url are correct. Please be careful this.
I have a problem with my AJAX. Using Insomnia, I was able to get in with a successful response of 200 using the API token.
However, when I implement it in the HTML, I get a 401 response of access denied.
$.ajax({
url: "https://ecoexchange.dscloud.me:8080/api/get",
method: "GET",
apikey: sessionStorage.getItem("apikey"),
dataType: 'json',
success: function(result) {
$('#infoTable tr').empty();
var header = $('#infoTable thead');
var body = $('#infoTable tbody');
var hTr;
$('#infoTable thead').append(hTr = $('<tr>'));
// Headers
for (var h = 0; h < result.headers.length; h++) {
hTr.append($('<th>', {
text: result.headers[h]
}))
}
// Body
for (var d in result.data) {
var data = result.data[d];
$('#infoTable tbody').append($('<tr>')
.append($('<td>', {
text: data.RecyclableID
}))
.append($('<td>', {
text: data.Name
}))
.append($('<td>', {
text: data.RecyclableType
}))
)
}
}
})
I am not sure how to put in the token or user name or password.
How can I improve the code so I don't get the error?
What is this apikey parameter you're using? That's not in the documentation.
apikey: sessionStorage.getItem("apikey"),
Did you mean to pass it as a header instead? For example:
headers: {"apikey": sessionStorage.getItem("apikey")},
The documentation for the service you're using should specify how to include the API key. Presumably you have that information, because:
Using Insomnia, I was able to get in with a successful response
So you'll need to include the value in your AJAX request wherever it belongs. Most likely as either a header value or a query string value. But the jQuery .ajax() function isn't going to know how to pass the value, you have to specify.
I think your problem is with passing queries which can be solved here
As it's been said on David's answer , You must know where your apikey is required on the server-side, in header or queries(parameters).
If your apikey is required on queries based on the docs you can use :
$.get('/api/get' , {'apikey' : 'YOUR-KEY'}).done((res) => {
console.log(res)
})
Or if your apikey is required in headers:
$.ajax({
url: '/api/get',
type: 'GET',
headers: {'apikey' : 'YOUR-KEY'},
success : (res) =>{
console.log(res);
}
})
jQuery.ajax() docs can be found here
And jQuery.get() docs here
I am looking for a way to put variables in to a AJAX get call, now i know the obvious way to do it would just be to add it too "data" like so
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication', favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});
But this goes to an api and the api also handles request from an iOS app which put the data into httpBody like so
let json: [String: Any] = ["userid":userID, "message":applicationtext.text, "favourid":selectedFavour]
let jsondatatosend = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = "myurl";
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsondatatosend
I believe the reason i did this origionally was it was messing up because of having strange characters in the URL so i had to send it through the body which all worked well, but now im trying to get a website to follow the same method on my api i would like it to be sent in the body from ajax so my php can do this function
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
I understand there are many ways for me to get around it in my php just use $_GET[' var '] instead of file_get_contents when it is sent from the AJAX of my website but i was wondering if there was a way of sending it into the body via ajax so i dont have to change the php file and then it is not sent through url's
so what i want to be able to do is something like this
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication'},
httpBody: {favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});
I'm building a REST api on top of express.js. I am having trouble updating variables inside my routes.
Example:
I'm calling app.get("/wp/page/create/:id", function(req, res)
Inside this route I start by calling a http request using request-promise library. The response of this call I use in a nested http call.
I use a global variable for the headers for the nested call, and it's to the header a i need to make changes by using the etag variable.
Code:
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
res.send(data).end()
console.log("All done!");
})
})
When i start the server up and enter the route everything works fine. When i when try to hit it again the etag variables is still the same, even though it should be updated.
If I restart the server it works the again on the first attempt but fails on the second/third.
Any idea what I am doing wrong?
I have resolved the issues. The simple solution was to clear the headers containing the variable.
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
postHeaders['If-Match'] = "";
res.send(data).end()
console.log("All done!");
})
})
postHeaders is a global variable. is headers in global.postHeaders = headers; also a global varaible ? Whatever you are trying to do here is grossly wrong. postHeaders variable will be shared across multiple request. so you will hit a scenario where postHeaders['If-Match'] value might be empty string or the etag .
Try this instead of the first line
var postHeaders = Object.assign({}, headers);
Not sure what you are trying, but at-least this statement will subside the huge error in the code. This will create a new header object for each request.
This seems very similar to a number of other questions and it seems obvious that the error indicates there's something wrong with my JSON payload. But I'm at a loss as to why.
I'm running a Google Apps Script to test sending a message to Google Firebase Cloud Messaging.
My code:
function SendGCMessage() {
var url = "https://gcm-http.googleapis.com/gcm/send";
var apiKey = "AbCdEfG";
var to = "ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"
var payload = {
"data": {
"message" : "This is the message"
},
"to":to
};
var sendCount = 1;
var headers = {
"Content-Type": "application/json",
"Authorization": "key=" + apiKey
};
var params = {
headers: headers,
method: "post",
payload: payload
};
var response = UrlFetchApp.fetch(url, params);
return {message: "send completed: " + response.getContentText()};
}
When I run this in debug mode, the object payload looks fine - like a normal Javascript object. params as well. UrlFetchApp takes a Javascript object, not a String in JSON notation. However I did try "JSON.stringify(params)" and I got an error. What did I do wrong?
Note: params looks like this when I pause it in the debugger:
{"headers":{"Content-Type":"application/json","Authorization":"key=AbCdEfG"},"method":"post","payload":{"data":{"message":"This
is the message"},"to":"ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"}}
I discovered the problem, thanks to https://stackoverflow.com/a/10894233/3576831
the 'payload' parameter must be a string as specified here:
https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
Adjusting this section of the script works:
var params = {
headers: headers,
method: "post",
payload: JSON.stringify(payload)
};