PHP cURL to Google Civic API

Well, this stumped me for like an hour.

The Google Civic Information API is a handy way to grab voting and elected official information. The current way I do that on GeoPortal is to enter some representative information locally and update it when somebody emails me in ALL CAPS. That is not a good way.

But the Google Civics API’s representative service (oddly) only does POST, and POST doesn’t do JSONP, necessitating a proxy. And to further complicate things, it isn’t a straight-forward cURL operation - you have to send the POST argument as JSON and not the default x-form or you’ll get an error message. So, do this:

civicproxy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// The only arguments are "address" and "callback" (the latter optional for JSONP)

$url = "https://www.googleapis.com/civicinfo/us_v1/representatives/lookup?key=_your_api_key_here_";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);

// I swore a lot over these next two lines
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"address":"' . $_GET["address"] . '"}');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$json = curl_exec($ch);

curl_close($ch);

// if a callback is set send back jsonp
echo isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;

And then a little jQuery to eat it.

1
2
3
4
5
6
7
8
9
10
11
$.ajax({
url: 'civicproxy.php',
type: 'GET',
dataType: 'json',
data: {
'address': activeRecord.address
},
success: function (data) {
// do magical things
}
});