SharePoint Rest API Microsoft.SharePoint.Client.InvalidClientQueryException The expression is not valid. Bad Request

Recently while working with Rest API in SharePoint Online to delete all items from a SharePoint list, I got the below error. I have added the code inside a script editor web part in a web part page in SharePoint Online. When I run the code it gave the below error:

{"readyState":4,"responseText":"{\"error\":{\"code\":\"-1, Microsoft.SharePoint.Client.InvalidClientQueryException\",\"message\":{\"lang\":\"en-US\",\"value\":\"The expression \\\"Web/Lists/getByTitle('Announcements')/getItemById(item.ID)\\\" is not valid.\"}}}","responseJSON":{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The expression \"Web/Lists/getByTitle('Announcements')/getItemById(item.ID)\" is not valid."}}},"status":400,"statusText":"Bad Request"}

The error looks like below:

Microsoft.SharePoint.Client.InvalidClientQueryException: The expression is not valid. Bad Request

In the Rest API code I was writing like below:

var items = data.d.results;
for(var item in items){
var url = "/_api/Web/Lists/getByTitle('MyList')/getItemById(item.ID)"

Here into the URL variable, I was passing like item.ID which I have put inside double quote as a string.

Then I have modified like below and it started working.

$.each(data.d.results, function (key, value) {
var id=value.ID;
var url = "/_api/Web/Lists/getByTitle('Announcements')/getItemById("+id+")";

You may like following SharePoint Rest API tutorials:

This SharePoint Rest API tutorial explains, how to solve error Microsoft.SharePoint.Client.InvalidClientQueryException The expression is not valid. Bad Request.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site