google-drive-api

How do I get the webViewLink of a newly created file using Google Drive API?


My intention is to upload a file to a Google Drive and then retrieve the webViewLink of that file. I do the following steps.

Upload a file

curl -X POST -D- -H "Authorization: Bearer ${ACCESS_TOKEN}" -H "Accept: application/json" -F "metadata=@meta.json;type=application/json;charset=UTF-8" -F "file=@hi.txt" "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true"

The meta.json file contains this

{
    "name": "hi.txt",
    "parents": ["xxx"],
    "description": "hi"
}

hi.txt is a small text file.

The post request responds with

HTTP/2 200 

{
  "kind": "drive#file",
  "id": "1NR4LqfYiGt_bzy8olPZicRZ-CoWYuqTN",
  "name": "hi.txt",
  "mimeType": "text/plain",
  "teamDriveId": "xxx",
  "driveId": "xxx"
}

Then I query for the file using the returned id.

curl -X GET -D- -H "Authorization: Bearer ${ACCESS_TOKEN}" "https://www.googleapis.com/drive/v3/files/1NR4LqfYiGt_bzy8olPZicRZ-CoWYuqTN?fields=webViewLink"

And get this

HTTP/2 404 

{
  "error": {
    "code": 404,
    "message": "File not found: 1NR4LqfYiGt_bzy8olPZicRZ-CoWYuqTN.",
    "errors": [
      {
        "message": "File not found: 1NR4LqfYiGt_bzy8olPZicRZ-CoWYuqTN.",
        "domain": "global",
        "reason": "notFound",
        "location": "fileId",
        "locationType": "parameter"
      }
    ]
  }
}

If I simply go GET https://www.googleapis.com/drive/v3/files It returns a list of files, and I can see that my newly created file is there

HTTP/2 200 

{
  "kind": "drive#fileList",
  "incompleteSearch": false,
  "files": [
    {
      "kind": "drive#file",
      "mimeType": "text/plain",
      "id": "1zYzotn1hxiP-MLfXabivj6hNg1HExhlc",
      "name": "hi.txt"
    },
...

But it has a different id. I expected to be able to get a file, and specifically it's webLinkView URL, using the id returned by the file.create call.

The question is how do I get the webViewLink of a newly created file?

thanks Igor


Solution

  • From your 1st curl command and the showing error message File not found: ###., I guess that your file might be uploaded to the shared drive. If my guess was correct, your 2nd curl command is required to be modified as follows.

    curl -X GET -D- -H "Authorization: Bearer ${ACCESS_TOKEN}" "https://www.googleapis.com/drive/v3/files/1NR4LqfYiGt_bzy8olPZicRZ-CoWYuqTN?fields=webViewLink&supportsAllDrives=true"
    

    In this modification, supportsAllDrives=true is added to retrieve the file on the shared drive.

    Reference: