March 21, 2017

SharePoint: Getting list items with SPFx and CamlQuery

Problem

When fetching SPList items using SPFx and REST combined with CAMLQuery, you need to use spHttpClient.post. However, the following code wasn’t working:

const options: ISPHttpClientOptions = {
	body: `{'query': {
		'__metadata': {'type': 'SP.CamlQuery'},
		'ViewXml': '<View><Query><OrderBy><FieldRef Name="ID"" /></OrderBy></Query></View>'
	}}`
};

return this.context.spHttpClient.post(window.location.protocol + '//' + window.location.hostname + (this.properties.webUrl +
	`/_api/web/lists/GetByTitle('Pages')/items?$select=Title`),
	SPHttpClient.configurations.v1,
	options)
	.then((response: SPHttpClientResponse) => {
		return response.json();
});

But instead it was throwing errors such as:

The property 'query' does not exist on type 'SP.Data.PagesItem'. Make sure to only use property names that are defined by the type.

or

An entry without a type name was found, but no expected type was specified. To allow entries without type information, the expected type must also be specified when the model is specified.

Solution

First of all make sure you use the “odata-version: 3.0”, but more importantly, as you’re using POST, change the REST URL from …/items to …/GetItems.

Final working code:

const options: ISPHttpClientOptions = {
	headers: {'odata-version':'3.0'},
	body: `{'query': {
		'__metadata': {'type': 'SP.CamlQuery'},
		'ViewXml': '<View><Query><OrderBy><FieldRef Name="ID"" /></OrderBy></Query></View>'
	}}`
};

return this.context.spHttpClient.post(window.location.protocol + '//' + window.location.hostname + (this.properties.webUrl +
	`/_api/web/lists/GetByTitle('Pages')/GetItems?$select=Title`),
	SPHttpClient.configurations.v1,
	options)
	.then((response: SPHttpClientResponse) => {
		return response.json();
});

Oh, and no need to use JSON.stringify() when building the ISPHttpClientOptions body query, just use ` around the code and it will already be a string.

3 comments:

  1. Thanks a lot for pointing out the ` in the body option. I always got a 500.

    ReplyDelete
  2. Thanks after hours of pulling my hair out, this worked, thank you so much!

    ReplyDelete
  3. The back-ticks were not working out for me in the Body, so used used good old JSON.stringify and it worked. But the headers and other things are bang-on... Thanks much!!!

    ReplyDelete