Welcome to the restfb documentation.
Here you find basic information how the restfb library is used. All the different topics are handled here, but we only give a overview over the usage of the library. If you need a more in depth view and more information have a look at the cookbook. There you’ll find a lot of receipes that cover the advanced usage of restfb.
Migration from 1.x to 2.x
Important migration information
The most important change is the migration to a new JSON parser. With RestFB 2.x we use the very fast minimal-json library. That's the reason why the
JsonObjectand the other objects found in
com.restfb.jsonhave a different API. Please have a look at their GitHub repository to get a sense of how that API looks.
Important change with Graph API 2.4
fieldsparameter to get the fields you need. According to Facebook, reducing the default fields leads to faster performance. In the Advanced Usage section you'll find a example how the fields are requested with RestFB.
Fetching Single Objects
The simplest way to fetch an object from Facebook is the
fetchObject method. To use
this method you need at least the endpoint you want to access and the result type.
The endpoint can be found in the Facebook Graph API Reference. There you can find the correct syntax for the endpoint and how the response json is defined by Facebook. The type you have to provide is a concrete mapping between the json and a java object.
Fetching Multiple Objects
If you want to fetch several objects at once and these objects are very similar, you can use the “multiple ids” request. A simple way to fetch two user objects is a call like:
As you can see, you use the
fetchObjects method and supply a list of
ids as first parameter. You get a
JsonObject as a response with the previously provided
ids as names in this
If you prefer to work with a strongly-typed object instead of a basic
JsonObject, you can define your own. For example, we fetch the user
me and the page
cocacola. You may even mix different ids. But please pay attention to the fields you request: you may only request intersecting fields, otherwise you will receive an error response.
Additionally, you may work with edges. If all
ids have the requested edge you’ll get the requested data. If one
id is missing this edge, you’ll get an error instead.
The request is equivalent to these requests:
Summary of multiple ids misusage
idswith non intersecting fields requested: Only intersecting fields are allowed.
- Edges are requested that are not part of all
- More than 50 ids requested: Only 50 ids are allowed in one request.
Multiple ids and the request limit
Although you make only one request, Facebook counts every id. If you provide e.g. 10 ids, the single request is counted as 10.
You should check your implementation: If you have many ids of the same type, a "multiple ids" request can be the better solution. On the other hand, it makes more sense to send single requests if the ids have different types.
Fetching Object Lists
Before we can get to the RestFB implementation details, we have to explain some fundamentals.
Some requests - like a post’s comments or a user’s feed - are returned as a list.
Because these lists can be very large, Facebook provides a paging mechanism. This means
you receive only a limited amount of items encapsulated in a single JSON response (a “page”).
To get access the next page, you have to call a special URL which is provided for you
as part of the page data. You can iterate over all pages by calling these urls.
The relevant field in the
paging JSON is called
Every page includes the data you requested - comments, posts, accounts and so on.
To access this data, you have to iterate over the list on the page. It is important to mention
that there is a
limit query parameter. It limits the elements on one page. Changing the
limit parameter does not change the overall number of items. You can still iterate over
all pages, but you can change the amount of requests needed for this. For example, if you’d
like to query for a maximum of 50 posts, you should use a counter and stop both loops as soon
as no new items are found or your limit is reached (source code is further below).
RestFB supports paging, but you need to fetch the endpoint with the
FacebookClient.fetchConnection() method. One page of a pageable result
set is called a Connection. Now you can iterate over the Connection and you’ll
get a lot of lists of the fetched element. The loading of the next list is
automatically done by RestFB so you don’t need to know how the URLs are built.
fields to change the configuration of the returned objects
Fetching lists of objects supports this technique to specify which
fields should be returned. To get better insight how the
fields parameter can be used,
check out the Advanced Usage section.
A common use case is to fetch all elements of a specific endpoint and work with those items. You can manage this by nested iteration. So you iterate over the connections and iterate over the list in one connection. This sounds a bit complicated, but the following source code example shows how it works.
Connection object implements the
With this interface it is possible to get an iterator object or you can simply use
foreach loop as you can see in the code example above.
We already mentioned the
limit parameter and in the following example we show how to use it
and how you can use a personal limit.
In some rare cases you may need to prevent RestFB from automatically loading further
results and exert deeper control over what the Connection object is doing. To do this, you must
not use the normal iteration process and use a different approach instead. You can
simply work with the very common iterator pattern as mentioned above. Or you can use
Connection.next() methods on a connection object.
Together with the
Connection.getData() you have complete control over the object.
We don't suggest using this, ...
... because it makes the complete process of fetching items from Facebook unnecessarily complicated and error-prone. Nevertheless, here is a short example of how to use the more complicated way to duplicate the functionality of the first code example in this section.
Insights work almost like any other connections, but the
Insight type contains a list of
JsonObject. The reason for this unusual approach is the dynamic nature of the different insights. They returned values are not all of the same structure and
not defined in the Graph API reference.
To fetch some page insights you simply have to call the endpoint of a page. But don’t forget to add the
metrics parameter if you are using Graph API 2.6 or later. An example of this looks like:
Fetching User Picture
Fetching objects with RestFB is straightforward, but there’s a special endpoint that is a bit different and can be a little confusing.
If you call the
<userid>/picture endpoint you don’t receive a JSON response object. This endpoint
redirects directly to the user picture and you get the image’s binary data.
The GET request above returns these header fields.
Now, we want to receive the image url in a JSON instead of the binary data. This can be achieved by adding a special parameter to the request URL. The query parameter is
The corresponding Java code looks like this:
With this “trick” you receive a JSON response as expected when calling the Facebook Graph endpoint.
A few words...
Before we go further, a few words about logging...
With RestFB 2.x the logging framework used is slf4j as soon as it is found in the class path. If no slf4j is found, java.util.logging is used as in RestFB 1.x.
RestFB 1.x uses
java.util.logging to log the data that's sent over the wire to and from Facebook. It's often helpful to look at the log output so you can make sure that RestFB is sending the data as you expect it to and that Facebook is returning the correct JSON.
java.util.logging is used by RestFB 2.x as fallback.
Want to use Log4j instead of java.util.logging? No problem! You can disable java.util.logging for RestFB and use SLF4J to re-route (bridge) all logging calls to Log4j. You may look at our example project which demonstrates this process</a>.
If you're curious about how this works, here's more information about SLF4J bridging.
If you're concerned about SLF4J bridging performance, check out this section of the SLF4J manual.
Thanks to Chris Pruett for the heads-up about that.
java.util.logging as its logging framework. But many applications are based on
slf4j provides a bridge to log
slf4j. The following example shows how this can be done.
RestFB tries to use
slf4j. As soon as this logging library is included in the application, RestFB will use slf4j and you can use all the loggings frameworks, that slf4j can use.
If no slf4j is found, RestFB uses
java.util.logging as fallback. Then RestFB works exactly like the older version from the 1.x branch.
RestFB can be forced to use
java.util.logging - simply set the system property
true. Then slf4j is ignored even though slf4j is on the classpath.
To make the configuration of our logging simpler for developers, we don’t use loggers that are initialized with the name of the class they are created in. Our loggers have fixed names and the therefore the logging is clustered into categories.
The HTTP logger is used to keep track of the communication between RestFB and the Facebook Graph API. In the log file you'll find the requests/responses, header information, and more.
JsonMapper is used to convert JSON to RestFB types. Because the conversion contains many interesting steps, we provide a special logger. If everything works as is should the logger is very silent, but developers may change the log level to
TRACE to get much more information about what’s going on during the mapping process. You should do this only if you run into problems and would like to track them down to a special conversion step.
The logger is used in our utilities. We have utilities for date conversion, base64 calculations, and more. Just check the
com.restfb.util package. These utilities log some information and use this special logger to not pollute the other logs with less important information.
This logger provides information about the communication between your application and RestFB.
The log messages in the
ChangeValueFactory are used to notify developers about problems with the conversion of a object that is received via a webhook. Suppose RestFB does not support a special value object - you can capture the log output to send a special String to the RestFB team. Because this is different from our normal logging, we provide a special logger and you may filter these messages and log them in a different log file.
The HTTP logger is used to keep track of the communication between RestFB and the Facebook Graph API. In the log file you'll find the requests/responses, header information and more.
JsonMapper is used to convert JSON to RestFB types. Because the conversion contains many interesting steps, we provide a special logger. If everything works as is should the logger is very silent, but the developer may change the log level to
TRACE to get much more information about what’s going on during the mapping process. You should do this only if you run into problems and would like to track them down to a special conversion step.
The logger is used in our utilities. We have utilities for date conversion, base64 calculations and more. Just check the
com.restfb.util package. These utilities log some information and use this special logger to not pollute the other logs with less important information.
This logger provides information about the communication between the application and RestFB.
The log messages in the
ChangeValueFactory are used to notify the developer about some problems with the conversion of a object that is received via a webhook. Maybe RestFB does not support this special value object and the developer can capture the log output to send a special String to the RestFB team. Because this is different from the normal logging, we provide a special logger and the developer may filter these messages and log them in a different log file.
As you can see, all loggers use the package structure with the prefix
com.restfb.. With this it is possible to change the log level of all loggers at once.
With RestFB it is very easy to search Facebook. But before we go deeper in this topic, you need to know some basic information. First, Facebook differentiates between the public search and the targeted search. With the public search, you can search for public information and get some useful insights in what’s going on at Facebook. The targeted search is another approach to filter your private information.
The public search uses a special endpoint called
search. You have to provide a
query string (
q) and a type parameter (
type). With this technique, you’ll get
back data that can be marshaled to the normal RestFB types. For example, you might search for a user with the name “Mark” and get back a
User objects. Because you receive a
List, you have to use the
Connection pattern RestFB provides.
Public search for posts is no longer supported
The supported public search types are
ad_*. Some types like
place need additional parameters so you should have a look at the Facebook Graph API Search documentation.
With “targeted search” you are able to search in a user’s home, a.k.a. news feed. You can simply call
/me/home endpoint and add the
q parameter as mentioned in
the sections above.
FQL is deprecated and removed with Graph API 2.1
With Graph API 2.1, Facebook discontinued support for FQL (Facebook Query Language). All applications using Graph 2.1 or newer need to change their request and should work with the Graph API.
Because not every kind of request can transferred to Graph API, you should have a look at the Webhooks (former Real-Time Updates).
We support Webhooks with special types and you should look at the Webhooks section in this documentation.
On August 7, 2016 Facebook discontinued support for both Graph API 2.0 and FQL.
Basic Webhooks Know-How
The Graph API has supported real time updates for a long time and with Graph API 2.2 the real time updates for
pages have been improved a lot. Since, Graph API 2.5 the real time updates (RTU) have been renamed and are now called
Webhooks replace the polling mechanism with a pushing solution. With the deprecation of the FQL API, this is the only way to get notification about changes in a news feed and other Facebook objects. These changes are very lightweight and that’s the reason why you only get some basic information. But you receive everything that is important and may fill missing information with a normal Graph API call.
Technically you have to provide an endpoint on a server that is reachable by Facebook and understands
POST requests received from Facebook. You may simply parse them with a JSON library or you can use the new
Webhook types from RestFB.
To get a much deeper insight and a better overview you should take a look at the Facebook explanation of Webhooks.
Webhook Types in RestFB
The Webhook types in RestFB are a very special construction. They are fetched differently from other types and while they appear similar on the surface, their internals are completely different. The JSON is pushed to your server and so you cannot use the normal
fetchObject method. You have simply a JSON String and you can now use a
JsonMapper to convert it to a Java object.
The result is a
Webhook entity and you only need to call something like this:
Now you can step through the
WebhookObject and fetch the necessary information. The structure is a bit cumbersome, but RestFB has to reflect the original Facebook JSON structure. In this way, we are able to react to changes much faster and are able to expand our Webhooks support as new possibilities arrive.
value-field of the
Change object is very interesting. Here we added a new solution and made use of the
@JsonMappingCompleted annotation in combination with a
Because the difference between the
WebhookObjects you receive from Facebook lies in the change value, we implemented a factory so you can work with the correct entity and don’t need to implement some logic. Because some change values contain a
postId, some a photo URL and other specific differences. These are provided by a group of classes whose names end with
Important notice regarding the new Webhook types
At the moment we only support a subset of all possible webhook JSON types. The main focus lies on the page webhooks. You should be able to use the Webhooks nevertheless, but perhaps you have to deal with the
FallBackChangeValue. It encapsulates the raw JSON that represents the change value and you may work with the JSONObject, but it lacks some convenience methods.
If this happens, you will see a log message with a hint to send us the JSON. We would really like to implement more
Value classes and with the help of our users and the RestFB community we can provide a complete solution for Webhooks.
With Graph API 2.6, Facebook introduced the Messenger API. The new API allows developers to implement chat bots. With these bots it is possible to provide a great new user experience and the user may contact his/her favorite Facebook pages directly with the messenger.
The implementation of such a bot consists of two elements.
The first element is the webhook. Webhooks are used to receive messages from a user and new JSON requests are sent from Facebook. RestFB supports these new JSON requests and you can find new objects in the webhook packages of the RestFB types. Because the entrypoint to these types is the same as with normal webhooks, you should have a look at the Webhooks section if you need to refresh your knowledge. Otherwise use the webhooks as before and have a short look at the Facebook Messenger Webhook API to understand how they are built.
The second and the more interesting part of the Messenger API is the
Send API. After receiving a text from a user, your bot should react to the request and you can now have different possibilities to respond. The different types are covered in the
following sections, but you have first to know how the Send API is used and how RestFB supports you with the Send API.
Creating a recipient
Sending a message to a user requires a unique recipient identifier. There are two types of identifiers that are supported by the
The first is the
id-identifier. You can get the recipient
id as soon as a user sends a message to your bot. Please be aware of the fact that the
recipient id is not the user id. If you try to send a message to a
user id this will not work. You are required to use the
If you received a message and took the
id from that message you can create a new
IdMessageRecipient with this simple line of code:
The second identifier type is the phone number of the user you try to contact. Facebook only sends a message to a phone number if there is a certain level of confidence the the phone number can be reached.
Creating a text message
Now we have a recipient and need something we want to send to the recipient.
The simplest message you can send to a user is the text message. To generate a text
message simply need to generate a
Message object and use the
An example looks like this:
Creating a image message
Message object can contain an attachment. A simple attachment is the
MediaAttachment and you only need to provide a URL that points to the attachment and the type of it. Available types are
The attachment is then added to the newly-created message. The
Message is created like this:
Use the button template
Facebook allows more complex objects and with these it is possible to define postbacks the user can use.
The postback is a button that is presented to the user in the messenger. On click, a specially-defined string is sent back to the bot via the webhook api so the bot knows which button was pressed.
Like the postback button, there exists a
WebButton. A click on that button directs the user to a webpage.
In this example we create both types of buttons and add them to a
Use the generic template
A more complex example is the “generic” template.
It may contain some of the so-called “bubbles” that are horizontally-aligned and the user can switch between them. Switching between bubbles is performed by clicking on a arrow at the left or at the right side of the messenger view. Devices with touch support like smartphones can switch between these bubbles by swiping them to the left or right. The arrows are only visible on mouseover, so you should not be confused if you add more than one bubble and don’t see the other bubbles at first glance.
Bubble can contain further information like subtitles and images as well as the buttons
we already saw in the earlier example.
GenericTemplate allows a developer to create great-looking messages users can
interact with in very new ways.
Use the media template
With the Messenger Platform 2.2, the new media template type was introduced. This template allows the developer to send a message with animated content like a video or an animated gif. The animation is shown directly in the message thread. Additionally, buttons are available as optional interaction elements.
An example of this template type follows:
If a button is added to the
MediaTemplateElement, the example code looks this:
MediaTemplateAttachmentElement is generated with an attachment id and a
MediaType as seen in the example above.
An alternative way to generate the
MediaTemplateElement is the
MediaTemplateUrlElement. A Facebook URL is used to generate the
MediaTemplateElement and only special URLs are allowed. The
MediaType is not needed here, because RestFB detects the type automatically according to the given URL. The allowed URL list follows:
|Media Type||Media Source||URL Format|
Sending a message
Now, we are ready to do the most important thing with our new build objects: sending them to Facebook.
We use the well known
publish method of RestFB and only need to use the right endpoint with the right access token.
To send the message you have to use two parameters, the recipient and the message.
So we are ready to go and do something like this:
Setting a welcome message
A special use case for the new messages is the welcome message. You can set a special message on a page that is sent as soon as a new user starts a conversation with your page.
This welcome message contains three parameters:
Facebook expects that
thread_state are used as they are defined in the documentation and you should not modify them. Only
call_to_actions is a parameter that you have to change to modify the welcome message. It’s a list of messages and these messages may be created as explained in the chapters above.
Now we dive into coding. We configure a welcome message and send it to Facebook.
First we have to create some
Now a message object is created and added to our convenience object
CallToAction to make the process a bit easier.
In our example we only create a simple text message, but it’s possible to create more complicated objects.
After creating all the objects we can wire everything together and send it to Facebook.
If the request was successful you can check the result JSON and it looks like:
Sometimes you need to send a large text to a recipient. Using the messenger platform this can be done in a very small amount of time. Because this is not a natural behavior for a normal user, it is possible to simulate typing so you let the user think she is talking to a human being.
RestFB supports this with a special enum called
SenderActionEnum. In the following example, you can see how the typing simulation can be started.
To stop the typing you can simply use the
SenderActionEnum.mark_seen action is very interesting. With this, you are able to show the recipient that you’ve read his/her message. This is useful to give the user a good experience and the feeling he/she is talking to a human although it is a bot.
Setting a persistent menu
As of March 2 2017, there is a new persistent menu available. The new menu can contain submenus and allows developers to prevent user interaction via text input. The user may only select items in the menu and the bot does not need to understand the entered text. It seems Facebook tries to support bots that are “dumb”, because these bots cannot react in a useful way to arbitrary text inputs. More sophisticated bots have to understand the text input and act on the input in a way that makes sense.
Back to the persistent menu: the menu can contains several kinds of items. These can be found in the
MenuItem marker interface. A new item type is the
NestedButton. This provides access to the submenu and the
NestedButton can contain a list of call-to-actions.
At the moment, the hierarchy is limited to 3 levels and 5 actions are allowed per level.
The localization feature is very important. A developer can decide, depending on the user’s language, what kind of menu a bot shows and if text input is supported or not.
The following code example is from the Facebook documentation and has been adapted to RestFB and the persistent menu structure. With this, you are able to compare the JSON with the object-oriented approach RestFB provides.
The menu is shown as soon as the user has the
en_us language selected. Then we disable the text input and show 2 buttons,
a WebButton and a NestedButton. The Nestedbutton (“My Account”) is the access point to the underlying submenu with some “account details”. Some PostbackButtons are used to let the user decide what she/he wants to do next: “Pay Bill”, “History” or “Contact Info”.
With these new objects it is possible to build great persistent menus and the locale feature allows for more advanced user interaction.
Pass/Take Thread Control
As of Graph API 2.6, Facebook supports the Handover Protocol API. This API is used to allow several applications to work on the Messenger Platform of one page. The primary message receiver can be changed via the API.
For example, you can switch between a chatbot that answers to incoming messages and a human agent who has to take over the conversation as soon as the chatbot is not able to fulfill the request or answer the question. It’s even possible to switch between dedicated chatbots.
To pass the thread control to another app, you can simply use this call:
If the primary receiver app wishes to take back the control, we have to use another request and it will look like this:
Fetch secondary receivers
The primary receiver needs a list of secondary receivers to pass the control to one of them. This list can easily be obtained by calling the Graph API. An example call looks like:
fields parameter is optional and can be omitted. In that case, only
name are provided by Facebook. If you need the applications to be prefilled with additional values, you have to add the
fields parameter like in the example above.
Facebook does not allow unlimited data to be sent via the Send API and therefore they limit the amount of some fields. RestFB does not limit the data, because they may change in the future and so you don’t have to wait for new relases to use the new limits.
Limitations while creating new messages
- Titles may have up to 45 charactes
- Subtitles may have up to 80 charactes
- Call-to-action titles may have up to 20 characters
- Call-to-action items may have up to 3 buttons
- A message may have up to 10 bubbles
Messenger Code API
To advertise your Facebook page and let your users talk to you with messenger, you can use Messenger Codes.
Messenger Codes are similar to the QR-codes widely used in different places, but the are designed as circles and after scanning one of these codes the messenger app connects to your page.
Metadata & Introspection
The Facebook Graph API provides a great feature which permits deep insight into node data. This feature is called introspection and it works similarly to the well-known reflection techniques that are part of many programming languages.
To activate introspection, you simply need to add the
metadata parameter with the value
1. How this is done can be found in the Passing Parameters section or look at the example at the bottom of this section.
RestFB supports ths feature, too. All types that extend the
FacebookType have access to the metadata and you simply need to call the
getMetadata method. The returned
Metadata contains all the
connections and the
type of the requested object.
type is very important if you don’t know what kind of node an
id represents. In this metadata field you’ll find the node and you can use this information to send a more complex and type-dependent request to Facebook. For example, if you analyze a feed and its
from fields, it is important to discriminate based on
type because the
from may contain a
User or a
Some requests need additional parameters. With Graph API 2.4 for example it is mandatory to provide the
fields parameter to get a more extensive response. RestFB provides the
Parameter class to serve this purpose.
Parameter class needs a name and a value to be sent to Facebook. The value is internally processed by a
json mapper, so you can provide a
JsonObject, a primitive java type (like
Boolean and so on), or a class that uses the
Selecting Specific Fields & Field Expansion
If you fetch a type from Facebook you get a prefilled version. With Graph API 2.4 Facebook changed the behavior and you get only a very minimalistic object. The basic idea of this approach is to save bandwidth and make the transfer much faster, but you have to tell Facebook which fields you need. The requested fields have to be provided as comma separated list.
Basically you should add the
fields parameter on every request. So you can be sure to get
the right information. The fields a type supports can be found in the Graph API Reference.
Request with fields (first level)
A simple example looks like the following snippet. A user is fetched with
Request with fields (limit)
A even more interesting feature is the
limit(x) method. If a type contains a field that
represents a list of other types, for example the comments field on a post, you can limit the transferred
objects with the
limit(). This sounds very complicated and abstract but is very easy to use.
To show the usage we have a simple example.
Request with fields (second level)
Now we go a step further and have a look at the second level of the fields. Until now we worked only with the first level, but Facebook supports more levels. In this example we use the second level. The next level is added with the curly brackets and they encapsulate the fields of the next level type. This sounds complicated too, but is easy as soon as you see a example. And here we go:
Request with fields (third to n-th level)
And the last example is the third level. Now we take the last example and request only the
id from the
from field. This is similar to the second level and so you get a idea how the different levels work and so you can work with n-levels if necessary.
Fetch Post with comments/likes total count
To fetch the likes, shares and comments count you must use the correct parameters, because Facebook does not sends you this information with a normal call. In the example at the bottom all fields (shares, comments and likes) are fetched and you see how easy it is to fetch these information with RestFB.
You need to know how the parameters work so we dive a bit in this speciality. As soon as you request one of the three candidates you get a short list and you can page through the results, but you don’t get a complete overview. As soon as you add the
summary(true) part - don’t forget the dot delimiter - you get additional fields from Facebook with interesting information. The most important information is the total count. RestFB wraps the summary in the
Likes type and e.g. the
Post type has the special methods
getCommentsCount that use the summary.
This explains why you need to add the
fields parameters to the request, otherwise the method returns the fallback value
As you can see there is a
limit(0) part added to the request. This is simply used to reduce the transferred data. Because no share, comment or like is transfered and only the summary is present. We should support Facebook and don’t request data we don’t use.
A note about the Publish and Delete examples below
In order to use these, you'll need to create a Facebook Application and then request an OAuth access token with the proper permissions, e.g.
The Facebook Graph API authorization documentation explains how to do this in detail.
If you're in a hurry, though, here's a quick example:
- Create a Facebook Application
- Facebook will redirect you to
- Facebook will respond with
A note regarding the difference between live and dev apps
Newly created Facebook apps are in development mode. These apps work similar to live apps, but some actions act a bit differently. In particular, the publishing of elements is completely different. Even public elements are not visible to other users.
So please check the state of the app if your application behaves strangely or you don't see published elements.
Publishing a Message and Event
In addition from fetching information from Facebook, it is important to be able to write new comments, posts or other kinds of data to Facebook. A popular item is a simple text. Comments, posts, private messages support this type and a developer should have the possibility to easily publish text on Facebook.
Therefore you should have a look at the next example. Here, we create a new Post on the user’s feed. The great message is “RestFB test”. In return, we get the id of the created post. RestFB provides a special type for these returned ids and it is called
It is possible to create more sophisticated items. For example, if you’d like to schedule a post, you can simply read over
the next example. In that example, the scheduling timestamp is defined and the created
Date object is used as
scheduled_publish_time. Because scheduled post may not be published before “now”, the
published parameter needs to be false.
Publishing a binary object
Publishing a photo is an example of publishing binary content. There are two ways to publish binary content to Facebook. The old and deprecated way is with an
InputStream and the new way with a
ByteArray. Although the InputStream method is deprecated, you may use it and we don’t intend to remove it in the near future.
You may use several endpoints to publish a photo and it depends on your usecase which one you have to use. It is important to use the correct access token, because some endpoints have specific permission requirements.
Note regarding publishing multiple photos at once
"There is no way to publish more then one photo in the same graph API call."(see here in the creating section)
The first example shows the
InputStream method. In addition to the binary content, a message is added in the first case and a description in the second one.
This second example shows how to use a
BinaryAttachment with a byte array. The generation of the array is not part of the example code, because it is highly dependent on the libraries used in your project and the way you receive the binary content.
Publishing a binary object with a special field name
Sometimes Facebook requires the form field name to have a special value when sending a binary object, so RestFB provides a mechanism to do this. You can simply use the
BinaryAttachment object. An example for the required field name is adding a caption file to a video. This example is shown in the following code snippet. In that special case, the filename is important too, because it needs to contain the locale of caption file.
The caption file must contain the locale it represents and must be in srt format. In the example above, we set a caption for the
en_US locale and define this as the default locale.
Publishing a tagged Photo
In the previous section focused on publishing a photo. Now we expand on this a bit and include a Tag as part of the publishing process. A
tag permits you to link a Facebook user to a photo, providing formal information about who is in the photo.
To tag a user you need two things. First, a custom
PhotoTag type, and second, you have to modify the request from the
previous section. Because the custom type is the most important and exciting thing, we start with the custom type.
Now we have the custom type and may create a new instance. This is just good old Java. Now, let’s get to the publishing part. To make it easier, we use the publish call from the previous section and simply add the new parameter. When everything is wired together it looks like this:
We use the list in this example because Facebook allows up to 40 tags per photo.
Publishing a Checkin
Publishing a checkin works like publishing a normal post to a user’s feed. You simply have to provide a
place parameter with a
place id. If you only have longitude and latitude, you have to search for places in the given area first and let the user select the correct place. Publishing via longitude/latitude is not possible since Graph API version 2.0. (see Stackoverflow question)
Publishing a Video Via Resumable Upload
Uploading a short video is the same as uploading a picture. You should take a look at the picture section to understand how it works.
A new feature Facebook added with Graph API 2.4 is resumable upload support. Large videos (up to a file size of about 2GB) should be uploaded with this new approach. The current max value can be found in the Graph API documentation, or you can simply try to start the upload and handle any filesize errors that occur.
The resumable upload is divided in 3 phases: Start, Transfer, and Finish. If you are familiar with databases and transactions, you can compare the start with starting a transaction and finish with committing it. The transfer phase is where the real action takes place.
The first phase is the Start phase. Instead of uploading the file itself, you tell Facebook you want to upload a file and how big it is. The file size you send to Facebook is in bytes. Facebook checks the size and returns an error if something is not okay, but normally you should get a Video ID, a Session ID, and the range of bytes (expressed as a start and end offset) Facebook expects you to send in the first transfer chunk.
From Facebook’s response, you’ll know what the first chunk of the file you need to upload is. Now you enter the Transfer phase. You upload a chunk of the file the same way you normally upload a binary file to Facebook - you simply have to add some additional information about the offset and session so Facebook can join the file correctly.
With each chunk transfer, Facebook will return the next byte range it’s expecting. This happens in a loop. So you upload the next part and get new offsets, and upload those bytes and so on.
At some point you’ll receive a response where start and end byte offsets are equal. This signifies that it’s time to enter the Finish phase.
After uploading all binary chunks you enter the third phase and send Facebook the request to publish the video. The
response is the frequently-used “success” JSON and you may use the
GraphResponse type to easily access
After you receive a success response, you’ll have to wait until Facebook finishes processing the video. This might take a few minutes. Once done, you’ll receive one or more notifications: an email, a Facebook message, and - if you have a working real time update subscription - a call regarding the new video.
Once you receive a notification, the video is online and ready to be played.
To delete an object on Facebook, RestFB provides a
deleteObject-method. You have to provide
the ID of the object and RestFB does the magic. As a return value you receive a boolean -
means the object had been deleted,
false otherwise. You might encounter one of the common exceptions
if something happened.
Using Batch Request API
Including Binary Attachments Using the Batch Request API
Access Token Operations
Get Login Dialog URL
Before you can build your Facebook Login Dialog URL you need to look deeper into the the scope concept. Every Access Token is bound to a scope and a scope is a set of permissions. The developer decides which permissions are needed to get the application working correctly.
RestFB supports the developer building the scope and so you should use the
ScopeBuilder. The permissions are implemented as Enums. Here’s an example how to build a scope:
With the ScopeBuilder you can now easily build the login dialog url, like this:
Extending an Access Token
Normally access tokens are only valid for a short time, but you can extend the lifetime with a simple Facebook call. RestFB provides a method to make this easy.
Getting an Application Access Token
App access tokens are used to make server to server calls on behalf of your application. With these special access tokens, you can modify your application settings as well as perform some other calls - for example, publishing Open Graph actions or debugging access tokens.
To obtain an application access token you’ll need your App ID and App Secret. This is the reason why application access tokens are only used in the server-to-server communication.
RestFB provides a mechanism for obtaining app access tokens. You simply have to make the following call:
Getting an Device Access Token
Important change with Graph API 2.6
With the Device Access Token, Facebook provides functionality to connect to devices with limited input or display capabilities.
The device access token is generated using a two-step process. First, you have to call
FacebookClient.fetchDeviceCode(see example code). You receive a user code, a code and some additional information. The user code has to be shown to the user and she has to enter it on a special Facebook page. The url of that page is part of the DeviceCode object. You should not hardcode this url, because Facebook might change it. As soon as you present this information to the user, you have to poll Facebook and try to fetch the device access token.
Fetching with Graph API 2.5 or below
Graph API 2.5 and below don’t use any access token to fetch the device access token. Only the App Id is needed and you are ready to go. First we acquire a
Now you have to start polling Facebook with the
code you received in the
DeviceCode object. Every poll request may result in a checked exception that extends the
FacebookDeviceTokenException. A table of the possible exceptions and their meanings can be found below.
The call that is used to poll the
AccessToken from Facebook looks like this. You should call it in a loop:
Fetching with Graph API 2.6 or newer
With Graph API 2.6, Facebook changed the way a device token is requested. First we need a special access token that consists of the
application id and the
client token. The client token can be found in the Application Dashboard. The new token looks like
<app_id>|<client_token>. With this access token, a new
FacebookClient is created and the client is used for the device token interactions with Facebook. Because the application id is part of the access token we don’t need to provide the application id in the method call. So we have two new methods that work with this access token and don’t use the application id as parameter.
The first part - fetching the
DeviceCode - looks like this:
Now we have to call the polling call in a loop and can receive the same exceptions as in earlier versions. One change is important: there is no
FacebookDeviceTokenDeclinedException because this information is not sent to the application. This is an important change, because you have to handle this in your application. You can run into the code expired exception or you let the user close a dialog or something and stop the polling in respect to the user action.
The polling call doesn’t need the application id, so it looks like this:
The checked device token exception
The polling method should return the AccessToken, but may throw a FacebookDeviceAccessToken exception.
You showed the
user_code to the user and he/she had not finished the authorisation. This is a rather normal case because you should poll Facebook in short intervals and the user cannot switch devices (for example) that quickly.
FacebookDeviceTokenDeclinedException - (only up to Graph API 2.5)
The user declined the authorisation and your application is not allowed to access Facebook on behalf of that user.
Everything workd fine, but the authorisation proccess took to long. Perhaps you showed the
user_token to the user and he/she did not start the authorisation. Anyway, it is not possible to finish the process and you have to start again from the beginning.
You started the polling and the polling interval is too small, so you were polling too fast. Make the interval larger and spend more time waiting between 2 polling requests. The
DeviceCode object contains the interval facebook expects. You should respect this.
Parsing Signed Requests
Parsing Deauthorization Callback request
A user may uninstall an application in his or her Facebook app settings. Because the application owner might need this information, Facebook calls a Deauthorization Callback. A developer can set the deauthorization callback url in the app settings. As soon as someone uninstalls the app, this url is called with a signed POST request.
RestFB provides support for checking these signed requests and decoding the provided information.
The following snippet explains how to use the
DeAuth type to get the user id of the user who
uninstalled the app. Additionally, you’ll get the date when the app was uninstalled.
Securing Graph API Requests
Most requests need an access token. If someone is able to steal the access token, he or she can send spam with this app.
To make this more secure, Facebook provides a special parameter called
appsecret_proof. This is a parameter that is
transferred as query parameter in a normal request and contains a hashed version of the app secret.
The additional security is only achievable if the communication to Facebook occurs via a
server controlled by the developer.
FacebookClient contains the
obtainAppSecretProof method to calculate the proof,
but a much easier way is to instantiate the
DefaultFacebookClient with the additional
appsecret_proof parameter. In that case, the
appsecret_proof is automatically added to every call.
Require proof on all API calls
appsecret_proofto be transferred. If this option is enabled, all calls without a proof result in an exception.
Running The Examples
RestFB provides a repository on Github with an example project. In this repository RestFB is used to fetch several pieces of information from Facebook, publish some information, and run a legacy example. The whole project is Maven-based and you may use this repository to start your own project using RestFB.
To run the examples you need to download the restfb-examples project as zip file or clone it from Github. Don’t forget to replace the
MY_ACCESS_TOKEN with your access token, otherwise the examples won’t run.
Supported Graph Object Types
RestFB can map JSON to any class that has fields annotated with the
You may use these builtin types if you wish, or you can subclass them to add additional fields or functionality, or just write your own if you have special requirements. The builtins come with reflective implementations of
equals(Object o) to make your life simpler. If you subclass any of the builtins and add additional fields with accessors, those fields will be automatically taken into account by the above 3 methods.
com.restfb.types package you can find many classes and some packages. The classes represent Graph API types that are used in the “normal” Graph API. The distinction between normal and other classes is really easy if you look at the packages. The Marketing API has its own package called
ads. Everything that is only used in the Marketing API can be found in this special package.
send packages are associated with each other. Everything is located in the
webhook package that is received via a Facebook webhook. Changes to the feed, changes to the user and page and of course incoming messages are received by subscribing to the Messenger Platform webhook.
send package contains all objects that are used by the Messenger Platform to send new messages to a user. The different templates (even the airplane specific ones), quick replies and so on can be found here. How they are used is explained in the Messenger Platform section of this documentation
So all Graph API types that don’t belong to the Marketing API, the Messenger Platform or the Facebook Webhooks are “normal” Graph API types and can be found in
Working with JSON
Per the architecture of RestFB, a JSON mapper is used to convert the Facebook JSON into Java objects and convert them afterwards in the RestFB types according to defined rules.
In RestFB 1.x, a modified json.org implementation is used to map the JSON to Java. In the past this was a reliable and stable way to work with JSON in Java, but nowadays there are more requirements.
So in RestFB 2.x a new mapper has been introduced. We decided to use minimal-json because it is not only an implementation that has rather small code base, but it is a fast mapper and we expect a performance boost in comparison to the old json.org implementation of RestFB 1.x. Moreover, the minimal-json code is completely covered by junit tests.
RestFB is able to recursively map JSON fields annotated with
- The convenience classes provided by RestFB in
- Your own JavaBean-compliant classes
Don’t forget to provide a public default constructor!
Lists of any of the above types
Java to JSON mapping is supported by default via
JsonMapper.toJson(Object object). You may recursively convert primitive wrapper types as specified above,
String keys, and your own Javabean types by applying the
The default behavior of
DefaultJsonMapper is to throw a
FacebookJsonMappingException if it cannot map JSON to Java correctly. However, given the frequency with which the Facebook API changes, you might want to guard yourself from “surprise” errors in production by exerting more fine-grained control over how the mapper handles mapping exceptions. You can do so like this:
A note about Java to JSON mapping with the Graph API
DefaultJsonMapper should meet the needs of the vast majority of users. If it doesn’t support a feature you need, you can easily subclass it or write your own implementation of
Getting Any Kind of Data as a JSON Object
Sometimes you can’t know field names at compile time
JsonObject is the lowest-level object type. You have full control over the
object, but you don’t have convenient type mapping support available. For example, date fields
Strings and you have to map them manually to a
Date object. The version
independence regarding the Graph API is gone, too. You should only work
JsonObject if you know what you are doing.
Fetching a single object is almost the same as with a standard RestFB type. You simply
choose the JsonObject as returned type and you are ready to go. Afterwards you can
The JsonObject API depends on the used RestFB version
In RestFB 1.x we use the reference implementation that is
provided by json.org. Our
API is therefore the same as in that library.
With RestFB 2.x the internally-used
JsonObject implementation changed and is based on the
minimal-json library. In our benchmarks, this implementation
is much faster. When migrating from RestFB 1.x to 2.x, you must modify your code to support this API
change if you are using the low-level
JsonObject in your project.
If you’d like to use a
JsonObject in a Connection, there are two ways you can go.
The first was is to simply use the
JsonObject as the returned type and work
fetchConnection as described in the Fetching Object List section.
The second way is even more low-level and you work only with the JSON returned by Facebook. You should have a good knowledge of the returned JSON to access the fields. In the below example you can see how to accomplish this:
Using the low-level
JsonObject is sometimes OK, but perhaps you’d like to map the object
or special fields to RestFB types. You can manually invoke the built-in
JsonMapper to do this.
These are the
FacebookException subclasses that you may catch:
Thrown when an error occurs when attempting to map Facebook API response JSON to a Java object. It usually indicates that you’ve used the
BigDecimalor a JSON object to a Java
You generally should not explicitly catch this exception in your code, as it usually signifies programmer error in setting up
Thrown when a failure occurs at the network level. This can happen if your machine doesn't have a network connection or the Facebook API endpoint returns an unexpected HTTP status code. If there's an HTTP status code available, it's included in the exception so you may take custom actions depending on what type of error occurred.
Thrown when the Graph API returns an error, as shown in the example JSON snippet below. Exposes the
messageso you can handle them in your code and take custom action as needed.
FacebookGraphExceptionis a catchall Graph API exception. For your convenience, RestFB will throw more-specific subclasses
FacebookQueryParseExceptionif it detects either of these Graph API error types. These are described below.
Thrown when the Graph API returns an OAuth-related error (type
OAuthAccessTokenException), as shown in the example JSON snippet below.
Thrown when the Graph API returns an FQL query parsing error (type
QueryParseException), as shown in the example JSON snippet below.
This is thrown by RestFB when an FQL call fails.
FacebookGraphExceptionand its subclasses are not applicable in that case because Facebook returns this “legacy” exception instead due to FQL not yet being a full-fledged member of the Graph API.
FacebookResponseStatusExceptionwill include both the error code and error message returned by the Facebook API so you may take custom actions depending on the type of error that occurred.
This is thrown by RestFB when Facebook responds with unexpected data. For example, when extending an access token, Facebook should return an HTTP response body of the form
access_token=123&expires=456. But if Facebook does not respond as expected - perhaps they modify the response format in some future API release -
FacebookResponseContentExceptionwill be thrown.
It is unlikely that you will ever see this exception.
Here’s some example code to illustrate the above. Keep in mind that your code doesn’t need to handle every single exception the way we’re doing here - this is just to demonstrate what’s possible.
Here’s some example code to illustrate the above. Keep in mind that your code doesn’t need to handle every single exception the way we’re doing here - this is just to demonstrate what’s possible.
To prevent abuse of the Graph API, Facebook uses a rate limiting mechanism.
The number of calls you are allowed to make depends on the kind of request. There
are 3 types of limits:
user limit and
The app limit is connected to the app. As soon as you run into this limit you are in mayor trouble, because no more calls are allowed using this Facebook app. This is a limit that affects all your users and all pages.
The user limit comes into play if you use a user access token. This limit can be reached as soon as a user fires too many requests to Facebook. If you run into this limit, the app can be used by other users and the app limit is not triggered. The user has to wait before new requests can be sent.
The page limit is a bit different and more complicated. This limit is reached if a page access token is used to send too many requests to Facebook. But the page limit is directly connected to the page and not to the application. If any application that manages a page triggers the limit, all applications that use a page access token for this page are in trouble. In the past, Facebook has permitted the app owner to send an increase request to enlarge the limit for the page. Now they are using an opaque algorithm to detect a suitable limit.
RestFB supports the limits and you can fetch the limit information from the
DebugHeaderInfo with rate limiting and some additional debug information Facebook provides per call and
developers can handle this information and act in accordance with the given limits.
In general, the rate limits are not provided until you reach an 80% threshold. As soon as you are above this limit the
request contains the rate limit and you can reduce your calls.
DebugHeaderInfo can be fetched after every client call like this:
The example above shows only a short sample and you can get more information. Very important for opening new bug reports on Facebook is the trace id. A complete explanation of the returned header fields can be found here.
Extensibility and Unit Testing
These dependencies are designed to allow for straightforward subclassing (if you only want to replace a little bit of functionality) and simple custom implementations (if you require full control).
This comes in handy when unit testing - for example, you can write your own
WebRequestor implementation that simulates a Facebook API endpoint response. You can drop in custom data designed to exercise your application’s Facebook integration or simulate error conditions to make sure you’re handling them properly.
Here’s a trivial example which shows one way you might implement this:
SimpleDateFormat instance is incredibly expensive and you should not generate a new formatter for every date string you have to parse. Therefore RestFB provides the possibility to replace the old and slow parsing with a faster solution. But you have to take care of some cleanup because the higher speed can result in a small memory leak. Of course RestFB provides everything you need to do it right.
With version 1.7.0 you can decide which
DateFormatStrategy you use. The default strategy is the
SimpleDateFormatStrategy. It’s almost the same behavior as in the versions before 1.7.0 and you don’t need to change anything.
The faster stretegy is called
CachedDateFormatStrategy. You have to set this manually in the
DateUtils singleton and call the
clearThreadLocal method at the end of a thread to prevent the memory leak mentioned above. You should have a look at the code example below.
Because we provide the
DateFormatStrategy as an interface you can implement your own strategy.
You can improve your connection’s performance by using the
ETagWebRequestor. This WebRequestor is a special implementation wich adds ETag support to the restfb’s requests. For further information about
ETag you should have a look at the wikipedia page.
EtagWebRequestor the response body of every single request is stored in a cache. If you send the same request again to the Graph API, a hash key is added to the request header. Facebook will check the hash key and if the new response is the same as the stored one, Facebook returns an HTTP 304 and RestFB uses the cached response body. If an HTTP 200 is received instead, the old cached response body is replaced with the newly received response.
Requestor you can cut down on a lot of network traffic and it is very easy to use. This snippet shows how the
EtagWebRequestor is created and used in RestFB.
Disable Caching while using EtagWebRequestor
Sometimes it is useful to switch to the non-caching version. The
EtagWebRequestor provides the
setUseCache methods. With these methods you can ask the Requestor if caching is enabled and switch it to your needs.
- Because every call is stored in the cache, this may lead to a performance degredation if the cache size increases significantly.
- The cache uses a
SoftHashMapto store the response bodies. If you drive your system to the memory limit, the JVM will remove elements from the cache to allow the system to work normally. If this happens at a really bad time, RestFB may run into problems and you will have to re-try your request.
Visit RestFB’s home on Github.
Have a question not covered here? Ask in the RestFB Google Group.
Found a bug or have an enhancement request? Create a ticket in the issue tracker.
Download a read-only copy of the current source code using Git: