Skip to content

Instantly share code, notes, and snippets.

@dthapa
Last active August 29, 2015 13:57
Show Gist options
  • Save dthapa/9794272 to your computer and use it in GitHub Desktop.
Save dthapa/9794272 to your computer and use it in GitHub Desktop.
A simple Javascript/HTML script used to access ES APIs, both GET and POST. Replace code with your api key and input.
<!--
A simple Javascript/HTML script demonstrating GET and POST calls.
Can also adjust to Http/Https request
Download and load the in either Chrome or Firefox and follow the instructions.
The examples demonstrate one "CORS" API and one that isn't.
-->
<html>
<head>
<script>
function http_request(url, method, post_data){
var client = null;
client = new XMLHttpRequest();
client.open(method, url, false );
client.setRequestHeader("Content-Type", "application/json");
document.getElementById("request_url").innerHTML = "<a href=" + url + ">" + url + "</a>";
document.getElementById("response_headers").innerHTML = "Traffic should be in Chrome/FF's dev tools' network tabs";
document.getElementById("response_body").innerHTML = "Traffic should be in Chrome/FF's dev tools' network tabs";
client.send(post_data);
document.getElementById("request_url").innerHTML = url;
document.getElementById("response_headers").innerHTML = client.getAllResponseHeaders().toLowerCase();
document.getElementById("response_body").innerHTML = client.responseText;
}
function get_response_cors(){
var url = "https://stage-api.target.com/products/v3/saleable_quantity_by_location?key=your_key";
var post_data = '{"products":[{"product_id":"243-19-9033","desired_quantity":1}],"nearby":"55430","radius":15,"multichannel_options":[{"multichannel_option":"none"}]}';
http_request(url, "POST", post_data);
}
function get_response_nocors(){
var url = "https://api.target.com/v2/store/2228?locale=en-US&key=your_key";
http_request(url, "GET", null);
}
</script>
</head>
<body>
<p><b>Before clicking Send, from inside Chrome or Firefox, Hit 'F12' <br />
to enable developer mode. Click on the Network tab and see the API <br />
transaction info. Headers, Response and Timing are all available. <br />
The products/v3 api allows <a href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS</a> -
Access-Control-Allow-Origin:* <br />
So you can see its response in this browser directly. <br />
For other APIs, Chrome/FF's dev tools, still show the Network info at least.</b></p>
<button type="button1" onclick="get_response_cors()">Send [Browser + DevTools]</button>
<button type="button2" onclick="get_response_nocors()">Send [DevTool only]</button>
<h3>-- URL --</h3>
<div id="request_url"></div>
<h3>-- Response Headers -- </h3>
<div id="response_headers"></div>
<h3>-- Response body --</h3>
<div id="response_body"></div>
</body>
</html>
<!-- small edit -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment