pythonjsonfilegoogle-drive-apiflysystem-google-drive

Get file from GoogleDrive without downloading it to storage - Python


I have a python-script running on a server and I need to get a json-file from my GoogleDrive. I want to use the GoogleDrive API to get the file, which I know the name, location and ID of but I only could find code-samples which downloads the file to storage. The json-content is supposed to be a dict in my script and the file must not be downloaded to storage. I'm new to Python and the GoogleDrive API, so I don't know how to manage it by myself. This is the website I followed: https://www.thepythoncode.com/article/using-google-drive--api-in-python

I hope you can help me because I really need it. Thanks in advance.


Solution

  • I believe your goal as follows.

    In this case, in order to retrieve the file content to the memory, I would like to propose to retrieve it using requests. For this, the access token is retrieved from creds of get_gdrive_service().

    In order to retrieve the file content, the method of "Files: get" is used by adding the query parameter of alt=media.

    Sample script:

    file_id = "###"  # Please set the file ID you want to download.
    
    access_token = creds.token
    url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
    res = requests.get(url, headers={"Authorization": "Bearer " + access_token})
    obj = json.loads(res.text)
    print(obj)
    

    Note:

    Reference: