How can I upload a local CSV file to Google Drive using the Drive API v2 so that the uploaded file is in the native Google Spreadsheet format. Preferably in Python, but a raw HTTP request will suffice.
What I tried:
request body content-type: 'application/vnd.google-apps.spreadsheet', media_body content-type: 'text/csv'. --> 401 Bad Request
request body content-type: 'application/vnd.google-apps.spreadsheet', media_body content-type: 'application/vnd.google-apps.spreadsheet'. --> 400 Bad Request
... (a couple of others such as leaving a property out and similar, usually got 400 or Drive didn't recognise it as a native spreadsheet)
Claudio Cherubino's answer is correct -- you have to add the parameter manually. Since you asked in Python though, here's a concrete example:
Java :
(Mar 2017) Note, while the question specifically asks about Drive API v2, developers should know that the Google Drive API team released v3 at the end of 2015, and in that release,
insert()
changed names tocreate()
so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C to upload a file and another that imports a CSV file as a Google Sheet.
Just to show up straightforward it is, below is one alternate Python solution (to the sample in the docs) for short files ("simple upload") where you don't need the
apiclient.http.MediaFileUpload
class. This snippet assumes your auth code works where your service endpoint isDRIVE
with a minimum auth scope ofhttps://www.googleapis.com/auth/drive.file
.Your insert request should specify
text/csv
as the content-type. The trick to get the file converted is to add the?convert=true
query parameter to the request url:https://developers.google.com/drive/v2/reference/files/insert
The best way to get started is using the web form at https://developers.google.com/drive/v2/reference/files/insert#try-it