View as Markdown

Step by step

One of the most common uses of the what3words API is within browser-based applications. For example, you might be using the what3words AutoSuggest Component to allow easy capture of 3 word addresses on your website. In cases like these, where a client-side JavaScript application is making calls to the public what3words API, there is a danger that your API key will be both visible inside your JavaScript application, and over the network.

To mitigate against this, you can hide your API key by proxying API calls through a proxy application running on your server.

1Step 1: Setup#

The example provided on the code tab is written in PHP. While no PHP dependencies are required, it is assumed that you have a working environment to host PHP from.

You will need a what3words API key, which should be assigned to the $base_url variable. If you don’t already have an API key, you can obtain one by registering for an account.

2Step 2: Usage#

Assuming you have the above PHP script running on your webserver, in a file called w3w_proxy.php, you should be able to call it with any valid what3words API HTTP GET request. For example, to make a convert-to-coordinates call, you could make the following HTTP request:

Endpoint
https://<domain>/w3w_proxy.php/convert-to-coordinates?words=index.home.raft

3Step 3: CORS#

It is important that efforts are taken to make sure other websites are not able to make use of your proxy.

By default, web browsers permit scripts contained in a first web page to access data from a second source, but only if both sources have the same origin. Therefore, by default, only web pages served from the same domain as your proxy will be able to make successful AJAX through the proxy.

If however, you are hosting your proxy on a different domain to your website, you will need to add the Access-Control-Allow-Origin header (with the value of your websites domain) to your proxies response headers. This allows the browser to access your resource (the proxy), even though the request is coming from a different domain. The following code snippet demonstrates how this can be achieved:

PHP
$allowed_origin = 'example.com';
header('Access-Control-Allow-Origin:' . $allowed_origin);

4Step 4: API Key Restriction Settings#

If you need to include your API key in plain text within an HTML tag, it’s critical to restrict its usage to specific applications, domains, or IPs to minimize the risk of misuse. Follow these steps to apply restrictions to your API key:

Step 1: Access API Key Restriction Settings

After creating your API key:

  1. Navigate to the API Key Restriction section of your API management interface.
  2. Choose the appropriate restriction method from the following options:
  • HTTP referrers (websites)
  • IP addresses (web servers, cron jobs, etc.)
  • iOS apps
  • Android apps

Step 2: Configure Restrictions for Your API Key

  1. HTTP Referrers (Websites)

Restrict API key usage to specific domains:

  1. Add these to allow access to your site: *.yoursiteaddress.com*/* ,* yoursiteaddress.com/*
  2. For specific restrictions:

2. IP Address Restrictions

Restrict API usage to certain IPs or subnets:

  • Single IP: 192.168.0.1
  • IPv6: 2001:db8::1
  • Subnet: 192.168.0.0/22

3. iOS Apps

  • Use the Swift/Objective-C API wrapper.
  • Add your app’s Bundle ID (found in project settings).

4. Android Apps

  • Use the Android API wrapper.
  • Add your app’s Package Name and SHA-1 fingerprint.

To find the SHA-1:

keytool -list -v -keystore mystore.keystore

Use the Package Name from AndroidManifest.xml.

Step 3: Save and Test

Once you’ve set the desired restrictions:

  1. Save the changes.
  2. Test your API key within your application or website to ensure it functions as expected under the applied restrictions.

Why Restrict API Keys?

Adding restrictions ensures that your API key can only be used by the intended application, domain, or server. Even if someone gains unauthorised access to your key, they won’t be able to use it outside the defined restrictions, adding a layer of security to your integration.

Full example

The example provided here is written in PHP. While no PHP dependencies are required, it is assumed that you have a working environment to host PHP from.

You will need a what3words API key, which should be assigned to the $base_url variable. If you don’t already have an API key, you can obtain one by registering for an account.

PHP
<?php 
	// Extract the what3words API methods - autosuggest, grid-sectiont etc
	$method = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];

	// The what3words API URL
	$base_url = 'https://api.what3words.com/v3/';

	// Extract URL parameters to be passed onto the request
	$params = "";
	foreach ($_GET as $key=>$value) {
		$params = $params . $key . '=' . urlencode($value) . '&';
	}

	// The what3words API key to use
	$key = 'MY-API-KEY';

	// Build up the URL to proxy
	$url = $base_url . $method . '?' . $params . 'key=' . $key;

	$curl = curl_init();
	$headers = [];

	curl_setopt_array($curl, array(
		CURLOPT_URL => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => 'UTF-8',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'GET',
	));

	// Read the headers back from the response
	curl_setopt($curl, CURLOPT_HEADERFUNCTION,
		function($curl, $header) use (&$headers)
		{
			$len = strlen($header);
			$header = explode(':', $header, 2);
			if (count($header) < 2) // ignore invalid headers
				return $len;

			$name = strtolower(trim($header[0]));
			if (!array_key_exists($name, $headers))
				$headers[$name] = [trim($header[1])];
			else
				$headers[$name][] = trim($header[1]);

			return $len;
		}
	);

	// Call the what3words API with the proxied request
	$response = curl_exec($curl);

	// Mimic the content type header from the actual API response
	$content_type = $headers['content-type'][0];
	header('Content-Type:' . $content_type);

	/** 
	* Return appropriate CORS headers if the proxy is hosted on a different 
	* domain to the website initiating the AJAX request
	*/
	$allowed_origin = 'example.com';
	header('Access-Control-Allow-Origin:' . $allowed_origin);

	echo $response; 	
?>
esc
↑ ↓ to choose↵ to openesc to close