How to add content to Google Docs file using Google Drive API

I need help with adding text content to a Google Docs file through the API. Right now I can successfully create new documents using the Drive API, but they always end up empty. I want to either add text content during the creation process or update the document with text after it’s created.

Here’s my current Python code that generates an empty document:

file_details = {
    'title': 'my_document',
    'parents': [f'{parent_folder_id}'],
    'mimeType': 'application/vnd.google-apps.document'
}

try:
    new_file = drive_api.files().create(body=file_details).execute()
    doc_id = new_file.get("id")
except HttpError as err:
    print(f'Error happened: {err}')

What’s the best way to populate this document with actual text content?

I ran into this exact same issue when I first started working with Google’s APIs. The key thing to understand is that you need two separate API connections - one for Drive and one for Docs. What worked for me was establishing the Docs service right after creating the document through Drive API. Make sure you include the docs scope when setting up your credentials, something like ‘https://www.googleapis.com/auth/documents’. Once you have both services initialized, you can immediately call the batchUpdate method on your newly created document ID. The timing doesn’t matter much - you can add content immediately after creation or hours later, the document ID remains valid as long as the file exists.

yah, u cant put text just using drive api, it’s for file mgmt. after u create the doc, u need to use google docs api for adding text. try docs_service.documents().batchUpdate() with insertText for that.

The Drive API is limited to document creation and file management, meaning it can’t directly add text. After obtaining the document ID from Drive API, you should transition to the Google Docs API to insert your text. For my implementation, I used the following approach:

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

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

Ensure that both APIs are enabled in your Google Cloud project and that the appropriate scopes are set, as the Docs API requires different authentication permissions compared to the Drive API.