Search code examples
rubygoogle-docsgoogle-docs-api

Write text to a google doc file with google-api-ruby-client


I'm trying to write some text into a new google doc file using the google-api-ruby-client.

I think the following should work, but it doesn't:

file_metadata = {
  name: "Testing",
  mime_type: 'application/vnd.google-apps.document'
}

@drive.create_file(file_metadata,
                   fields: 'id',
                   upload_source: StringIO.new("tt"),
                   content_type: 'text/text')

When I run this I get Google::Apis::ClientError: badRequest: Bad Request


UPDATE: After Tanaike posted the correct answer below, I also had to move the file as it was created in the root directory of my service user. The final (working) code looks like this

file_metadata = {
  name: "Filename",
  mime_type: 'application/vnd.google-apps.document'
}

file = @drive.create_file(file_metadata,
                   fields: 'id,parents',
                   upload_source: StringIO.new("Text to go in file"),
                   content_type: 'text/plain')

current_parent = file.parents.first
@drive.update_file(file.id, nil,
                   add_parents: "#{@folder_id}",
                   remove_parents: "#{current_parent}")

Solution

  • How about this modification? In this case, the mimeType of text is text/plain.

    From:

    content_type: 'text/text'
    

    To:

    content_type: 'text/plain'
    

    Note:

    • In my environment, when I use content_type: 'text/text', the same error occurs. And when I use content_type: 'text/plain', the Google Document including the text of tt is created to the root folder on Google Drive.
    • In this case, it supposes that your @drive can be used for uploading a file.

    Reference: