Get ItemCount from Existing View
-
20-02-2021 - |
Domanda
I have a Task list that I'm trying to query to get the total Active Tasks for the current user. There is a view already built that I would like to use.
/_api/web/lists/getbytitle('Tasks')/views/getbytitle('My Tasks')/ItemCount
However, it throws an error:
Cannot find resource for the request ItemCount
Is there a way I can grab the item count from an existing view using the REST API ?
Soluzione
There is no direct way to get the items count for list view like you can get for list using /ItemCount
endpoint.
Workarounds
Solution 1 (Personally Recommended):
First get the
ViewQuery
for list view which stores the CAML query for list view. You can get it like:<siteUrl>/_api/web/Lists/getbytitle('Tasks')/views/getbytitle('Active Tasks')/ViewQuery
Example Output:
<Where> <Neq> <FieldRef Name="Status" /> <Value Type="Text">Completed</Value> </Neq> </Where> <OrderBy> <FieldRef Name="ID" /> </OrderBy>
Using this ViewQuery, you can build CAML query and then fetch list items using getItems() endpoint (POST Method).
Count the number of items returned in 2nd step.
Reference: How to get all items in a view using REST API
Solution 2:
If you want to reduce the number of REST calls then you can use this approach.
First take a note of all filters applied to list view
Get list items using
/items
endpoint by applying filters noted in 1st step, something like this:<siteUrl>/_api/web/Lists/getbytitle('Tasks')/items?$filter=Status ne 'Completed'
Count the number of items returned in 2nd step.
Note: If you use this approach then you have to change $filter
query every time you change the filter conditions from list view settings.
Altri suggerimenti