Search code examples
pythonsharepoint

how to upload file to SharePoint with Metadata using Python Rest API


I am trying to upload file to SharePoint site using Python REST API. I can successfully upload the file to SharePoint site, However, I am not sure, how can I add metadata to show up in columns under site.

example: I am uploading TEST.pdf along with

metadata {"name" : "TEST.pdf", "Owner": "Mumbai", "TimeStamp": "3Aug2022 12:12", "pages": 34}

Below is the code to uploade file to sharepoint site.

from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
from concurrent.futures import ThreadPoolExecutor, as_completed




def get_sharepoint_context_using_user():

    # Get sharepoint credentials
    sharepoint_url = "https:/{sitename}.sharepoint.com/sites/TEST"

    # Initialize the client credentials
    user_credentials = UserCredential("username", "password")

    # create client context object
    ctx = ClientContext(sharepoint_url).with_credentials(user_credentials)

    return ctx



def upload_to_sharepoint(dir_name: str, file_name: str):

    # sp_relative_url = create_sharepoint_directory(dir_name)
    ctx = get_sharepoint_context_using_user()

    target_folder = ctx.web.get_folder_by_server_relative_url(
        "test")

    with open(file_name, 'rb') as content_file:
        file_content = content_file.read()
        target_folder.upload_file(file_name, file_content).execute_query()


print(upload_to_sharepoint('test', "TEST.pdf"))

I need to create columns based on metadata.

I am referring below github link but not finding suitable example. https://github.com/vgrem/Office365-REST-Python-Client/tree/master/examples/sharepoint


Solution

  • After few days Hard Work of API documentations reading, finally I found a solution. This will helpful for any one working Python SharePoint API.

    data = {"name" : "TEST.pdf", "Owner": "Mumbai", "TimeStamp": "3Aug2022 12:12", "pages": 34}
    
    1. First create sharepoint context using username & password / client_id and secrete key.
    ctx = get_sharepoint_context_using_user()
    
    1. Fetch items from sharepoint list.
    list_items = ctx.web.lists.get_by_title(
            config.SHAREPOINT_LIBRARY_NAME,
        )
    
    items = list_items .items.get().execute_query()
    
    1. Iterate over a items and update data (dictionary) as metadata property.
    for item in items:
        for k, v in data.items():
            item.set_property(k, v).update().execute_query()