I'm trying to create a Google Docs on Google drive, with some text inside the Docs. I'm already creating the Docs via api, but i only can update a blank archive.
Does anyone know how to update the text inside the doc and/or add the information when the docs is created?
This piece of code creates the blank docs in python:
doc_metadata = {
'name': 'docs_name',
'parents': [f'{folder_id}'],
'mimeType': 'application/vnd.google-apps.document'
}
try:
doc = drive_service.files().create(body=doc_metadata).execute()
documentId = doc.get("id")
except HttpError as error:
print(f'An error occurred: {error}')
TRY:
#Authentication
SCOPES = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/documents']
doc_metadata = {
'name': 'docs_name',
'parents': [f'{folder_id}'], #FolderID
'mimeType': 'application/vnd.google-apps.document'
}
#Service Builder
service_docs = build('docs', 'v1', credentials=creds)
service_drive = build('drive', 'v3', credentials=creds)
#Creating document file using the drive API
try:
doc = service_drive.files().create(body=doc_metadata).execute()
DOCUMENT_ID = doc.get("id")
except HttpError as error:
print(f'An error occurred: {error}')
new_text = 'This is a sample sentence for the newly created document'
requests = [
{
'insertText': {
'location': {
'index': 1,
},
'text': new_text
}
}
]
#Inserting text using insertText request from Google docs API
result = service_docs.documents().batchUpdate(
documentId = DOCUMENT_ID, body={'requests': requests}).execute()
To insert text into a document, use the BatchUpdate
method and include an InsertTextRequest
with the text and location as the payload.
Moreover, you need Drive API to create document and Docs API to edit document.
Reference: Insert, delete, and move text