Search code examples
pythongoogle-drive-apigoogle-docsgoogle-docs-api

How to create a Google Doc with regular text as the body?


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!


Solution

  • I believe your goal as follows.

    • From 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.

    Issue and workaround:

    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.

    1. Create new Google Document using the method of documents.create. Ref
    2. Upload the text using the method of documents.batchUpdate. Ref

    So, 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.

    Sample script:

    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)
    
    • When above script is run, new Google Document with the filename of Test is created, and the body has the text of Hello world!.
    • In this case, from googleapiclient.http import MediaIoBaseUpload is also used.

    Note:

    • 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)
      

    References: