Facebook Graph API (JavaScript) – Real Quick Start

I have found the “QuickStart” and API documentation to be rather lacking for developers who have never worked with Facebook before. Sure they provide all the pieces but there is not a “Here is an example of how to use all the pieces together” example. So … here it is.

First you need an in page element Facebook can attach it is self to, this element by default is a div with the id “fb-root”.

<div id="fb-root"></div>

Next we need to establish a session with Facebook from our site. This is done by a simple initialization script.

window.fbAsyncInit = function() {
FB.init({
appId        : '[appId Assigned to your app]',
              		xfbml        : false,
              		version      : 'v2.2'
            	});
};

(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
            	if (d.getElementById(id)) {return;}
             	js = d.createElement(s); js.id = id;
             	js.src = "//connect.facebook.net/en_US/sdk.js";
             	fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Now we are ready to request data, since most Graph calls require an Access Token I think it makes since to define a variable.

var access_token = "access_token=[access token assigned to you]";

To request data you will be making a GET call, something similar to the following will print the result into your console.

FB.api(
"/v2.2/me?fields=id,name&" + access_token,
function (response) {
if (response && !response.error) {
			Object.getOwnPropertyNames(response).forEach(function(val, idx, array) {
				console.log(val + ' -> ' + response[val]);
			});
}
	}
);

Now let’s put it all together.

<!DOCTYPE html>
<html>
    <head>
        <title>Facebook Graph API JavaScript Example</title>
        <meta charset="UTF-8">
    </head>
    <body>
		<script>
			var access_token =[access token assigned to you]";
        	window.fbAsyncInit = function() {
            	FB.init({
              		appId        : '[appId Assigned to your app]',
              		xfbml        : false,
              		version      : 'v2.2'
            	});

				FB.api(
					"/v2.2/me?fields=id,name&" + access_token,
					function (response) {
				  		if (response && !response.error) {
							Object.getOwnPropertyNames(response).forEach(function(val, idx, array) {
								console.log(val + ' -> ' + response[val]);
							});

				  		}
					}
				);

          };

          (function(d, s, id){
             var js, fjs = d.getElementsByTagName(s)[0];
             if (d.getElementById(id)) {return;}
             js = d.createElement(s); js.id = id;
             js.src = "//connect.facebook.net/en_US/sdk.js";
             fjs.parentNode.insertBefore(js, fjs);
           }(document, 'script', 'facebook-jssdk'));

        </script>

        <div id="fb-root"></div>
    </body>
</html>

SOLUTION: