I'm in the process of taking information stored in a Google Sheet and trying to neatly format it on a Google Doc. I'm using the Google Docs API here, but I'm not following how to properly use the 'body:' part of the JSON representation.
For the sake of simplicity, how would you create a new document with the title "Test" and the body just saying "Hello world!". If needed, I'm using Python 3.7.
Thanks for any help!
I believe your goal as follows.
how would you create a new document with the title "Test" and the body just saying "Hello world!".
, I understood that you want to upload a text of Hello world!
as new Google Document using python.I think that in this case, I would like to propose to use Drive API. Because in the current stage, when Google Docs API is used, 2 API calls are required to be used as follows, because the method of documents.create
cannot include the text body.
documents.create
. Refdocuments.batchUpdate
. RefSo, in this answer, I would like to propose to use the method of Files: create
in Drive API. Ref When this method is used, your goal can be achieved by one API call.
The sample script using googleapis for python is as follows.
In this case, please use the authorization script of Quickstart. In this case, please use https://www.googleapis.com/auth/drive
as the scope.
drive = build('drive', 'v3', credentials=creds)
text = 'Hello world!'
media = MediaIoBaseUpload(io.BytesIO(text.encode('utf-8')), mimetype='text/plain', resumable=True)
file_metadata = {"name": "Test", "mimeType": "application/vnd.google-apps.document"}
file = drive.files().create(body=file_metadata, media_body=media).execute()
print(file)
Test
is created, and the body has the text of Hello world!
.from googleapiclient.http import MediaIoBaseUpload
is also used.If you are required to use Google Docs API, you can also use the following script. In this case, the result is the same with above sample script.
docs = build('docs', 'v1', credentials=creds)
text = 'Hello world!'
res1 = docs.documents().create(body={"title": "Test"}).execute()
requests = [{"insertText": {"location": {"index": 1}, "text": text}}]
res2 = docs.documents().batchUpdate(documentId=res1.get('documentId'), body={"requests": requests}).execute()
print(res2)