Wrangling with the Facebook Graph API

Wrangling with the Facebook Graph API

Tutorial Details
  • Topic: Facebook Graph API
  • Version: Facebook PHP SDK v.3.1.1
  • Difficulty: Intermediate
  • Estimated Completion Time: 1 Hour

Have you ever wanted to learn how to make your applications more social with Facebook? It’s much easier than you think!

In this tutorial, we’ll be building an application that reads and publishes data to and from Facebook using Facebook’s Graph API. Interested? Join me after the jump!


A Short Introduction to the Open Graph Protocol

Facebook Open Graph

Open Graph Protocol

Image courtesy of http://ogp.me

The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on Facebook to allow any web page to have the same functionality as any other object on Facebook.

While many different technologies and schemas exist and could be combined together, there isn’t a single technology which provides enough information to richly represent any web page within the social graph. The Open Graph protocol builds on these existing technologies and gives developers one thing to implement. Developer simplicity is a key goal of the Open Graph protocol which has informed many of the technical design decisions.

In a nutshell, the Open Graph Protocol turns any web page into an object in a huge graph. Each object, at least in Facebook’s graph objects, can have many other objects linked to it. For example, a Facebook Page can have multiple Post objects, which are posts made by that page. In turn, each Post object can have multiple Comment objects attached to it, referring to comments written by people on the post. This relationship between graph objects is the basis for Facebook’s Graph API, which in turn allows us to do CRUD operations on these objects.

In this tutorial, we’ll be learning how to use and integrate the Facebook Graph API into an application. We’ll also learn how to use data from the Graph API to do operations like logging in a user via their Facebook account. Ultimately, we’ll be creating a small application than allows people to create and read posts from a Facebook Page they’re managing, similar to HootSuite or TweetDeck.


Step 1: Create a Facebook Application

The first thing you should do when you’re planning to use the Facebook Graph API is to create a Facebook application. This doesn’t necessarily mean that we’ll be putting the application on Facebook (although we can); we just need a Facebook application (specifically an APP ID and APP SECRET) to access the API.

Open http://developers.facebook.com and click on the Apps link in the navigation bar.

Facebook's Developer Site

Facebook’s Developer Site

You’ll be prompted to log in (if you’re not) and allow the Developer application to access your account. Just click on Allow and you’ll be redirected to the Developer App homepage.

Allow the Developer application access

Allow the Developer application access

On the Developer App homepage, click on Create New App in the upper right corner of the page.

Developer App homepage

Developer App homepage

You’ll be greeted with a modal window asking for an App Display Name and App Namespace. Provide anything you want here, but for the purposes of this tutorial, I’ll be using Nettuts+ Page Manager and nettuts-page-manager respectively. Click on Continue.

Birth of the Nettuts+ Page Manager

Birth of the Nettuts+ Page Manager

After some obligatory captcha checking, you’ll be redirected to your newly-minted application’s page. Here you’ll see the APP ID and APP SECRET that we need. Copy and paste these values somewhere for later use.

The APP ID and APP SECRET

The APP ID and APP SECRET

When that’s done, go to the lower part of the page and click on the “Website” box, and below it should appear a form that asks for a Site URL. Since I’m just using my local machine to build the application, I’ll use http://localhost/nettuts/pagemanager. When you’re done, click on the Save Changes button below.

Nettuts+ Page Manager Settings

Nettuts+ Page Manager Settings

Step 2: Download and Set Up Facebook’s PHP SDK

Facebook's GitHub page

Facebook’s GitHub page

Our next task is to download and set up Facebook’s PHP SDK. The best location to get it would be on Facebook’s GitHub page, since this is where the latest and greatest version of the PHP SDK will be.

Downloading Facebook's PHP SDK

Downloading Facebook’s PHP SDK

Point your browser to https://github.com/facebook/php-sdk and click on the “ZIP” button. This should prompt a download for the latest version of the SDK. Save it anywhere you like.

Now, extract this into PHP’s include_path to make it accessible by any application. Alternatively, if you’re just using this for one application, extract it inside the application’s folder — just make sure to take note where, since we’ll have to include facebook.php in our code later.


Step 3: Read from Facebook via the Graph API

Let’s start creating our project and using the Facebook Graph API to read information from Facebook. For starters, create an index.php file where a user can log in via Facebook. The index.php file should contain the following code:

<!DOCTYPE html>
<html>
<head>
	<title>Nettuts+ Page Manager</title>
	<link rel="stylesheet" href="css/reset.css" type="text/css" />
	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
	<script src="js/jquery.min.js"></script>
	
	<style>
	body {
		padding-top: 40px;
	}
	#main {
		margin-top: 80px;
		text-align: center;
	}
	</style>
</head>
<body>
	<div class="topbar">
		<div class="fill">
		<div class="container">
			<a class="brand" href="/">Nettuts+ Page Manager</a>
		</div>
	</div>
	<div id="main" class="container">
		<a href="connect.php" class="btn primary large">Login via Facebook</a>
	</div>
</body>
</html>

If you’re wondering, reset.css is just your standard stylesheet reset, and bootstrap.min.css is Twitter Bootstrap. I’ve also added jQuery into the mix to make it easier to do client-side stuff. Now, if you refresh the page, it should look something like this:

Nettuts+ Page Manager First Run
Nettuts+ Page Manager First Run

Now let’s create our connect.php file, which will enable us to connect a user’s Facebook account and the pages that he or she manages. Let’s start by including the Facebook library we downloaded earlier. Instantiate it using the APP ID and APP SECRET:


//include the Facebook PHP SDK
include_once 'facebook.php';

//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
	'appId' => 'REPLACE WITH YOUR APP ID',
	'secret' => 'REPLACE WITH YOUR APP SECRET',
	'cookie' => true
));

The $facebook variable can now be used to make API calls to Facebook on behalf of the application.

  • The appID setting tells Facebook which application we’re using.
  • The secret setting “authenticates” our API calls, telling Facebook that they came from someone who owns the application. This should never be shown to the public, which is why it’s named the “Application Secret.”
  • The cookie setting tells the library to store the user’s session using cookies. Without it, we won’t be able to know whether the user is logged in via Facebook or not.

Now, we check if the current user has already allowed access to the application. If not, the application has to redirect them to Facebook’s “Allow Permissions” page.


//Get the FB UID of the currently logged in user
$user = $facebook->getUser();

//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
	//do stuff when already logged in
} else {
	//if not, let's redirect to the ALLOW page so we can get access
	//Create a login URL using the Facebook library's getLoginUrl() method
	$login_url_params = array(
		'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
		'fbconnect' =>  1,
		'redirect_uri' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
	);
	$login_url = $facebook->getLoginUrl($login_url_params);
	
	//redirect to the login URL on facebook
	header("Location: {$login_url}");
	exit();
}

Essentially, this is all that happens here:

  • The application makes a simple API call to get the user’s Facebook User ID (also known as FB UID) via the $facebook->getUser() method.
  • If the $user variable has a value, it means that the user has already allowed basic permissions for the application.
  • If not, then it means the user hasn’t allowed the application permissions yet, and the application needs to redirect to Facebook’s permissions page to get the necessary permissions.
  • It then generates a Login URL, which is where the application should redirect the user to show Facebook’s permissions page for the application. The getLoginUrl() method takes in the following parameters:

    • scope – this is a comma-delimited list of permissions the application needs
    • fbconnect – this should be 1 to tell Facebook that the application will be using Facebook to authenticate the user
    • redirect_uri – this is the page Facebook redirects to after the user has gone through the Facebook permissions page

    You can read more about the getLoginUrl() method here: https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/

  • Afterwards, the application redirects the user to the Login URL and the user sees Facebook’s permissions page.
Facebook's Permissions Page

Facebook’s Permissions Page

Facebook Permissions

Let’s take a minute to talk about Facebook permissions. Similar to when you install an application on your Android phone, Facebook permissions are various levels of access a Facebook application can do on behalf of a user. For example, if we wanted access to user’s email address, we can add the email permission to the scope setting we use to generate the login URL.

Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

It’s important that your application only asks a user for permissions that it actually needs. If you only need to authenticate a user via Facebook, you don’t even need to ask any permissions at all! Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

In the app, we use the following permissions:

  • publish_stream – allows the application to publish updates to Facebook on the user’s behalf
  • read_stream – allows the application to read from the user’s News Feed
  • offline_access – converts the access_token to one that doesn’t expire, thus letting the application make API calls anytime. Without this, the application’s access_token will expire after a few minutes, which isn’t ideal in this case
  • manage_pages – lets the application access the user’s Facebook Pages. Since the application we’re building deals with Facebook Pages, we’ll need this as well.

There are a lot more permissions Facebook requires for different things. You can read all about them in Facebook’s documentation for permissions.

Going back to the application, now that the user has allowed the permissions required by the application, we can do some API calls to Facebook! Place this inside the if-else block from the code above:

<pre>
//start the session if needed
if( session_id() ) {

} else {
	session_start();
}

//get the user's access token
$access_token = $facebook->getAccessToken();

//check permissions list
$permissions_list = $facebook->api(
	'/me/permissions',
	'GET',
	array(
		'access_token' => $access_token
	)
);
</pre>

The first thing we do is get the $access_token for the user that the application just authenticated. This is crucial, as the application will need this access token for almost everything we do. To get it, we use the getAccessToken() method. The $access_token acts as a ‘password’ for the user. It’s always unique for every user on every application, so make sure to store this when needed.

Afterwards, we can see how to make API calls to Facebook using the api() method. This method takes in the following parameters:

  • $graph_path – this is the Facebook graph path, which is essentially the “URL” to the open graph object we want to access. This can be any graph object on Facebook, like a Post (e.g. ‘/<post_id>’), a Comment (e.g. ‘/<comment_id>’), or even a User (‘/me’ is a shortcut for the current user whom the $access_token belongs to. It can also be ‘/<user_name>’ or ‘/<fb_uid>’, but the $access_token you’re using must have access to that user, or you’ll only be able to get the user’s public information).
  • $method – this is the kind of method you want to do. It’s usually GET when you’re trying to “get” information, and POST when you’re trying to “post” or update information and DELETE if you want to remove information. If you’re not sure, the Graph API documentation tells you which method to use for specific API calls.
  • $params – these are the parameters that come with your API request. Usually for GET methods you only need to supply the user’s $access_token. For POST methods though, you’ll also need to provide other parameters. For example, if you want to post a new status update, you’ll provide the status update message here.

Alternatively, we can also use the api() method to execute FQL (Facebook Query Language) queries, which lets us get data via SQL-style language. This is great for retrieving information not available in the Graph API, as well as running multiple queries in one call. For example, we can get a user’s name and other details through this FQL API call:

$fql = 'SELECT name from user where uid = ' . $fb_uid;
$ret_obj = $facebook->api(array(
   'method' => 'fql.query',
   'query' => $fql,
 ));

We won’t need this for this tutorial, but it’s good to keep this in mind when you come across something the Graph API can’t get.

Now that we have the list of permissions the user has allowed for the application, we need to check if the user gave the application all the necessary ones. Since Facebook’s permissions page allows users to revoke certain permissions, we need to make sure that all of them have been allowed to make sure the application works. If the user has revoked one of the permissions, we’ll redirect them back to the permissions page.

//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access', 'manage_pages');
foreach($permissions_needed as $perm) {
	if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
		$login_url_params = array(
			'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
			'fbconnect' =>  1,
			'display'   =>  "page",
			'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
		);
		$login_url = $facebook->getLoginUrl($login_url_params);
		header("Location: {$login_url}");
		exit();
	}
}
var_dump() of the $permissions_list variable

var_dump() of the $permissions_list variable

When that’s done, it means we’re all set and we’ll be able to run the application without any problems. Let’s start by doing another API call, this time to retrieve the list of Facebook Pages the user has administrative rights to, and saving these into a session variable. Afterwards, we’ll redirect the user to the manage.php page, where the page management code will be.

//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
	'/me/accounts',
	'GET',
	array(
		'access_token' => $access_token
	)
);

//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
$_SESSION['active'] = $accounts['data'][0];

//redirect to manage.php
header('Location: manage.php');
var_dump() of the $accounts variable

var_dump() of the $accounts variable

The /me/accounts graph path gives us a list of the pages that a user has administrative rights to. This returns an array of all of the pages, plus specific $access_tokens for each of these pages. With those $access_tokens, we’ll be able to do API calls on behalf of the Facebook Page as well!

Save these in the $_SESSION array and redirect to the manage.php page.

Let’s start working on our manage.php file. Remember that we’ve saved the user’s $accounts list into the $_SESSION array, as well as set the first account on the list as the default active page. Let’s GET that account’s news feed and display it:

//include the Facebook PHP SDK
include_once 'facebook.php';

//start the session if necessary
if( session_id() ) {

} else {
	session_start();
}

//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
	'appId' => 'APP ID',
	'secret' => 'APP SECRET',
	'cookie' => true
));

//get the news feed of the active page using the page's access token
$page_feed = $facebook->api(
	'/me/feed',
	'GET',
	array(
		'access_token' => $_SESSION['active']['access_token']
	)
);

Again, the application does the intialization of the Facebook library, and then another api() call, this time to /me/feed. Take note that instead of using the user's access token, we use the active page's access token (via $_SESSION['active']['access_token']). This tells Facebook that we want to access information as the Facebook Page and not as the user.

var_dump() of the $page_feed variable

var_dump() of the $page_feed variable

Wow, that’s a lot of information about a Facebook Post. Let’s dissect a single Facebook Post object and see what it’s made of.

The Facebook Post Object

Facebook Post Cheat Sheet

Facebook Post Cheat Sheet
  • id – this is the Post‘s ID
  • from – contains information about the user who posted the message
  • message (red) – the message component of the post
  • picture (orange) – a link to the photo attached to the post
  • name (blue) – the “title” of the Facebook post
  • link (also blue) – the link to where the name goes to when clicked
  • caption (purple) – a few words to describe the link
  • description (pink) – more than a few words to describe the link
  • icon (grey) – a link to the icon image used
  • actions – Facebook actions you can do to the post, such as Liking it or Commenting on it.
  • privacy – the privacy of the post
  • type – the type of the post. A post can be a status, link, photo or video.
  • created_time – the time when the post was created
  • updated_time – the time when the post was updated
  • comments – comments on the post

It would be wise to keep a copy of the cheat sheet above, since we’ll be using that again when we publish Post objects to Facebook.

Moving on, let’s display the news feed in a more pleasing way. Add the following HTML below the PHP code:

<!DOCTYPE html>
<html>
<head>
	<title>Nettuts+ Page Manager</title>
	<link rel="stylesheet" href="css/reset.css" type="text/css" />
	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
	<script src="js/jquery.min.js"></script>
	
	<style>
	body {
		padding-top: 40px;
		background-color: #EEEEEE;
	}
	img {
		vertical-align: middle;
	}
	#main {
		text-align: center;
	}
	
	.content {
		background-color: #FFFFFF;
		border-radius: 0 0 6px 6px;
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
		margin: 0 -20px;
		padding: 20px;
	}
	.content .span6 {
		border-left: 1px solid #EEEEEE;
		margin-left: 0;
		padding-left: 19px;
		text-align: left;
	}
	.page-header {
		background-color: #F5F5F5;
		margin: -20px -20px 20px;
		padding: 20px 20px 10px;
		text-align: left;
	}
	</style>
	
</head>
<body>
<div id="main" class="container">
	<div class="content">
		<div class="page-header">
			<h1>
				<img width="50" src="http://graph.facebook.com/<?php echo $_SESSION['active']['id']; ?>/picture" alt="<?php echo $_SESSION['active']['name']; ?>" />
				<?php echo $_SESSION['active']['name']; ?>
				<small><a href="http://facebook.com/profile.php?id=<?php echo $_SESSION['active']['id']; ?>" target="_blank">go to page</a></small>
			</h1>
		</div>
		<div class="row">
			<div class="span10">
				<ul id="feed_list">
					<?php foreach($page_feed['data'] as $post): ?>
					<?php if( ($post['type'] == 'status' || $post['type'] == 'link') && !isset($post['story'])): ?>
					<?php //do some stuff to display the post object ?>
					<?php endif; ?>
					<?php endforeach; ?>
				</ul>
			</div>
			<div class="span6">
				<h3>Post a new update</h3>
			</div>
		</div>
	</div>
</div>
</body>
</html>

We make use of a simple Graph API trick here: the Picture Graph API object. Basically, you can take the Graph path of any User or Page object (e.g. http://graph.facebook.com/293518907333589), add /picture in the end and you’ll get a 50×50 photo of that object. For example:

http://graph.facebook.com/293518907333589/picture

Becomes…



Demo Picture Graph API Object

Going back, when we refresh the manage.php page now, it should look something like this:

Add this inside the <?php foreach($page_feed['data'] as $post): ?> to display the feed from the page:

<?php if( ($post['type'] == 'status' || $post['type'] == 'link') && !isset($post['story'])): ?>
<li>
	<div class="post_photo">
		<img src="http://graph.facebook.com/<?php echo $post['from']['id']; ?>/picture" alt="<?php echo $post['from']['name']; ?>"/>
	</div>
	
	<div class="post_data">
		<p><a href="http://facebook.com/profile.php?id=<?php echo $post['from']['id']; ?>" target="_blank"><?php echo $post['from']['name']; ?></a></p>
		<p><?php echo $post['message']; ?></p>
		<?php if( $post['type'] == 'link' ): ?>
		<div>
			<div class="post_picture">
				<?php if( isset($post['picture']) ): ?>
				<a target="_blank" href="<?php echo $post['link']; ?>">
					<img src="<?php echo $post['picture']; ?>" width="90" />
				</a>
				<?php else: ?>
				&nbsp;
				<?php endif; ?>
			</div>
			<div class="post_data_again">
				<p><a target="_blank" href="<?php echo $post['link']; ?>"><?php echo $post['name']; ?></a></p>
				<p><small><?php echo $post['caption']; ?></small></p>
				<p><?php echo $post['description']; ?></small></p>
			</div>
			<div class="clearfix"></div>
		</div>
		<?php endif; ?>
	</div>
	<div class="clearfix"></div>
</li>
<?php endif; ?>

When you refresh the page again, it should look something like this:

Looks good, right? We’ll have to thank the Twitter Bootstrap CSS for that!

Now, let’s add a top navigation bar to help us switch from one page to another. Add the following HTML after the <body> tag and before the <div id="main" class="container"> tag:

<div class="topbar">
	<div class="fill">
	<div class="container">
		<a class="brand" href="/">Nettuts+ Page Manager</a>
		<ul class="nav secondary-nav">
			<li class="dropdown" data-dropdown="dropdown">
				<a class="dropdown-toggle" href="#">Switch Page</a>
				<ul class="dropdown-menu">
					<?php foreach($_SESSION['accounts'] as $page): ?>
					<li>
						<a href="switch.php?page_id=<?php echo $page['id']; ?>">
							<img width="25" src="http://graph.facebook.com/<?php echo $page['id']; ?>/picture" alt="<?php echo $page['name']; ?>" />
							<?php echo $page['name']; ?>
						</a>
					</li>
					<?php endforeach; ?>
				</ul>
			</li>
		</ul>
	</div>
	</div>
</div>

Don’t forget to load the dropdown JavaScript library from Twitter Bootstrap’s JavaScript page. You can download it here.

<script src="js/bootstrap-dropdown.js"></script>
<script>
$('.topbar').dropdown()
</script>

Lastly, let’s create the switch.php file, where we’ll set another page as the active page:

<?php
session_start();
$page_id = $_GET['page_id'];

foreach($_SESSION['accounts'] as $page) {
	if( $page['id'] == $page_id ) {
		$_SESSION['active'] = $page;
		header('Location: manage.php');
		exit();
	}
}
exit();
?>

Refresh the manage.php page again and you should see something like this:

And now, by using our dropdown switcher, we’re able to switch pages.


Step 4: Publish to Facebook via the Graph API

Now we’re ready to publish new updates to our page! First of all, let’s create the HTML form where we can set what we’ll publish. Add this below the <h3>Post a new update</h3> HTML:

<img src="post_breakdown.png" alt="Facebook Post Cheat Sheet" width="340" /><br />
<form method="POST" action="newpost.php" class="form-stacked">
	<label for="message">Message:</label>
	<input class="span5" type="text" id="message" name="message" placeholder="Message of post" />
	<label for="picture">Picture:</label>
	<input class="span5" type="text" id="picture" name="picture" placeholder="Picture of post" />
	<label for="link">Link:</label>
	<input class="span5" type="text" id="link" name="link" placeholder="Link of post" />
	<label for="name">Name:</label>
	<input class="span5" type="text" id="name" name="name" placeholder="Name of post" />
	<label for="caption">Caption:</label>
	<input class="span5" type="text" id="caption" name="caption" placeholder="Caption of post" />
	<label for="description">Description:</label>
	<input class="span5" type="text" id="description" name="description" placeholder="Description of post" />
	
	<div class="actions">
		<input type="submit" class="btn primary" value="Post" />
		<input type="reset" class="btn" value="Reset" />
	</div>
</form>

Refresh to see how it looks:



Loving Twitter Bootstrap’s default form styles

The Post cheat sheet should come in handy when we’re figuring out what to put in the fields. Now, let’s create the newpost.php file where we’ll actually use the Facebook Graph API to publish to the page’s feed.

Start by creating the file and initializing the Facebook library like we did for the other pages:

<?php
//include the Facebook PHP SDK
include_once 'facebook.php';

//start the session if necessary
if( session_id() ) {

} else {
	session_start();
}

//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
	'appId' => 'APP ID',
	'secret' => 'APP SECRET',
	'cookie' => true
));
?>

Afterwards, let’s get all of the content we received from the POST request:

//get the info from the form
$parameters = array(
	'message' => $_POST['message'],
	'picture' => $_POST['picture'],
	'link' => $_POST['link'],
	'name' => $_POST['name'],
	'caption' => $_POST['caption'],
	'description' => $_POST['description']
);

Let’s not forget to add the $access_token for the page to the parameters:

//add the access token to it
$parameters['access_token'] = $_SESSION['active']['access_token'];

Now that we have our $parameters array, let’s build and send our Graph API request!

//build and call our Graph API request
$newpost = $facebook->api(
	'/me/feed',
	'POST',
	$parameters
);

Take note of what difference the $method can make. A GET API call to /me/feed will return the news feed of that particular object, but a POST API call to /me/feed will post a new status update to the object.

To publish a new Post object to Facebook, the application needs to make a call to the /<page_id or /me>/feed graph path, and it needs to supply the following in the $parameters array:

  • access_token – the access token of the account we are publishing for
  • message – the message to publish
  • picture (optional) – a link to the photo of the post
  • name (optional) – the “title” of the post
  • link (optional) – a link to where the name will go to when clicked
  • caption (optional) – a few words to describe the link/name
  • description (optional) – more than a few words to describe the link/name

You can see that the only parameters that are required are the access_token and the message parameters. By providing only these two, we can publish a simple status message, like so:



Status Update Example

Everything else is optional. However, if you provide a name, link, caption, or decription, you have to provide all four. As for picture, if a parameter value is not provided or not accessible, the post’s picture will be blank.

Finally, let’s try publishing to Facebook using the application! Go back to the manage.php page and fill up the form, then press Post:

Afterwards, you should be redirected back to the manage.php page, but there should be a new post on the feed!



Publishing to Facebook successful!

You can also check the Facebook Page itself. You should see the new post there:



Publishing to Facebook Page

Conclusion

By now, you should already have a clear grasp on how to use the Facebook Graph API to both read and publish to Facebook. In this tutorial, we only cover the basics — there’s a whole lot more you can do using the Graph API. Stuff like real-time updates, which lets you subscribe to events that happen to your application’s users (e.g. when a user changes his/her profile photo) or the Insights Graph object, which lets you get the statistics of an application, page, or domain the user has access to.

Of course, the best resource for learning more about the Graph API is undoubtedly Facebook’s Graph API documentation, but I also suggest taking a look at FBDevWiki, which is a third-party hosted wiki for Facebook Development documentation.



FBDevWiki.com

Additionally, there’s also a special Facebook version of StackOverflow you can visit at http://facebook.stackoverflow.com. The questions here are all about Facebook and Facebook Development, so it’s well worth visiting if you need any help or have any questions on the subject.



Facebook StackOverflow

Hopefully, you’ve learned from this tutorial how easy it is to use the Facebook Graph API to make your applications more social.

Have you used the Facebook Graph API in a previous project, or are you planning to use it now? Tell me all about it in the comments below and thank you so much for reading!

Tags: api
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.redkingdesigns.com Rory

    Brilliant tutorial. Good job.

  • Okeowo Aderemi

    Now this is what i call a kickarse tutorial, i wanted to know about facebook app apparently am not always online so a tutorial on graph api is really what i need to go by. awesome

  • Tanax

    I wanted to try the FB API myself a few months ago but was struck by every option at the developer control panel when creating an App. Especially the URL thingy since I was purely doing some testing “offline” – meaning the site wasn’t public to anyone but me.

    I am curious though, what are you allowed to do for private testing like this? Can I do whatever I want?
    For instance, can I loop through my friendlist and store them? Will Facebook notice? Obviously they can’t notice that I store them but they’ll see I loop through the list so the question is, will they figure it out?

    • http://nikkobautista.com Nikko Bautista
      Author

      From what I know, Facebook logs EVERYTHING that we do on Facebook. That’s something we can’t really avoid, so we should try to accept it :D

      Anyway, based on my experience with the Facebook’s APIs in general, the only limit that’s important is the “publishing” limit, which limits an app from publishing on a user’s behalf (e.g. posting status updates, photos, videos). This is limited to around 10-25 per app, per user, per day. They increase these depending on the activity on your app (e.g. FarmVille will probably have more since they have like a gazillion users).

      With regards to GET requests like reading a friends list, there’s usually no “human” limits to these, so feel free to make as many requests as you like.

      One recommendation I can give you is that you should create two Facebook applications, one for development purposes and one for production purposes. So at least, in the worst case scenario, Facebook will only disable your development app and not your production one. It also saves you the time of changing the URLs and stuff when you deploy :)

      • Tanax

        Thank you for your reply!
        What I meant with my previous comment was that the example I showed with the friendlist is actually breaking Facebooks’ Terms of Agreement because of storing user-data and providing a feature that doesn’t exist yet(for instance, if we store our friendlist we can compare our stored friendlist with our current friendlist and see who removed us as friends).

        So in regards to that, is it possible to, for instance, store your friendlist if it’s only for developer and private purposes e.g. NOT a public application on Facebook?

        :)

  • sirfilip

    Always a pleasure to see great tut !

  • http://pinoyscreencast.net pinoyscreencast

    wow! Awesome tuts that’s really helpful on creating a simple app going to try this out :)

  • HM

    Nice and sweet! =)

  • hardik gajjar

    Awesome…….. Its all about integrating fb in a single shot.

  • Kyle Smith

    The Graph API is pretty sweet, and this tutorial does a good job of exposing developers to the basics (IOW: nice tutorial!).

    Here’s one problem that I constantly battle with after working with the Graph API for a few weeks. I’m buying drinks if you can figure it out.:

    Even if an account is COMPLETELY public (say for a business, or public university), there are graph objects that do not allow any type of anonymous access. Although there are different levels / types of access tokens (app access is one of them: https://developers.facebook.com/docs/authentication/#applogin) and even some that you can give a very long expiration period to, there simply isn’t any way (that I’ve found) to make the graph API useful for non-authenticated access.

    An example? Let’s say you’re a business and you create Facebook events for all of your company activities / outings. The company’s Facebook page is completely public, including all of the events. Perfect, now anyone can check out your Facebook page and look at events (without signing into Facebook).

    Now on your company’s website you want to pull a list of all the upcoming events in and show them calendar-style on your homepage. But wait… you can’t. You have to force every visitor to your site to authenticate with Facebook before viewing your COMPLETELY PUBLIC events because, to query for a list of events via username/ID, you need the “user_events” permission. Why?

    • http://nikkobautista.com Nikko Bautista
      Author

      I’m not really sure what Facebook’s reasoning is, but if it were me, the reason that I would restrict public access via API even if something is publicly available is that retrieving data programmatically is a lot easier to do, so most probably this is to prevent spam?

      Anyway, with regards to your example. here’s what I understand:

      - You have a FB page with public events, etc etc
      - You want to display these events on your company’s website

      If my assumption is correct, then I think what you can do is you can get the permissions of the administrator of the page, then get a non-expiring access_token for the FB page via the /me/accounts graph path. Afterwards, you can store the access token somewhere, and just use this access token repeatedly to query the Graph API for the FB page’s events. This way, you don’t have to get every user to authenticate with Facebook, you only need to do it for one person.

      Remember, the only reason you’ll need to authenticate with Facebook is when you need to do something on the user’s behalf as them (e.g. post a status message as the user, authenticate the user, check information of a user’s friend, etc). So if you need to display the events of a single Facebook Page, then you only need access to the user who administers that Facebook Page, and not everyone else.

      I hope this answers your questions :)

  • http://www.jvsoftware.com Javier Villanueva

    Awsome! I was looking for a good tutorial on this since FB documentation is so cryptic :/

  • http://www.persefer.com Ozan Dikerler

    This s the best facebook api tutorial I have ever seen. Thank you so much. I m motivated again to build something with graph api. I m starting to work immediately

    • http://nikkobautista.com Nikko Bautista
      Author

      Thanks! I’m glad the tutorial has you motivated, here’s so much you can do with all the data and information you can use from Facebook. All you need is an idea that takes advantage of this, and boom, you’re in business!

  • http://uldata.blogspot.com url

    Nice tips .Thank you for sharing..

  • Sobin

    Can I do the same for an ASP.NET website??

  • http://360signals.com Maor

    Super great tutorial! Thanks for sharing this awesome information. Sure will be very useful for me and others!

  • http://www.quentin-ravinet.fr Quentin

    Maybe one of the best Facebook Graph API tuts I’ve seen on the net.
    Many thanks for this great tut !

  • Adam

    Super excellent tut! I was playing around with and modifying somebody else’s Facebook API code recently, but I really had no idea what I was doing or how it worked. This tut explains a ton.

    One question I do have, though, is why do this:

    if(session_id()) {

    } else {
    session_start();
    }

    That seems like silliness for a handful of reasons. First of all, why not just use a single negative conditional, as that’s what you really want anyway:

    if(!session_id()) {
    session_start();
    }

    Second of all, aren’t PHP session functions designed to inherit? So basically, if a session for the current visitor does exist, calling session_start() again wouldn’t overwrite the original session_id() anyway.

    So shouldn’t it all become just this:

    session_start();

    It seems like a real novice mistake to check for a session id before starting a new one, so I’m assuming I must be missing something here. I’d be quite happy if someone could point out what I don’t understand about the conditional.

    • http://nikkobautista.com Nikko Bautista
      Author

      Hey Adam,

      I do this:

      if(session_id()) {

      } else {
      session_start();
      }

      For clarity’s sake. If it were a project I was working on, I would’ve done it your way, but since this is a tutorial, I feel like this is much easier to understand.

      Anyway, the reason why I check before starting a session, is that when you call start_session() after a session has been started, PHP throws a warning that tells you that a session has already been started. Add to this the fact that the Facebook library itself will start a session somewhere in it’s code, so it’s important to ensure that the code doesn’t get any warnings.

  • Deadlow

    Can anyone suggest a way to extend the submenu? I have over 50 pages I admin and the menu only reveals the height of the monitor and does not scroll.

    Thanks in advance!

    • http://nikkobautista.com Nikko Bautista
      Author

      Hey,

      You can actually just put in a check on the foreach-loop that renders the submenu. Once it reaches a certain number (say 10?), break it and then render a new submenu beside it.

  • http://www.oteos.com daru

    Cool, I can follow your tutorial clearly. Good quote, remind me to Spiderman :-)
    Thanks.

  • http://www.annospot.com Fayçal M

    Great just in time :D !
    I didn’t know we could provide the app link in a localhost…
    Thanks for the great tut :)

    • http://nikkobautista.com Nikko Bautista
      Author

      Yeah, this is actually something a bit recent. Before, they didn’t allow non fully-qualified domains, so the domain you placed must be a complete one (e.g. domainsname.com/net/dev/local). Now I believe they allow any domain to be used.

  • Somesh

    Interesting. One more on using twitter in c# http://www.msguy.com/2011/12/talk-to-twitter-using-cnet-and.html

  • leanne

    This tutorial seems to have everything Im looking for, however, I dont need to manage pages and want to udate the status of my main wall and not the wall of a page. I have played around witht he code but cannot get this working. Any help would be micy appreciated.

    • leanne

      Ive found out how to do this. It was very straight forward and quite obvious, so I dont mind you removing this post.

  • http://nikkobautista.com Nikko Bautista
    Author

    Hey leanne,

    Publishing to your main wall is exactly the same as publishing to your Facebook Page’s wall, except that you would use the account’s FB UID and access token.

    It’s great that you were able to figure it out. Let me know if you have any other questions!

  • http://giuice.com Giuliano Lemes

    It’s by far the best facebook tutorial I found on the net. Thx very much and PLEASE post more facebook tutorials like this one!

  • leanne

    Hello again,

    I have been using the app that I built based on this tutorial today and am wondering if it is possible to keep users connected so that they do not have to login for every new session. Id like that once they have been authenticated the first time, they are always connected and not asked to login multiple times. Possibly by storing the access token in a database and this using this to connect somehow. Is this possible? I have noticed other apps that do this, but have no idea how they do this eg. ping.fm

    Many thanks in advance :0)

  • http://nikkobautista.com Nikko Bautista
    Author

    Hey leanne,

    Since we have the ‘offline_access’ permission enabled, you can store the access token in the database. You can then probably use cookies to authenticate the user when he or she returns, and you should be able to avoid having to ask them to login.

  • Edwin Luijten

    Hello,

    I’m having a little problem here, it seems that this peace of code keeps me in a loop (Firefox has detected that the server is redirecting the request for this address in a way that will never complete.) :

    $login_url_params = array(
    ‘scope’ => ‘publish_stream,read_stream,offline_access,manage_pages’,
    ‘fbconnect’ => 1,
    ‘display’ => “page”,
    ‘next’ => ‘http://’.$_SERVER['HTTP_HOST'].’/development/pc/’
    );
    $login_url = $facebook->getLoginUrl($login_url_params);

    When i compare the url in my browser with the ‘next’ parameter i see this:
    next=http://localhost/development/pc/auth/facebook
    As you can see, it seems it is not using the next value I specified.

    sidenote:
    the link to the auth page is:
    auth/facebook (controller/action)

    I hope someone is able to help me, if more information is needed ill post it.
    Thanks in advance

    • http://www.facebook.com/aryans.vinay Vinay Aggarwal

      Hey! I was having the same problem on windows. After researching a little bit i found that the issue was with ‘Security Certificate file’. After including the “fb_ca_chain_bundle.crt” file with the php facebook sdk, i get the solution to the problem. Now it is working fine.

    • http://www.facebook.com/aryans.vinay Vinay Aggarwal

      Hey! I was having the same problem on windows. After researching a little bit i found that the issue was with ‘Security Certificate file’. After including the “fb_ca_chain_bundle.crt” file with the php facebook sdk, i get the solution to the problem.

      Now it is working fine for me.

      • Thomas

        I have the same problem. According to what you said, it doesn’t work for me. Does anyone have the same problem?

    • alex

      i am having the same problem, it produces an infinity loop

      As the .cert it’s inlcuded by base_facebook, right?? I already have it uploaded on the server.

      How did you fx it?

  • leanne

    Ive added the database functionality to the app so that the access token is stored after the user first connects with Facebook. When the user returns and tries to connect to Facebook with the access token stored in the database I get:
    Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user
    Therefore am wondering if this cannot be stored and needs to be generated.

    • http://nikkobautista.com Nikko Bautista
      Author

      Weird – usually indicating that you need offline_access in the permissions would make the access token returned be a non-terminating one.

      Try removing the application permissions on Facebook for your account (http://facebook.com/editapps.php) and then re-adding it. Make sure that you see an “Offline Access” permission in the dialog.

  • http://www.ipagetraining.com iPage

    Pretty much good tut. Had the hard time figuring this out though, sorry about that. Neophyte at this app! hehe..

  • http://www.graphs.net Graphs

    These is huge. It has tons of information. Well described one indeed.

  • Barbara Gonzalez

    Hello, this was a very useful tutorial, however after trying to implement i feel its missing a way to log out from it, any ideas on how to achieve this?
    Thanks.

    • http://nikkobautista.com Nikko Bautista
      Author

      Hey Barbara,

      There’s a “logout” call in the Facebook API that allows you to logout a user from Facebook. You can put this together with a logout.php file, which will delete the current session. Just add that to the navigation bar, and you should be able to achieve logout functionality.

      • nick

        please be brief with the logout thing … i was working asp.net when i figured that its like impossible for me to logout or delete the current session please help and i am not using javascript or smthing jus C# code

  • http://www.startutorial.com XuDing

    Thank you very much for writing this tutorial.

    It definitely opens my interest to develop some Facebook Apps.

  • Jean Carlos Novaes

    Hello, I’m Brazilian and not speak English, I’m using google translator, I apologize before hand for spelling errors. Anyway, after much searching I found your blog and this excellent tutorial, it was exactly my doubts about using facebook api graph. Well I would like to know just one thing, if I want to access the photos of the friends of a user who has my application. How would you do??

    Thanks in advance.

    Jean

    • http://nikkobautista.com Nikko Bautista
      Author

      Hi Jean,

      I hope you’ll be able to understand my reply. Basically, the photos of a user is also another object in Facebook’s graph. You should be able to access it via “/me/albums”. Remember that you’ll need the “user_photos” permission to get access to it. You can also access the photos a user is tagged in via “/me/photos” graph url.

      Please do let me know if you need anymore help!

      • Jean Carlos Novaes

        I understood what you meant, but to access the photos are not the user who is using the app, but the friends of this user

        Type this app it accesses the photos of friends the user that is using the application.

        Jean

        http://apps.facebook.com/ysozlqrpwdtcvbi/

  • http://www.vmobileelite.com VMobile

    I’ve been looking around the web for a good graph-api tutorial for my social network project to be tightly integrated with facebook .. This tut is amazing :) Good job and thanks so much :)

  • Alberto Navarro

    I agree with all, your tutorial is amazing, thanks for share your knowledge!

  • Ivan

    Hi, this is a great tutorial, but I have 2 questions:
    - How do I get Cyrillic to work correctly?
    - How can I get a dynamically generated image to show? Example:
    thumbnail.php?file=photos/600×400/[image-name].jpg&size=article_medium

  • http://abdulapopoola.wordpress.com AbdulFattah Popoola

    Super-duper tutorial, easy to follow!

  • alex

    Hi,

    First off, happy new year.

    Second i am having a problem, just with the source file and my FB keys i get an error saying:

    Fatal error: Cannot use object of type stdClass as array

    Should i alter a facebook setting for my application???

    How to fix this??

    regards

    • alex

      hmmm, i have alter base_facebook.php by adding this
      //around line 560
      $user_info = (array)$user_info;

    • alex

      oh and then my var_dump() of permissions_list variable
      gives

      object(stdClass)#3 (1) {
      ["data"]=>
      array(1) {
      [0]=>
      object(stdClass)#4 (9) {
      ["installed"]=>
      int(1)
      ["status_update"]=>
      int(1)
      ["photo_upload"]=>
      int(1)
      ["video_upload"]=>
      int(1)
      ["offline_access"]=>
      int(1)
      ["create_note"]=>
      int(1)
      ["share_item"]=>
      int(1)
      ["read_stream"]=>
      int(1)
      ["publish_stream"]=>
      int(1)
      }

  • http://www.facebook.com/pages/Indiavideo/137514242938702 Sudheesh

    Hi,

    Great tutorial!!!

    I install it on our site and it working fine, only one problem. The post we published through the app is not showing the SHARE icon, check the page http://www.facebook.com/pages/Indiavideo/137514242938702

    Is there is additional setting to make to enable the SHARE icon

    Thanks in advance.

  • http://blog.geotitles.com Praveen Gowda I V

    This is a really good tutorial, keep up the good work coming.

  • http://joe.com Joe

    Each time I try to run through this tutorial I get stuck when I attempt to login to Facebook. Rather than re-directing to the Allow Access prompt, all my browser will do is d/l a copy of the connect.php.

    Anyone know what I’m doing wrong here? Also, I couldn’t the index.php to work in the browser until I saved changed it to an html file.

    I’m sure this is an absolute BASIC question, but I don’t have much experience php.

    Thanks in advance for your help!

    • Jean Carlos Novaes

      You need to Enable CURL on your server.

      Create a file .php with this code:

      access by the browser and search for CURL SUPPORT, also to encounter is already enabled, if not, look for the file on the server and pnp.ini find this line of code.

      ;extension=php_curl.dll

      delete the “;” looks like this:

      extension=php_curl.dll

      Create a file. Php with this code:

      access by the browser and search for CURL SUPPORT, also to encounter is already enabled, if not, look for the file on the server and pnp.ini find this line of code.

      ; extension = php_curl.dll

      delete the “;” looks like this:

      extension = php_curl.dll

      save and is already enabled, restart the server and this should solve your problem, sorry do not speak English I hope you understand.

      by

      • Jean Carlos Novaes

        PS *Create a file .php with this code:

        remove bones ” * “

      • Jean Carlos Novaes

        phpinfo();

  • superb

    thx mas dude… superb

  • http://www.game-swapzone.com Damien

    Thanks for a very informative article, as always net tuts+ rocks. After spending the last 6 days trying to get my head around FB login and register integration this has realy helped. I think I have gone round in circles that much that I’m about to disappear up my own you know what.

    Could you answer a query for me please? The script I bought for my website comes with what appears (to me at least) a fairly robust user management system that carries out all the session checks and user validation that you have covered. Would I be right in thinking that to integrate FB I should only be looking to pass the variables to my current system and allow it to continue to do all the checks or am I still barking up the wrong tree.

    Any help appreciated.

    Regards

    Damien

  • Joash

    Brilliant tutorial. I spent hours looking for a solution to this, you are a hero

  • Mrsku
  • http://fuga-tech.com Sabrina

    the offline_access permission has been depreciated. When I tried out this code I got an infinite redirect loop on the connect.php page because the permissions are never correct. For now I just took off the offline_access (I’ll post if I have problems) but later I’ll sort it out better according to https://developers.facebook.com/docs/offline-access-deprecation/
    Alternatively you can enable offline_access for now (see the article)

    Great tutorial overall though!

  • Farzad

    Thanks for this great tutorial!

    I’ve followed everything step-by-step, but I get no result once click on the “Login via Facebook” button, redirects to manage.php page but it’s just a blank screen!

    I’ve even added app and secret keys to all the PHP pages where required but still no result!

    Can anyone please help me! :)

    Many thank :)

  • Mihai

    Hi,

    Thank you for this tutorial.
    I keep running into the same basic problem with the facebook login: if I’m not logged on Facebook already, I get to the facebook login page, which says An error occurred. Please try again later.
    If I am logged on Facebook, I am redirected to the connect.php page, but the message Server Error: The website encountered an error while retrieving…
    Does anyone have any suggestions on how to make this work?

    Thank you

    • Andres

      Same error here, but I always get “An error occurred. Please try again later.”, wether I’m logged in or not.

  • http://tweeplechat.com Himanshu Jaju

    Some of you might be interested in doing it using FB SDK for PHP
    i just found this : http://techeeforum.com/index.php/2011/11/connecting-to-facebook-php-sdk/

  • http://www.authorbooksdatabase.com Hans Simtanda Caspersen

    I was not granted acces to my facebook account due to too many redirects (LOOP). Please help me out!!!

  • http://www.socialcatalyst.in abhi

    i am trying to develop a application for timeline .. where when someone read an article the feed goes to his wall and friends can see it(frictionless sharing)

  • http://nil slimtugo

    I have tried. I get redirected to facebook with this error:

    An error occurred. Please try again later.

    Can anyone help
    Thanks

    • Chondo

      Did you find a solution to the infinite loop when you try to login?

      I have the exact same problem, but haven’t seen a solution that works, so if you’ve figured it out, please let me know!

      • http://www.facebook.com/valentine.mick Valentine Mick London

        Remove the ‘offline_access’ in your connect.php file