Search code examples
pythonjsongoogle-docs-api

How to update google doc using google docs api (Python)


I'm new to Google Docs api and want to be able to add text using the replaceText option. How would I set this up? I am doing this in Python 3.6


Solution

  • Just follow the steps from Google Docs API quickstart using Python. Then try to run this code to insert text using InsertTextRequest method:

    requests = [
         {
            'insertText': {
                'location': {
                    'index': 25,
                },
                'text': text1
            }
        },
                 {
            'insertText': {
                'location': {
                    'index': 50,
                },
                'text': text2
            }
        },
                 {
            'insertText': {
                'location': {
                    'index': 75,
                },
                'text': text3
            }
        },
    ]
    
    result = service.documents().batchUpdate(
        documentId=DOCUMENT_ID, body={'requests': requests}).execute()
    

    To insert text into a document, use the BatchUpdate method and include an InsertTextRequest with the text and location as the payload. It's better to use this suggested method in the documentation.