As all of you know that cross domain POST is not allowed in javascript. Many APIs requires post method, such APIs become hard to use with javascript. We can not move back to GET method because the input set is limited( restricted by length or URL) on GET. So in this article i am suggeting a Post JSON API design which should be followed for making API javascript friendly.
Lets say i am designing a API which requires "text" as input in POST, and returns an JSON response.
API URL: http://api.xyz.com/myapi
API Input: text as POST field.
API Output: JSON object.
1) How client can invoke the API?
of-course cross domain HTTPXMLrequest is not allowed
Another popular technique of injecting script tag with callback to get cross domain JSON (jsonp) can not be used becuase it can only do GET request. so how to do a POST to differnet domain? Solution is you can use iframes.
- Create an iframe in javascript
- Create a form whose method is POST, action is API URL and target is the iframe.
- Create hidden input as "text" and assigned the value whatever you want.
- Submitted the form.
Here is the code
function crossDomainPost(url, text) { // Add the iframe with a unique name var iframe = document.createElement("iframe"); var uniqueNameOfFrame = "sum"; document.body.appendChild(iframe); iframe.style.display = "none"; iframe.contentWindow.name = uniqueNameOfFrame; // construct a form with hidden inputs, targeting the iframe var form = document.createElement("form"); form.target = uniqueNameOfFrame; form.action = url; form.method = "POST"; // repeat for each parameter var input = document.createElement("input"); input.type = "hidden"; input.name = "text"; input.value = text; form.appendChild(input); document.body.appendChild(form); form.submit(); }
2) How to read the output back?
Now since form is submitted in iframe, whatever is happening in iframe is not accesible to main window and vise versa becuase these two iframes are not from the same domain. So this is where you should follow my proposed design,
The API maker will return an HTML page with script block in which it sends message to parent window.
e. g. Output of PAI goes like this.
<html>
<script>
var json={your-data}
window.parent.postMessage(json,"*");
</script>
</html>
This is how client will read in his javscript code
window.addEventListener("message", function (event) {
my_callbac(event.data);
}, false);
Note: message posted is HTML5 API may not be available in many browsers.
Thanks and enjoy!!!!!
Hi there,
ReplyDeleteI have a JSON object - how can I pass this to API using your iframe?
@LJ
ReplyDeleteStringify the JSON and pass it as text to crossDomainPost function.
I am not sure whether I answered your question or not