A Simple JavaScript API

Getting started building an API can be tough if all you’re looking at are big, monstrous (but useful) APIs. To combat this, I’ve built a really simple API to redirect users based on the hash in their URL. It initializes, take external data, and returns a response block.


Download the API and Example

The Code

var jsRedirector = {
	//Initialize the API with data (initData). goAhead (Boolean) tells it whether or not to do the redirect.
	init : function (initData, goAhead) {
		this.data = initData;
		if (goAhead) {
			return (this.go());
		} else {
			return {
				loaded : true,
				go : false,
				msg : "Data loaded. No redirect per user request.",
				title : null,
				url : null
			};
		}
	},
	//This is what actually does the redirection.
	//Can be called manually (jsRedirector.go() or called by the init method with goAhead set to true.)
	go : function () {
		if (window.location.hash !== '') {
			var chosen = this.data[window.location.hash.substr(1)];
			if (typeof chosen !== "undefined") {
				document.location = chosen.url;
				return {
					loaded : true,
					go : true,
					msg : "URL found. Activating redirect to " + chosen.title + ".",
					title : chosen.title,
					url : chosen.url
				};
			} else {
				return {
					success : false,
					go : false,
					msg : "Unable to find a matching entry for the hash provided.",
					title : null,
					url : null
				};
			}
		} else {
			return {
				success : false,
				go : false,
				msg : "No hash provided in URL. Cannot redirect.",
				title : null,
				url : null
			};
		}
	}
};

The Example

var urls = {
	home : {
		title : "Home Page",
		url : "http://www.brianrollins.com"
	},
	google : {
		title : "Google",
		url : "http://www.google.com"
	},
	youtube : {
		title : "YouTube",
		url : "http://www.youtube.com"
	},
	facebook : {
		title : "Facebook",
		url : "http://www.facebook.com"
	},
	twitter : {
		title : "Twitter",
		url : "http://www.twitter.com"
	}
};
var response = jsRedirector.init(urls, true);

The Optional Stuff

//This adds some optional user feedback
//based on the response from jsRedirector.
if (response.loaded && response.go) {
	document.getElementById("message").innerHTML = "Redirecting to " + response.title;
} else if (response.loaded && !response.go) {
	document.getElementById("message").innerHTML = "Data loaded successfully.";
} else {
	document.getElementById("message").innerHTML = "There was a problem with the data retrieved. Unable to redirect you. Sorry.";
}

The Explanation

So, let’s look at our data first. in the Example, check out var urls. As you can see, the data is just a simple object with keys. Each key has a title and URL. That’s it. No muss, no fuss. Your API will have a lot more moving parts, more than likely, but we’re sticking with the basics here. This method allows you to easily add or remove URLs from the list as you need. You could even hook this up to some service and load the object on the fly from AJAX.

Line 30 is the piece that gets things going with jsRedirector. It initializes it and passes in the URL data block and the true flag to tell the code to go ahead and do the redirect. It’s probably overthinking it to have the flag, but you’ve got to be flexible. For example, a user may want to delay the redirect for a few seconds. Actually, that’s not a bad idea for version 2. Maybe I’ll add a delay to the API for future use.

The Optional Stuff is an example of where the Dev using the API can get creative. This code is merely reacting to the response the API returns. This way the Dev can address failures or pass along success messages (in case the website we’re going to is slow to load).

Now, let’s have a look at the Code itself.

Line 1, we’re creating an object. Now everything that’s attached to it is in its own namespace (jsRedirector.xxxxx). Very handy for avoiding code collision.

Lines 3-16 build the init method. This pulls in the initial data and can (optionally) fire the go method when it’s done. It returns an object that gives the user some important info (success/failure and other details).

Starting on Line 19, we have the actual workhorse of the API, the go method. Invoking it examines the URL for a hash and acts on it. Starting on Lines 24, 32, and 41, the go method returns an object for user feedback. You don’t have to act on it, but it’s a good practice to do so. Otherwise, the dev using your code can’t have their software react to failure cases.

You may have noticed I’ve avoided using any console.logs in the code itself. There’s debate on whether or not to use them in production code. I vote for not using them, and instead use responses from the API. It’s up to the end-user on whether or not to throw code to the console. Run with your console open on other people’s sites. The amount of logging coming out is startling. And sometimes it puts info out you might not want the average person seeing.

Full disclosure: I use console.logs all the time in development, I just try to strip them out when I release the code. Nothing wrong with that, in my mind.

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.