How to modify Google Docs using Google Drive API

I’m working with Google Drive API v2 and trying to update Google Documents programmatically. Previously I used the old Documents List API where I could export a doc as HTML, make changes to the content, and upload it back as a Google Document.

Now with the Drive API I’m having trouble getting the same result. Here’s what I’m trying:

auth_http = # my authenticated http client
api_service = build('drive', 'v2', http=auth_http)

# fetch the document
document = api_service.files().get(fileId=DOC_ID).execute()

# get html export
export_url = document['exportLinks']['text/html']
resp, html_content = auth_http.request(export_url)

# modify content
modified_html = html_content.replace('old_text', 'new_text')

# upload modified version
file_metadata = {
    'title': 'Updated Document',
    'description': 'Modified version',
    'mimeType': 'text/html'
}
upload_media = MediaIoBaseUpload(StringIO.StringIO(modified_html), 'text/html', resumable=False)
api_service.files().insert(body=file_metadata, media_body=upload_media)

The problem is this creates a regular HTML file in Drive instead of converting it to a proper Google Doc format. How can I make the API treat the uploaded HTML as a Google Document like the old API did?

Also having issues with resumable uploads on App Engine - getting ‘_StreamSlice’ has no len() error when resumable=True.

hey there! looks like you’re missing the conversion part - when uploading back you need to set the mimeType to ‘application/vnd.google-apps.document’ in your file_metadata instead of ‘text/html’. this tells drive api to convert your html into a proper google doc rather than just storing it as html file. should fix your main issue

The issue with your App Engine ‘_StreamSlice’ error is likely due to how StringIO handles the content length. Try using BytesIO instead and convert your HTML string to bytes first. Also make sure you’re setting the file size explicitly in the MediaIoBaseUpload constructor. I ran into this exact problem last year and switching from StringIO to BytesIO with proper encoding resolved it. For the conversion issue, as mentioned you need the google docs mimetype, but also double-check that your HTML is properly formatted - malformed HTML sometimes gets rejected during conversion and falls back to creating a regular HTML file.