How to insert content into a Google Doc via API?

I’ve managed to create a new Google Doc using the API, but it’s coming up blank. I’m stumped on how to add text to it right away. Here’s what I’ve got so far:

file_info = {
    'name': 'my_document',
    'parents': [f'{parent_folder}'],
    'mimeType': 'application/vnd.google-apps.document'
}

try:
    new_file = drive_api.files().create(body=file_info).execute()
    doc_id = new_file.get('id')
except APIError as e:
    print(f'Oops, something went wrong: {e}')

This creates the doc, but it’s empty. How can I add some initial text when I make it? Or is there a way to update it right after creation? Any help would be awesome!

I’ve been working with the Google Docs API for a while now, and I’ve found that adding content right after creation is indeed possible. After you’ve created the document, you’ll need to use the Documents service to insert text. Here’s what’s worked for me:

First, make sure you have the docs service set up:

docs_service = build(‘docs’, ‘v1’, credentials=your_creds)

Then, you can use the batchUpdate method to insert text:

requests = [
{‘insertText’: {‘location’: {‘index’: 1}, ‘text’: ‘Your initial content goes here.’}}
]
docs_service.documents().batchUpdate(documentId=doc_id, body={‘requests’: requests}).execute()

This approach has always worked smoothly for me. Just remember to handle any potential errors, as network issues can sometimes cause hiccups. Good luck with your project!

To insert content into your newly created Google Doc, you’ll need to utilize the Documents service of the Google Docs API. After obtaining the document ID from your initial creation step, you can use the batchUpdate method to add text. Here’s a code snippet to accomplish this:

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

content = 'This is the initial content of the document.'
requests = [
    {'insertText': {'location': {'index': 1}, 'text': content}}
]

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

This will insert the specified content at the beginning of your document. Remember to import the necessary libraries and set up your credentials correctly. If you need to format the text or add more complex elements, you can modify the ‘requests’ list accordingly.

hey there! to add content, you’ll need to use the docs API after creating the file. here’s a quick example:

from googleapiclient.discovery import build

docs_service = build('docs', 'v1', credentials=creds)
requests = [
    {'insertText': {'location': {'index': 1}, 'text': 'Your initial text here'}}
]
docs_service.documents().batchUpdate(documentId=doc_id, body={'requests': requests}).execute()

hope this helps! let me know if u need more info