How to insert content into a Google Doc using the API?

Hey everyone! I’m working on a project where I need to create Google Docs programmatically and add some text to them. I’ve managed to create empty docs using the API, but I’m stuck on how to actually put content in them.

Here’s what I’ve got so far:

file_info = {
    'title': 'My New Doc',
    'parent_folder': [folder_id],
    'type': 'application/vnd.google-apps.document'
}

try:
    new_doc = drive_api.files().create(body=file_info).execute()
    doc_id = new_doc.get('id')
except ApiError as e:
    print(f'Oops! Something went wrong: {e}')

This creates an empty doc, but how do I add text to it? Can I do it when I first create the doc, or do I need to update it afterwards? Any help would be awesome!

I’ve been in your shoes, and I can tell you that working with the Google Docs API can be tricky at first. What worked for me was using the Documents service in conjunction with the Drive API. After creating the doc, you’ll want to use the batchUpdate method to add content.

Here’s a tip from my experience: prepare your content beforehand in a structured way. I usually create a list of ‘requests’ that define text insertions, formatting, and even table creation. This approach gives you more control over the document structure.

Also, don’t forget to handle potential API errors robustly. I’ve had instances where network issues caused updates to fail, so implementing retry logic can be a lifesaver. Lastly, if you’re dealing with large documents, consider breaking your updates into smaller batches to avoid hitting API limits. Good luck with your project!

To insert content into a Google Doc using the API, you’ll need to use the Documents service, not just the Drive API. After creating the document, you can use the Documents.batchUpdate method to add content. Here’s a basic example:

from googleapiclient.discovery import build

docs_service = build('docs', 'v1', credentials=creds)

requests = [
    {
        'insertText': {
            'location': {
                'index': 1,
            },
            'text': 'Your content here'
        }
    }
]

docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()

This will insert the text at the beginning of the document. You can modify the ‘index’ and ‘text’ values to insert content at different locations or with different formatting. Remember to set up proper authentication and install the google-auth and google-auth-oauthlib libraries if you haven’t already.

hey charlottew, try using the docs service. after creatin the doc, call batchUpdate with your insertText req. works fine in my experiance. hope it hepls!