Search code examples
google-apigoogle-docsgoogle-docs-api

google docs api delete all content


I noticed from the google docs API

I can do

{
  "requests": [
    {
      "deleteContentRange": {
        "range": {
          "startIndex": 1,
          "endIndex": 80
        }
      }
    }
  ]
}

but if the endindex is greater than the total length of characters in the document, I get the following error:

{
  "error": {
    "code": 400,
    "message": "Invalid requests[0].deleteContentRange: Index 79 must be less than the end index of the referenced segment, 7.",
    "status": "INVALID_ARGUMENT"
  }
}

but I just want to delete all of the content, even though I don't know the end range value.

So: is it possible to get the endIndex somehow, or delete all content another way?


Solution

    • You want to delete all contents in Google Document using Docs API.

    If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

    Issue:

    In the current stage, in order to use "DeleteContentRangeRequest", both values of startIndex and endIndex are required. It seems that this is the specification. So in your case, I think that is it possible to get the endIndex somehow, or delete all content another way? leads to the method for resolving your issue.

    Flow of workaround:

    Here, as the workaround, the following flow is used.

    1. Retrieve the object of content from Google Document.

    The sample curl command is as follows. When you use this, please set the Document ID. In this case, body.content(startIndex,endIndex) is used as the fields. By this, it is easy to see the response value.

    curl \
      'https://docs.googleapis.com/v1/documents/###?fields=body.content(startIndex%2CendIndex)' \
      --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
      --header 'Accept: application/json'
    

    The response value is like below.

    {
      "body": {
        "content": [
          {"endIndex": 1},
          {"startIndex": 1, "endIndex": 100},
          {"startIndex": 100, "endIndex": 200}
        ]
      }
    }
    
    • endIndex of the last index of content is the value for this.

    2. Retrieve endIndex from the object.

    From above response value, it is found that startIndex and endIndex are 1 and 199, respectively. If endIndex is 200, an error occurs. Please be careful this. So please reduce 1 from it.

    3. Delete all contents using startIndex and endIndex.

    The sample curl command is as follows.

    curl --request POST \
      'https://docs.googleapis.com/v1/documents/###:batchUpdate' \
      --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
      --header 'Accept: application/json' \
      --header 'Content-Type: application/json' \
      --data '{"requests":[{"deleteContentRange":{"range":{"startIndex":1,"endIndex":199}}}]}'
    

    References:

    If I misunderstood your question and this was not the direction you want, I apologize.