I believe your goal as follows.
- You want to directly download the file to the memory without creating the data as a file using python.
- From
I need to get a json-file from my GoogleDrive.
, the file you want to download is the file except for Google Docs files (Spreadsheet, Document, Slides and so on). In this case, it's a text file.
- You have already been able to use Drive API with googleapis for python.
- You are using the script for authorizing from https://www.thepythoncode.com/article/using-google-drive--api-in-python.
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)
- At above script,
creds
of creds.token
is from get_gdrive_service()
.
- From your question, I thought that the file you want to download is the JSON data. So at above script, the downloaded data is parsed as JSON object.
- In this case, please import
json
and requests
.
Note:
- When the returned content is JSON data, I think that you can also use
res.json()
instead of res.text
. But when JSONDecodeError
occurs, please check the value of res.text
.
Reference: