Search code examples
node.jsgoogle-docsgoogle-docs-api

Why is the equation object empty in json when returned from the google doc api?


I am trying to fetch the google doc content using the google doc api but I see that the json returned from the google doc api is missing eqaution information.

Example content :- google doc excerpt Example request :-

const baseUrl = `https://docs.googleapis.com/v1/documents/${doc_id}`
    const response = await googleReq(baseUrl, ctx.accessToken).then(res => {
        let data = res.json()
        return data
    }).catch(err => console.log(err))

const googleReq = (url, token) => {
    if (!token) return new Error("No accessToken")
    return fetch(url, {
        method: 'GET',
        headers: {
            Authorization: `Bearer ${token}`
        }
    })
}

example response :- 
...
{
   "startIndex": 321,
   "endIndex": 330,
   "equation": {}
}
...

As you can see the equation block is not returning anything. I am not sure why it would be the case.


Solution

  • Answer:

    Unfortunately, at present, you can not get equation information from the Google Docs API.

    More Information:

    As per the developer documentation, the equation block returned by the API should contain:

    • suggestedInsertionIds[]
    • suggestedDeletionIds[]

    These IDs would be alphanumeric strings which indicate the suggestions that an editor would have inserted or deleted.

    This block will not contain any equation text or other related info.

    The Only Way:

    At present, there is only one to get the equation text programmatically, and that is using Google Apps Script methods.

    An example script to do this would be:

    // Copyright 2021 Google LLC.
    // SPDX-License-Identifier: Apache-2.0
    
    function getEquations() {
    
      const searchElementType = DocumentApp.ElementType.EQUATION
      const documentBody = DocumentApp.getActiveDocument().getBody()
      const searchResult = null
    
      while (searchResult = documentBody.findElement(searchElementType,searchResult)) {
        let par = searchResult.getElement().asEquation()
        console.log("Search Result : " + par.getText())
      }
    }
    

    As a workaround, you could deploy this as a web app which serves the equation text as JSON content, and then use the fetch API in JavaScript to get this data rather than using the Google Docs API directly.

    Feature Request:

    You can however let Google know that this is a feature that is important for access to their APIs, and that you would like to request they implement it.

    Google's Issue Tracker is a place for developers to report issues and make feature requests for their development services, I'd urge you to make a feature request there. The best component to file this under would be the Google Docs component, with the Feature Request template.

    References:

    References for Web App-based Workround: