Nick Prozee
Nick Prozee

Reputation: 2913

Sharepoint REST api returns Bad Request (400)

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:
enter image description here

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?

Upvotes: 0

Views: 2838

Answers (1)

viky.pat
viky.pat

Reputation: 805

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.

Upvotes: 1

Related Questions