Petlover620
Petlover620

Reputation: 115

Creating a new file with text contents google drive api?

I am trying to create a python function using the Google Drive API to create a new Google Drive file with content.

I am a little confused (after looking at the documentation) which URI to use, as well as what I need to put in the response body to create this file. So far, this is the function to create the new file as well as the function to make the API call (which is working):

def make_request(self, method, url, url_params=dict(),
                     headers=dict(), body=None):
        # add Authorization header
        headers["Authorization"] = "Bearer " + self.token  # bearer authentication

        # make the request
        try:
            r = requests.request(method, url, headers=headers, params=url_params, data=body)
        except Exception as e:
            return 9999, str(e)

        # get the body of the response as text
        body = r.text

        # return value contains the error message or the body
        if r.status_code > 299:
            res_dict = json.loads(body)
            ret_val = res_dict["error"]["message"]
        else:
            ret_val = body

        return r.status_code, ret_val
def gd_create_text_file(self, name, parent_id, contents):
        request_body = {
            "name": name,
            "parents": "[" + parent_id + "]",
            "mimeType": "application/vnd.google-apps.document"
        }
        request_body_json = json.dumps(request_body)
        header = {
            "Content-Type": "application/json"
        }
        
        create_json = self.make_request("POST", "https://www.googleapis.com/upload/drive/v3/files/", headers=header, body=request_body_json)

        if(create_json[0] != 200):
            # an error code was thrown, return None
            print("Error" + str(create_json[0]))
            return None
        else:
            #no error, create and return dictionary
            dictionary = {
                "id": json.loads(create_json[1])["id"],
                "name": json.loads(create_json[1])["name"]
            }
            print("dict: " + str(dictionary))
            return dictionary

Currently, this does not create the file, and it does not have any of the contents of the file. What can I do to fix what I currently have, and add contents to the file?

Thanks!

Upvotes: 0

Views: 1932

Answers (1)

Tanaike
Tanaike

Reputation: 201428

I believe your goal as follows.

  • You want to upload a text data to Google Drive by converting to Google Document using Drive API.
    • From your question and comments, I understood that contents in your script is the text data.
  • Your access token can be used for uploading a file using Drive API.
  • You want to achieve your goal using requests with python.

In order to achieve your goal, I would like to propose the following sample script. In order to upload a file including the file metadata, it is required to upload it with the multipart upload.

Sample script:

import io
import json
import requests

token = '###' # Please set your access token.
name = 'sample' # Please set the filename on Google Drive.
parent_id = 'root' # Please set the folder ID. If you use 'root', the file is created to the root folder.
contents = 'sample text 1' # This is a sample text value for including the created Google Document.

para = {
    "name": name,
    "parents": [parent_id],
    "mimeType": "application/vnd.google-apps.document"
}
res = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
    headers={"Authorization": "Bearer " + token},
    files={
        'metadata': ('metadata', json.dumps(para), 'application/json'),
        'file': ('file', io.BytesIO(contents.encode('utf-8')), 'text/plain')
    }
)
print(res.text)
  • When I tested above script, I could confirm that new Google Document including the text of sample text 1 is cerated to Google Drive.

Note:

  • This is a simple sample script for uploading a text value to Google Drive as Google Document. So please modify it to your actual situation.

Reference:

Upvotes: 2

Related Questions