I’m working on a Python project that needs to generate documents through the Google Docs API. I’ve been following the official documentation but running into issues.
Here’s my current attempt:
import os
import json
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/documents']
def create_document():
credentials = None
if os.path.exists('auth_token.json'):
with open('auth_token.json', 'r') as file:
credentials = Credentials.from_authorized_user_file('auth_token.json', SCOPES)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
auth_flow = InstalledAppFlow.from_client_secrets_file(
'client_secret.json', SCOPES)
credentials = auth_flow.run_local_server(port=8080)
with open('auth_token.json', 'w') as file:
file.write(credentials.to_json())
docs_service = build('docs', 'v1', credentials=credentials)
document_data = {
'title': 'New Report'
}
result = docs_service.documents().create(body=document_data).execute()
print(f'Document created: {result.get("title")}')
if __name__ == '__main__':
create_document()
The script runs without errors but prints “Document created: None” instead of showing the actual title. I’ve tried different permission scopes and authentication methods but still can’t get it working properly. Has anyone encountered this before? What could be causing the document creation to fail silently?