Skip to content

Instantly share code, notes, and snippets.

@jbroadway
Created June 27, 2012 17:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbroadway/3005678 to your computer and use it in GitHub Desktop.
Save jbroadway/3005678 to your computer and use it in GitHub Desktop.
API wrapper example for use with Elefant's Restful class
// the api for accessing the site
var api = (function ($) {
var self = {};
// the prefix for api requests
self.prefix = '/myapi/v1/';
// enable/disable debugging output to the console
self.debug = false;
// helper function to verify parameters
var _has = function (obj, prop) {
return obj.hasOwnProperty (prop);
};
// console log wrapper for debugging
var _log = function (obj) {
if (self.debug) {
console.log (obj);
}
return obj;
};
// an api call to /myapi/v1/item/info
self.item_info (data, callback) {
// verify an id value has been passed
if (! _has (data, 'id')) {
throw new Error ('api.item_info() - Missing parameter: id');
}
$.get (
_log (self.prefix + 'item/info?id=' + data.id),
callback
);
return self;
};
// a post api call to /myapi/v1/item/update
self.item_update (data, callback) {
// ...verify parameters...
$.post (
_log (self.prefix + 'item/update'),
data,
callback
);
return self;
};
return self;
})(jQuery);
<script src="jquery.js"></script>
<script src="api.js"></script>
<script>
$(function () {
// call /myapi/v1/item/info
api.item_info ({id: 123}, function (res) {
if (! res.success) {
alert (res.error);
return;
}
// success!
console.log (res.data);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment