How to modify the metadata of a file on Sharepoint using Microsoft Graph and Python

Lexignot 45 Reputation points
2024-05-07T04:54:29.61+00:00

Hello,

I am trying to modify the metadata (i.e. value in a column I created on SH) using the following Python script but I receive the following error message. Do you have any thoughts/advice?

Response Text: {"error":{"code":"itemNotFound","message":"The specified list was not found","innerError":{"date":"2024-05-07T04:31:34","request-id":"","client-request-id":"""}}}

Thanks!

def update_file_metadata(access_token, site_id, list_id, item_id, field_name, field_value):
    endpoint = f'https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{list_id}/items/{item_id}/fields'
    headers = {'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json'}
    body = json.dumps({
        field_name: field_value
    })
    print (endpoint)
    response = requests.patch(endpoint, headers=headers, data=body)
    if response.status_code in [200, 204]:
        print(f"Metadata for {field_name} updated successfully.")
    else:
        print(f"Failed to update metadata: {response.json()}")
        print(f"Response Status Code: {response.status_code}")
        print(f"Response Text: {response.text}")

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,773 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,798 questions
0 comments No comments
{count} votes

Accepted answer
  1. RaytheonXie_MSFT 32,081 Reputation points Microsoft Vendor
    2024-05-09T01:14:39.4966667+00:00

    Hi @Lexignot

    I'm glad to hear you solve the problem ,if you have any issue about SharePoint, you are welcome to raise a ticket in this forum.

    By the way, since the Microsoft Q&A community has a policy that "The question author cannot accept their own answer. They can only accept answers by others." and according to the scenario introduced here: Answering your own questions on Microsoft Q&A, I would make a brief summary of this thread:

    [How to modify the metadata of a file on Sharepoint using Microsoft Graph and Python]

    Issue Symptom:

    modify the metadata of a file on Sharepoint using Microsoft Graph and the code return error itemNotFound

    Solution:

    Use the following code to update the metadata works fine

    def update_file_metadata(access_token, site_id, library_id, item_id, field_name, field_value):
        """Update metadata for a file in SharePoint."""
        endpoint = f'https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{library_id}/items/{item_id}/listItem/fields'
        headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
        body = json.dumps({field_name: field_value})
        response = requests.patch(endpoint, headers=headers, data=body)
        if response.status_code in [200, 204]:
            print("Metadata updated successfully.")
        else:
            print(f"Failed to update metadata: {response.status_code}, {response.text}")
    
    
    

    You could click the "Accept Answer" button for this summary to close this thread, and this can make it easier for other community member's to see the useful information when reading this thread. Thanks for your understanding!

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Lexignot 45 Reputation points
    2024-05-08T15:45:55.5533333+00:00

    Accepted Answer: I used the following script to do it using Microsoft Graph (Python language):

    def update_file_metadata(access_token, site_id, library_id, item_id, field_name, field_value):
        """Update metadata for a file in SharePoint."""
        endpoint = f'https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{library_id}/items/{item_id}/listItem/fields'
        headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
        body = json.dumps({field_name: field_value})
        response = requests.patch(endpoint, headers=headers, data=body)
        if response.status_code in [200, 204]:
            print("Metadata updated successfully.")
        else:
            print(f"Failed to update metadata: {response.status_code}, {response.text}")
    
    1 person found this answer helpful.
    0 comments No comments

  2. RaytheonXie_MSFT 32,081 Reputation points Microsoft Vendor
    2024-05-07T07:12:53.7466667+00:00

    Hi @Lexignot,

    The error message shows unable to find the list. You need to check if the list id is correct.

    You can also refer to following code to update list item

    from msgraph import GraphServiceClient
    from msgraph.generated.models.field_value_set import FieldValueSet
    graph_client = GraphServiceClient(credentials, scopes)
    request_body = FieldValueSet(
    	additional_data = {
    			"color" : "Fuchsia",
    			"quantity" : 934,
    	}
    )
    result = await graph_client.sites.by_site_id('site-id').lists.by_list_id('list-id').items.by_list_item_id('listItem-id').fields.patch(request_body)
    
    
    

    For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.