Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

RestFB allows us to interact programmatically with Facebook services, such as retrieving user profiles, posting to pages, and handling authentication. In this tutorial, we’ll explore how to use RestFB for these and other similar interactions in a Java application.

2. Setting up the Project

Before we start using RestFB, we add the RestFB dependency to the pom.xml file:

<dependency>
    <groupId>com.restfb</groupId>
    <artifactId>restfb</artifactId>
    <version>2025.6.0</version>
</dependency>

3. Authenticating With Facebook

To authenticate with Facebook’s API, we need an access token and an app secret. These tokens are scoped to users, pages, or apps, and must carry the necessary permissions for the actions we intend to perform.

Once we have the access token, we can use it in our code to authenticate API requests. For simplicity in this article, we’ll store them in a configuration file.

Let’s create an application.properties file to store and load them at runtime:

facebook.access.token=YOUR_ACCESS_TOKEN
facebook.app.secret=YOUR_APP_SECRET

4. Initializing the Facebook Client

The core of RestFB is the FacebookClient class, which handles API requests. To integrate it with our application, we create a configuration class that initializes the client as a Spring bean:

@Configuration
public class FacebookConfig {
    @Value("${facebook.access.token}")
    private String accessToken;

    @Value("${facebook.app.secret}")
    private String appSecret;

    @Bean
    public FacebookClient facebookClient() {
        return new DefaultFacebookClient(
          accessToken, 
          appSecret, 
          Version.LATEST
        );
    }
}

The facebookClient bean is initialized with these values and the latest Graph API version. The DefaultFacebookClient handles token validation, request serialization, and response parsing, making it ready for immediate use in services.

5. Fetching a Facebook User Profile

RestFB simplifies querying Facebook’s Graph API by mapping JSON responses to Java objects. For example, we can use the fetchObject() method with a User model class to fetch a user’s profile:

@Service
public class FacebookService {
    @Autowired
    private FacebookClient facebookClient;

    public User getUserProfile() {
        return facebookClient.fetchObject(
          "me", 
          User.class, 
          Parameter.with("fields", "id,name,email")
        );
    }
}

The getUserProfile() method queries the me endpoint, which returns data for the user associated with the access token. The User.class argument tells RestFB to deserialize the response into a User object, and the fields parameter specifies which data to retrieve (e.g., id, name, and email).

This approach avoids manual JSON parsing and ensures type safety.

6. Fetching a User’s Friends List

Apart from fetching a user’s profile, we can also retrieve their friends list:

List getFriendList() {
    Connection friendsConnection = facebookClient.fetchConnection(
      "me/friends",  
       User.class  
    );
    return friendsConnection.getData();
}

In this code, we use the fetchConnection() method to retrieve a list of the user’s friends. The Connection object contains the current page of results, and we can call getData() to access the list of User objects.

7. Posting a Status Update

RestFB also allows us to post updates to a user’s timeline or a Facebook page. To post a status update, we use the publish() method. This method sends a POST request to Facebook’s Graph API and returns a response object containing metadata about the newly created post.

Below is a code snippet that demonstrates this functionality:

String postStatusUpdate(String message) {
    FacebookType response = facebookClient.publish(
      "me/feed",
      FacebookType.class,
      Parameter.with("message", message)
    );  
    return "Post ID: " + response.getId();
}

In this code, we publish a simple text message to the authenticated user’s feed. The publish() method takes the Facebook endpoint (me/feed), FacebookType as the response type, and the message parameter as input.

FacebookType is a generic RestFB class that represents the structure of Facebook’s API response. When a post is created, Facebook returns an object containing details like the post’s unique ID, creation time, and other metadata. By using FacebookType, RestFB automatically deserializes this response into a Java object.

8. Uploading Photos to Facebook

In addition to posting status updates, RestFB also supports uploading photos to a user’s timeline or Facebook Page. Uploading media requires specific permissions like publish_to_groups, pages_manage_posts, or user_photos, depending on the context.

To upload a photo, we use the BinaryAttachment class provided by RestFB along with the publish() method. Here’s a sample snippet for uploading an image from the classpath:

void uploadPhotoToFeed() {
    try (InputStream imageStream = getClass().getResourceAsStream("/static/image.jpg")) {
        FacebookType response = facebookClient.publish(
	  "me/photos",
	  FacebookType.class,
	  BinaryAttachment.with("image.jpg", imageStream),
	  Parameter.with("message", "Uploaded with RestFB")
	);
    } catch (IOException e) {
	logger.error("Failed to read image file", e);
    }
}

9. Posting to a Facebook Page

To publish content to a Facebook Page, we need an access token with the pages_manage_posts permission. This token grants our application the authority to act on behalf of the Page.

The following example demonstrates how to retrieve a Page’s access token and publish a post:

String postToPage(String pageId, String message) {
    Page page = facebookClient.fetchObject(
        pageId,
        Page.class,
        Parameter.with("fields", "access_token")
    );

    DefaultFacebookClient pageClient = new DefaultFacebookClient(
      page.getAccessToken(),
      appSecret,
      Version.LATEST
    );

    FacebookType response = pageClient.publish(
      pageId + "/feed",
      FacebookType.class,
      Parameter.with("message", message)
    );

    return "Page Post ID: " + response.getId();
}

First, we use the fetchObject() method to query the Graph API for the Page’s details, including its access token. This token is distinct from the user’s token and grants permissions specific to the Page.

Next, we create a new DefaultFacebookClient using the Page’s access token. This client is configured to perform actions on behalf of the Page, such as posting to its feed.

Then we use the publish() method to send the post to the endpoint {page-id}/feed. Similar to the user post example, FacebookType is used to deserialize the response, which includes the new post’s ID.

10. Handling Errors

Facebook API requests can fail due to invalid tokens, rate limits, or permission issues. RestFB throws exceptions that we can catch and handle gracefully:

try {
    User user = facebookClient.fetchObject("me", User.class);
} catch (FacebookOAuthException e) {
    logger.error("Authentication failed: " + e.getMessage());
} catch (FacebookResponseContentException e) {
    logger.error("API error: " + e.getMessage());
}

FacebookOAuthException indicates authentication failures (e.g., expired tokens), while FacebookResponseContentException covers general API errors.

Wrapping API calls in try–catch blocks allows us to log errors and implement retry logic if needed.

11. Conclusion

In this article, we learned how to use RestFB to build Facebook-integrated features within a Java application. We discussed essential operations such as authentication, fetching user data, posting updates, and uploading photos. With RestFB’s type-safe and intuitive API, developers can interact with Facebook’s Graph API without getting overwhelmed by low-level HTTP or JSON handling.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW