Search code examples
python-requestsmicrosoft-graph-apipatchonedrivemicrosoft-graph-files

Can't Move DriveItem in Mocrosoft Graph


I am using Python to download PDF files from OneDrive to a local folder, and also moving the files to a different folder in OneDrive after they have been downloaded.

I am able to download the files from OneDrive to a local folder, however, I get a 400 response when trying to move (PATCH) the files to another OneDrive Folder.

Here is my successful code to download the files:

download_url = 'https://graph.microsoft.com/v1.0/me/drive/items/{item-id}/content'

headers = {'Authorization': 'Bearer ' + json_response['access_token']}

download_url_data = requests.get(download_url, headers=headers)

with open('/Users/Name/Folder/file_name, 'wb') as f:

     f.write(download_url_data.content)

Here is my unsuccessful PATCH request to move the files:

move_url = 'https://graph.microsoft.com/v1.0/me/drive/items/{item-id}

move_headers = {'Authorization': 'Bearer ' + json_response['access_token'],
           'Content-Type' : 'application/json'}

move_body = {'parentReference' : {'id' : '01EV3NG2F6Y2GOVW7775BZO354PUSELRRZ'}}

move_file = requests.patch(move_url, headers=move_headers, data=move_body)

return move_file.status_code

I have followed the documentation here https://learn.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0&tabs=http and I have tried different parentReference id's, but no luck.

Please help! Cheers.


Solution

  • What is the response you're getting (the actual content beside the 400 status code)?

    I believe that requests.patch should receive it's data as a string, not a dictionary (json).

    Try:

    move_file = requests.patch(move_url, headers=move_headers, data=json.dumps(move_body))
    

    And of course don't forget to import json