pythongoogle-docs-api

Google API batch update giving HTTP 400 error. Python


The Google API for docs is giving me HTTP 400 error.

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://docs.googleapis.com/v1/documents/1Z2rAi7CJINAwxzizOsIw0_UB1iguHaduIDBV5cOZ4iQ:batchUpdate?alt=json returned "Invalid requests[0].insertText: The insertion index must be inside the bounds of an existing paragraph. You can still create new paragraphs by inserting newlines.">

I have searched all over the place to find it. it is to insert in a blank document. it says to add a new paragraph but I don't know how to.

title = 'My Document'
text1 = "hi this is the first one"
text2 = "hi this is the first one"
text3 = "hi this is the first one"
body = {


        'title': title

    }
    requests = [
        {
            'insertText': {
                'location': {
                    'index': 0,
                },
                'text': text1
            }
        }
    ]




doc = service.documents().create(body=body).execute()
print('Created document with title: {0}'.format(
        doc.get('title')))
docid = doc.get('documentId')
print(docid)
result = service.documents().batchUpdate(documentId=docid, body={'requests': requests}).execute()

the compelte error message is this:

"E:/Python/News Uploader to Google Driver/venv/Scripts/quickstart.py"
Created document with title: My Document
1Z2rAi7CJINAwxzizOsIw0_UB1iguHaduIDBV5cOZ4iQ Traceback (most recent
call last):   File "E:/Python/News Uploader to Google
Driver/venv/Scripts/quickstart.py", line 76, in <module>
    main()   File "E:/Python/News Uploader to Google Driver/venv/Scripts/quickstart.py", line 70, in main
    result = service.documents().batchUpdate(documentId=docid, body={'requests': requests}).execute()   File "E:\Python\News Uploader
to Google Driver\venv\lib\site-packages\googleapiclient\_helpers.py",
line 130, in positional_wrapper
    return wrapped(*args, **kwargs)   File "E:\Python\News Uploader to Google Driver\venv\lib\site-packages\googleapiclient\http.py", line
856, in execute
    raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: <HttpError 400 when requesting
https://docs.googleapis.com/v1/documents/1Z2rAi7CJINAwxzizOsIw0_UB1iguHaduIDBV5cOZ4iQ:batchUpdate?alt=json
returned "Invalid requests[0].insertText: The insertion index must be
inside the bounds of an existing paragraph. You can still create new
paragraphs by inserting newlines.">

Process finished with exit code 1

Solution

  • In your request you should specify the location index as 1, since Google API is indexed from 1

    requests = [
            {
                'insertText': {
                    'location': {
                        'index': 1,
                    },
                    'text': text1
                }
            }
        ]