Monday 30 June 2014

Download a Spreadsheet from Google Docs

The following is my research into the Google APIs and how to successfully download a spreadsheet.

Auth Token

The method used for authorisation in this article is the ClientLogin Interface. This endpoint is accessible from a HTTP endpoint, which is ideal for a shell script.

The interface also requires the caller to specify the type of service that will be accessed which we can specify in the script.

This kind of interface is appropriate for applications which are installed on a users system, as they require the username and password of the user to perform their action.

Spreadsheet Application

The spreadsheet export feature is a little trickier to find API documentation for. Instead the URL was derived by looking at the URL the browser uses for the same function.

Script

The following is the script which I put together using CURL to perform the download.

 # Download Google Docs Spreadsheet  
 # google-login  
 # Performs a login operation against the Google ClientLogin endpoint to acquire the access token.  
 #   
 # For more details on request parameters, see:  
 # https://developers.google.com/accounts/docs/AuthForInstalledApps#Request  
 #  
 # This function needs to know the service that this auth token will be used for.  
 # This is covered in the following FAQ:  
 # https://developers.google.com/gdata/faq#clientlogin  
 #  
 # Parameters:  
 # 1 - Google E-mail address  
 # 2 - Google Password  
 # 3 - Service name  
 AUTH=  
 google-login() {  
     URL="--silent"  
     URL="$URL https://www.google.com/accounts/ClientLogin"  
     URL="$URL --data-urlencode Email=$1"  
     URL="$URL --data-urlencode Passwd=$2"  
     URL="$URL -d accountType=HOSTED_OR_GOOGLE"  
     URL="$URL -d source=Google-cURL-Example"  
     URL="$URL -d service=$3"  
     # Make the call and parse the auth token.  
     AUTH=`curl $URL | grep Auth= | sed -E 's/=/ /' | cut -d ' ' -f 2`  
 }  
 # spreadsheet-download  
 # Uses a given auth token to download the named Google Spreadsheet.  
 #  
 # Parameters:  
 # 1 - Auth token  
 # 2 - File ID  
 # 3 - Format: xls or csv  
 spreadsheet-download() {  
     curl --silent --header "Authorization: GoogleLogin auth=$1" "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=$2&hl&exportFormat=$3"  
 }  
 # Takes the given login credentials and performs a login, followed by a download  
 # operation for a Google Spreadsheet.  
 #  
 # Parameters:  
 # 1 - Google Email  
 # 2 - Google password  
 # 3 - Document File ID  
 download-as-xls() {  
     google-login "$1" "$2" wise  
     spreadsheet-download "$AUTH" "$3" xls  
 }  
 download-as-xls joe@blogs.com password 0123456789ABCDEFGHIJKLMNOPQURSTUWXYZ  

Feel free to use in your own projects.

No comments:

Post a Comment