Sunday, January 25, 2015

Curl C to google sheets

A quick post about using the CURL C API to upload data to google spreadsheets. I used it upload temperature and humidity data that I am tracking at home. There are a few steps

1.) create a google spreadsheet the normal way (with headings for each data item you want to save)

2.) get auth from google:
                curl_easy_setopt(curl, CURLOPT_URL, "");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "Email=YOUREMAIL&Passwd=YOURPASSWORD&accountType=GOOGLE&source=cURL&service=writely");

3.) Form your data in the correct XML format:
      sprintf(postData, "<entry xmlns='' xmlns:gsx=''> <gsx:date>%s</gsx:date>  <gsx:time>%s</gsx:time>  <gsx:temp>%f</gsx:temp>  <gsx:relhum>%f</gsx:relhum><gsx:location>%d</gsx:location><gsx:device>oregon</gsx:device></entry>", 
dateStr, timeStr, s->getTemperature(), s->getHumidity(), s->getChannel());

4.) Post the data with the correct fields to the spreadsheet:
                        curl_easy_setopt(curl, CURLOPT_URL, "");
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postData));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData);
curl_easy_setopt(curl, CURLOPT_POST, true);

struct curl_slist *headerlist=NULL;
char authHeader[600];
sprintf(authHeader, "Authorization: GoogleLogin auth=%s", g_auth);
cout << "auth header " << authHeader << endl << flush;
headerlist = curl_slist_append(headerlist, authHeader);
headerlist = curl_slist_append(headerlist, "GData-Version: 3.0");
headerlist = curl_slist_append(headerlist, "Content-Type: application/atom+xml");

Full function code at

No comments: