Search code examples
pythongoogle-drive-api

Can not create shortcut of file using google drive api


Here is sample code that i am trying to run.

import requests

api_endpoint = 'https://www.googleapis.com/upload/drive/v3/files?supportsAllDrives=true'

headers = {
    'Authorization': f'Bearer {access_token}'
}

json={"name": "a.jpg", "mimeType": "application/vnd.google-apps.shortcut", "parents": [{"id": "folder_id"}], "shortcutDetails": {"targetId": "target_file_id"}}

res = requests.post(api_endpoint, headers=headers,  json=json)
print(res.status_code)
print(res.text)

Even this code does not pickup that name and it just create a text file that contain json data.


Solution

  • Modification points:

    • I think that in this case, the endpoint is https://www.googleapis.com/drive/v3/files instead of https://www.googleapis.com/upload/drive/v3/files.
    • In the case of Drive API v3, the value of the property parents is required to be ["folder_id"] instead of [{"id": "folder_id"}].

    When these points are reflected in your script, it becomes as follows.

    Modified script:

    Please set your access token, the parent folder ID, and the target file ID.

    import requests
    
    access_token = "###" # Please set your access token.
    
    api_endpoint = 'https://www.googleapis.com/drive/v3/files?supportsAllDrives=true'
    
    headers = {
        'Authorization': f'Bearer {access_token}'
    }
    
    json = {"name": "a.jpg", "mimeType": "application/vnd.google-apps.shortcut", "parents": ["folder_id"], "shortcutDetails": {"targetId": "target_file_id"}}
    
    res = requests.post(api_endpoint, headers=headers,  json=json)
    print(res.status_code)
    print(res.text)
    
    • When I tested this modified script, I confirmed that a shortcut file of "target_file_id" was created to the folder of "folder_id".

    Reference: