How to insert content into a Google Doc using API?

I’ve managed to create an empty Google Doc on Google Drive using the API, but I’m stuck on how to add text to it. Here’s what I’ve got so far:

file_info = {
    'title': 'My Document',
    '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 Exception as e:
    print(f'Oops! Something went wrong: {e}')

This code creates a blank document, but I can’t figure out how to put any content in it. Is there a way to add text when creating the doc or update it afterward? Any help would be great!

I’ve actually worked with the Google Docs API quite a bit, and I can share what I’ve learned. To add content to your newly created doc, you’ll need to use the Google Docs API separately from the Drive API. Here’s a basic approach:

First, authenticate with the Docs API. Use the documents().get() method to fetch the existing document and then use documents().batchUpdate() to insert content.

Here’s a rough example of how you might do this:

from googleapiclient.discovery import build

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

document = docs_service.documents().get(documentId=doc_id).execute()

requests = [
    {
        'insertText': {
            'location': {
                'index': 1
            },
            'text': 'Hello, this is some inserted text!'
        }
    }
]

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

This should insert the text at the beginning of your document. You can adjust the index and text values as needed. Hope this helps!

hey, u can use docs api’s batchUpdate to add text after doc creation. try:

requests = [{'insertText': {'location': {'index': 1}, 'text': 'your text'}}]
docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()

hope that helps!

I’ve encountered this issue before. While the Drive API is great for creating documents, you’ll need to use the Docs API to actually insert content. Here’s a straightforward approach:

Set up the Docs API service.
Use the documents().batchUpdate() method to insert text.

Here’s a code snippet to get you started:

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

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

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

This will insert the text at the beginning of your document. You can adjust the ‘index’ and ‘text’ values as needed. Remember to handle any potential exceptions for a robust implementation.