Code for APIcall

So my approach to web APIs is to avoid all of the unnecessary details of the HTTP protocol. See what parts of HTTP are not useful today.

So for API calls done the way I would architect a modern web application, it’s fine just to reduce cognitive load and only do the calls one way using the HTTP “POST” method and just send the call data as JSON.

Also not much point having an error callback. It’s easier just to log it to console since it’s either going to be:

  • The programmer has made a mistake - they need to correct it.

  • Or we have lost network connection to the back end of the application - error detection of this needs to be handled as a separate concern rather than randomly intermingled with the all the AJAX calls of the application.

  • Because we have limited our scope to API calls that only involve JSON we can very much simplify how a framework like jQuery would handle these calls - we don’t need to compromise simplicity of the core for edge cases. In the same theme we don’t need to support functionality like promises.

  • Also it makes more sense to name this as an APIcall - let the name convey meaning for our application abstraction rather than emphasize the history of how we got here.

To run this code you will need to have a web server since for security reasons browsers won’t accept AJAX requests using URLs off the file system.

function APIcall(ApiPath,CallData, OnSuccessCallback){ var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE){ if (xmlhttp.status == 200) { OnSuccessCallback(JSON.parse(xmlhttp.responseText)); } else { console.log("APIcall failed", xmlhttp, ApiPath, CallData); } } }; xmlhttp.open("POST", ApiPath, true); xmlhttp.send(JSON.stringify(CallData)); }