Client-Side API Calls Now Available!
January 6, 2020
Zip API US now allows you to perform client-side calls. In order to make client-side calls, do the following:
- Generate a js key from your account by going to your dashboard.
- Add the domain(s) from which you will be performing your client-side calls.
Your js key is only used for client-side calls while your primary api key is designed for server-side calls. If you do not add your domain(s), your calls will receive a cross-origin request (CORS) error.
Client-Side Demo
Client-Side Response:
...
Client-Side Sample Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="clientside-demo">
<div class="row">
<div class="col-lg-12">
<h2>Client Side Demo</h2>
<p> </p>
<form>
<div class="row ">
<div class="col-md-6">
<div class="form-group zip-box">
<input type="text" name="zipcode" class="form-control form-control-alternative" placeholder="Enter Any Zipcode">
</div>
</div>
<div class="col-md-6">
<button class="btn btn-info" type="submit" id="submit">Perform Lookup</button>
</div>
</div>
</form>
</div>
</div>
<p>Client-Side Response:</p>
<div class="response">-</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var clientKey = "your js key";
var cache = {};
var container = $("#clientside-demo");
var responseDiv = container.find("div.response");
//response
function displayResponse(response)
{
responseDiv.text(JSON.stringify(response));
}
// Set up event handlers
$("#submit").click(function(e) {
e.preventDefault();
// Get zip code
var zipcode = $('input[name="zipcode"]').val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
responseDiv.empty();
// Check cache
if (zipcode in cache)
{
displayResponse(cache[zipcode]);
}
else
{
//url
var url = "https://service.zipapi.us/zipcode/" + zipcode + "?X-API-KEY=" + clientKey;
// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
// Store in cache
cache[zipcode] = data;
displayResponse(data);
}).fail(function(data) {
data = $.parseJSON(data.responseText);
// Store in cache
cache[zipcode] = data;
displayResponse(data);
});
}
}
});
});
</script>
</body>
</html>