Often in an Angular JS web application (or any other front-end framework) we want to make a call to an API which needs to be authenticated with an API key (a unique code assigned to us by the API provider) using the $http service. We want to keep our API key secret and so don’t want to put in our .js files where it can be viewed, and then used, by anyone but JavaScript is all on the client-side so how do we keep our key safe?

In the case of the Bristol and Bath Live Parking page I built on top of The Bristol API, I was initially just hard-coding the API key in to get something working but that’s very bad form so I’ve put together a really simple API proxy using PHP which I can call from my JavaScript code without an API key and my PHP code will pass on the API request with the API key inserted in on the server and then return the result from the API back to the client without the API key ever being visible on the client-side (ie to the browser).

Although this one is tailored towards the structure of Bristol API calls, the principle is very applicable to any other API we might want to send requests to.

<?php
$apiKey = 'XXXXXXKEEPSECRETXXXXXX';
$apiRoot = 'https://bristol.api.urbanthings.io/api/2.0/';

if(!isset($_GET['endpoint'])) die(); // if we don't have any endpoint parameter we return an empty page

// Build up the URL as https://bristol.api.urbanthings.io/api/2.0/END/POINT/?apiKey=XXXXXXKEEPSECRETXXXXXX
$url = $apiRoot . $_GET['endpoint'] . '?apiKey=' . $apiKey;

// Now add any additional GET parameters https://bristol.api.urbanthings.io/api/2.0/END/POINT/?apiKey=XXXXXXKEEPSECRETXXXXXX&param1=value&param2=value
foreach ($_GET as $key => $value) {
	if ($key != 'endpoint') {
		$url = $url . '&' . $key . '=' . $value;
	}
}

// Send the request to the API and return the result to the client
$outData = file_get_contents($url);
print_r($outData );
?>

Very simple. To use it we can just make a call in our JavaScript to our PHP page instead of calling the URL directly…

"https://bristol.api.urbanthings.io/api/2.0/END/POINT/?apiKey=XXXXXXKEEPSECRETXXXXXX&param1=value&param2=value"

…we call our proxy at our own URL using the $http service or equivalent…

"http://curlybrackets.co/api/bristolapi?endpoint=END/POINT&param1=value&param2=value"

No API key in our JavaScript but all the API functionality available to us in our front-end code with just a few simple lines of PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>