Accessing the Facebook API using Javascript

From Knowledge Kitchen
Jump to navigation Jump to search

Facebook has a very sophisticated set of APIs. Like Twitter, Facebook's APIs uses the OAuth authentication system to authenticate both the application accessing data and the user whose data is being accessed by the application.

Facebook currently encourages developers to use their Javascript API client. The following example shows some simple methods to authenticate a user using the Facebook Javascript API client. This code outputs some messages to the console that include some data pulled from the user's Facebook account. In order to use the Facebook API, an application must be 'registered' with Facebook.

<!doctype html>
		<title>Facebook API Example</title>
		<h1>Facebook API Example</h1>
		<p>Look at the code to see.</p>

<div id="fb-root"></div>
  window.fbAsyncInit = function() {
    // init the FB JS SDK
      appId      : 'your_app_id',                    // App ID from the app dashboard
      status     : true,                                 // Check Facebook Login status
      xfbml      : true                                  // Look for social plugins on the page

    // Additional initialization code such as adding Event Listeners goes here

    //force the user to log in
	FB.login(function(response) {
	   if (response.authResponse) {
	     console.log('Welcome!  Fetching your information.... ');
	     FB.api('/me', function(response) {
	       console.log('Good to see you, ' + + '.');
	   } else {
	     console.log('User cancelled login or did not fully authorize.');

    //request the /platform API resource, and alert the response
	FB.api('/platform', function(response) {
		//if we got a response, show some data
		if (response && {

	//request the /me API resource, and alert the response (note you must be logged in to get this)
	FB.api('/me', function(response) {
		//show one part of the response object
		//alert("Welcome, " +;	
		console.log("Your name is: " +;


  // Load the SDK asynchronously
     // If we've already installed the SDK, we're done
     if (document.getElementById('facebook-jssdk')) {return;}

     // Get the first script element, which we'll use to find the parent node
     var firstScriptElement = document.getElementsByTagName('script')[0];

     // Create a new script element and set its id
     var facebookJS = document.createElement('script'); = 'facebook-jssdk';

     // Set the new script's source to the source of the Facebook JS SDK
     facebookJS.src = '//';

     // Insert the Facebook JS SDK into the DOM
     firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);

What links here