SharePoint Api Add ListItem

On 29/11/2024

In javascript



const endpoint = `https://test.sharepoint.com/sites/fdiSandBox`;

const myHtttp = {
	getItemTypeForListName: async function (listTitle) {
		const fetchOptions = {
			method: 'GET',
			headers: {
				'Accept': 'application/json;odata=verbose',
				'Content-type': 'application/json;odata=verbose'
			}
		};
	
		const response = await fetch(endpoint + `/_api/web/lists/getbytitle('${listTitle}')/?$select=ListItemEntityTypeFullName`, fetchOptions);
		return response.json();
	},
	GetDisgestValue: async function () {//
		const fetchOptions = {
			method: 'POST',
			headers: {
				'Accept': 'application/json;odata=verbose',
				'Content-type': 'application/json;odata=verbose'
			}
		};
	
		const response = await fetch(endpoint + "/_api/contextinfo", fetchOptions);
		console.log(response);
		return response.json();
	}
}

const listItemEntityTypeFullName = (await myHtttp.getItemTypeForListName("test")).d.ListItemEntityTypeFullName;
const digest = (await myHtttp.GetDisgestValue()).d.GetContextWebInformation.FormDigestValue;
console.log(digest);

const toAdd = {
	__metadata: { type: listItemEntityTypeFullName },
	"Title": "test",
	"MyLookupId": 1
};
console.log("toAdd", toAdd);
// Fetch options with headers for authentication and response format
const fetchOptions = {
	method: 'POST',
	headers: {
		'Accept': 'application/json;odata=verbose',
		'Content-type': 'application/json;odata=verbose',
		'X-RequestDigest': digest
	},
	body: JSON.stringify(toAdd)
};

try {
	const response = await fetch(endpoint + `/_api/web/lists/getbytitle('test')/items`, fetchOptions);
	console.log("resp", response.json());
}
catch (e) {

	console.log(e);
}
 

Sharepoint javascript

No ratings yet - be the first to rate this.