🔍 Code Extractor

class ListItemCollection

Maturity: 48

A collection class for managing SharePoint list items, providing methods to retrieve items by various identifiers and URLs.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/listitems/collection.py
Lines:
6 - 37
Complexity:
moderate

Purpose

ListItemCollection serves as a container and manager for SharePoint ListItem objects. It extends EntityCollection to provide specialized methods for querying and retrieving list items from a SharePoint list using different identification methods (numeric ID, string ID, or URL). This class is typically obtained from a SharePoint List object and used to access and manipulate the items within that list.

Source Code

class ListItemCollection(EntityCollection[ListItem]):
    """List Item collection"""

    def __init__(self, context, resource_path=None):
        super(ListItemCollection, self).__init__(context, ListItem, resource_path)

    def get_by_id(self, item_id):
        """
        Returns the list item with the specified list item identifier.

        :param int item_id: The list item identifier.
        """
        return ListItem(
            self.context, ServiceOperationPath("GetById", [item_id], self.resource_path)
        )

    def get_by_string_id(self, s_id):
        """
        Returns the list item with either the specified list item identifier or the specified identifier
        for an instance of an external content type.

        :param str s_id: Specifies the list item identifier, or if the list is an external list, specifies the
        identifier for an instance of an external content type as specified in[MS-ECTPWPS] section 3.1.4.1.2.1.
        """
        return ListItem(
            self.context,
            ServiceOperationPath("GetByStringId", {"sId": s_id}, self.resource_path),
        )

    def get_by_url(self, url):
        """Returns the list item with the specified site or server relative url."""
        return self.single("FileRef eq '{0}'".format(url))

Parameters

Name Type Default Kind
bases EntityCollection[ListItem] -

Parameter Details

context: The client context object that maintains the connection to the SharePoint server and handles authentication. This is required for all API operations and is passed to child ListItem objects.

resource_path: Optional. The service resource path that identifies the location of this collection in the SharePoint API hierarchy. If not provided, it will be inherited from the parent object. This path is used to construct API endpoints for operations.

Return Value

Instantiation returns a ListItemCollection object that can be used to query and retrieve ListItem objects. The get_by_id and get_by_string_id methods return individual ListItem objects configured with the appropriate service operation path. The get_by_url method returns a single ListItem matching the specified URL by using the inherited 'single' method with an OData filter.

Class Interface

Methods

__init__(self, context, resource_path=None)

Purpose: Initializes a new ListItemCollection instance with the provided context and optional resource path

Parameters:

  • context: The client context object for SharePoint API communication
  • resource_path: Optional service resource path identifying the collection's location in the API hierarchy

Returns: None (constructor)

get_by_id(self, item_id) -> ListItem

Purpose: Retrieves a list item using its numeric identifier

Parameters:

  • item_id: Integer list item identifier (the ID field value in SharePoint)

Returns: A ListItem object configured with a service operation path to retrieve the specified item. The item's properties must be loaded via execute_query() before access.

get_by_string_id(self, s_id) -> ListItem

Purpose: Retrieves a list item using a string identifier, supporting both regular list items and external content type instances

Parameters:

  • s_id: String identifier - can be a numeric ID as string for regular lists, or an external content type identifier for external lists as per MS-ECTPWPS specification

Returns: A ListItem object configured with a service operation path to retrieve the specified item. The item's properties must be loaded via execute_query() before access.

get_by_url(self, url) -> ListItem

Purpose: Retrieves a list item by its site-relative or server-relative URL path

Parameters:

  • url: String containing the site-relative or server-relative URL of the list item (e.g., '/sites/mysite/Lists/MyList/item.aspx')

Returns: A single ListItem object matching the specified URL. Uses OData filtering on the FileRef field. Returns None if no match is found.

Attributes

Name Type Description Scope
context ClientContext Inherited from EntityCollection. The client context object used for all SharePoint API operations, maintaining connection state and authentication. instance
resource_path ResourcePath Inherited from EntityCollection. The service resource path identifying this collection's location in the SharePoint API hierarchy. instance

Dependencies

  • office365

Required Imports

from office365.runtime.paths.service_operation import ServiceOperationPath
from office365.sharepoint.entity_collection import EntityCollection
from office365.sharepoint.listitems.listitem import ListItem

Usage Example

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

# Setup context
site_url = 'https://contoso.sharepoint.com/sites/mysite'
credentials = UserCredential('user@contoso.com', 'password')
ctx = ClientContext(site_url).with_credentials(credentials)

# Get list and its items collection
list_obj = ctx.web.lists.get_by_title('MyList')
items = list_obj.items

# Get item by numeric ID
item = items.get_by_id(5)
ctx.load(item)
ctx.execute_query()
print(item.properties['Title'])

# Get item by string ID
item2 = items.get_by_string_id('5')
ctx.load(item2)
ctx.execute_query()

# Get item by URL
item3 = items.get_by_url('/sites/mysite/Lists/MyList/5_.000')
ctx.load(item3)
ctx.execute_query()
print(item3.properties['Title'])

Best Practices

  • Always call ctx.load() and ctx.execute_query() after retrieving items to populate their properties from the server
  • Use get_by_id for numeric identifiers when working with internal SharePoint lists
  • Use get_by_string_id when working with external lists or when the ID format is uncertain
  • Use get_by_url when you have the file reference path and need to locate the corresponding list item
  • The collection inherits from EntityCollection, so standard collection methods like filter(), top(), and select() are available
  • Handle exceptions for items that don't exist - methods will fail during execute_query() if the item is not found
  • Reuse the context object across multiple operations to maintain connection efficiency
  • The get_by_url method uses OData filtering with the 'FileRef' field, which is specific to document libraries and lists with file attachments

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class ListItemVersionCollection 80.4% similar

    A collection class that manages and provides access to versions of a SharePoint list item, inheriting from EntityCollection with ListItemVersion as the entity type.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/listitems/versions/collection.py
  • class ListItemCollectionPosition 76.6% similar

    A class representing a collection position for SharePoint list items, used for pagination and tracking position within list item collections.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/listitems/collection_position.py
  • class VideoItemCollection 72.0% similar

    A collection class for managing VideoItem entities in SharePoint, inheriting from EntityCollection to provide collection-level operations for video items.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/publishing/video/item_collection.py
  • class ListTemplateCollection 71.6% similar

    A collection class that manages and provides access to SharePoint list templates, extending EntityCollection to handle multiple ListTemplate instances.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/lists/template_collection.py
  • class FieldLinkCollection 70.7% similar

    A collection class for managing SharePoint field links, providing methods to add, retrieve, and reorder field links within a content type or similar SharePoint entity.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/contenttypes/fieldlinks/collection.py
← Back to Browse