Of course! Here's a comprehensive guide to using the Facebook Graph API with Java, covering the modern, official approach, the legacy approach, and important considerations.

The Modern Way: Using the Official Facebook for Java SDK
The best and most current way to interact with the Facebook API in Java is by using the official Facebook for Java SDK. It's a community-supported SDK that provides a clean, object-oriented interface to the Graph API.
Prerequisites
Before you start coding, you need to register your application with Facebook to get the necessary credentials.
- Go to the Facebook Developers Console: https://developers.facebook.com/
- Create a New App: Click "My Apps" -> "Create App". Choose "Consumer" as the app type.
- Get Your App ID and App Secret:
- Once your app is created, navigate to Settings -> Basic.
- You will find your App ID and App Secret. Keep these safe! Your App Secret should never be committed to a public Git repository or exposed in client-side code.
- Set Up OAuth Redirect URIs: In the same Basic Settings page, find the "Valid OAuth Redirect URIs" field. You need to add a URI here where Facebook will send the user after they grant permissions. For local development, a common choice is
http://localhost:8080/or a specific callback endpoint likehttp://localhost:8080/callback.
Adding the Dependency
You need to add the Facebook SDK to your project. The dependency information is available on the Maven Central Repository.
For Maven (pom.xml):

<dependency>
<groupId>com.facebook</groupId>
<artifactId>facebook-java-api</artifactId>
<version>5.15.0</version> <!-- Check for the latest version -->
</dependency>
For Gradle (build.gradle):
implementation 'com.facebook:facebook-java-api:5.15.0' // Check for the latest version
Authentication (Getting an Access Token)
Most API calls require an access token. The process of getting one involves redirecting the user to Facebook to log in and grant permissions.
Here’s a conceptual example of a web application flow (using a framework like Spring Boot or SparkJava would make this much cleaner).
Step A: Redirect the User to Facebook's Login Dialog

import com.restfb.util.StringUtils;
// In your controller or handler that initiates the login
String appId = "YOUR_APP_ID";
String redirectUri = "http://localhost:8080/callback";
String permissions = "public_profile, email"; // Request specific permissions
String facebookUrl = String.format(
"https://www.facebook.com/v18.0/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s",
appId,
redirectUri,
permissions
);
// Redirect the user's browser to this facebookUrl
// response.sendRedirect(facebookUrl);
Step B: Handle the Callback and Exchange the Code for a Token
After the user grants permission, Facebook will redirect them to your redirectUri with a code parameter.
import com.restfb.*;
import com.restfb.types.User;
// In your callback handler (e.g., /callback endpoint)
String code = request.getParameter("code"); // Get the code from the URL
String appId = "YOUR_APP_ID";
String appSecret = "YOUR_APP_SECRET";
String redirectUri = "http://localhost:8080/callback";
// Exchange the code for an access token
FacebookClient.AccessToken accessToken = FacebookClient.obtainUserAccessToken(
appId,
appSecret,
redirectUri,
code
);
String accessTokenString = accessToken.getAccessToken();
Making API Calls
Once you have an access token, you can use the FacebookClient to make Graph API requests.
import com.restfb.*;
import com.restfb.types.*;
// Use the access token to create a client
FacebookClient fbClient = new DefaultFacebookClient(accessTokenString, Version.LATEST);
// --- Example 1: Get the current user's profile ---
User user = fbClient.fetchObject("me", User.class);
System.out.println("User Name: " + user.getName());
System.out.println("User Email: " + user.getEmail());
// --- Example 2: Get the user's friends ---
Connection<User> friends = fbClient.fetchConnection("me/friends", User.class);
System.out.println("Number of friends: " + friends.getData().size());
// --- Example 3: Post on the user's feed ---
// You need the 'publish_actions' permission for this
fbClient.publish("me/feed", Post.class, Parameter.with("message", "Hello from the Facebook Java API!"));
// --- Example 4: Get a Page's information ---
Page page = fbClient.fetchObject("CNN", Page.class);
System.out.println("Page Name: " + page.getName());
System.out.println("Page Category: " + page.getCategory());
The Legacy Way: The Old Graph API SDK (Deprecated)
You might find older tutorials or projects using the original facebook4j library. This is now deprecated and not recommended for new projects.
- Maven Dependency (Deprecated):
<dependency> <groupId>org.facebook4j</groupId> <artifactId>facebook4j-core</artifactId> <version>2.4.13</version> <!-- No longer updated --> </dependency> - Why it's deprecated: Facebook has changed its API significantly over the years, and this library is no longer maintained to support those changes. The
com.facebookSDK is the modern, community-supported alternative.
Key Concepts and Best Practices
API Versions
The Facebook Graph API is versioned. You must specify a version in your requests. Using the latest version (Version.LATEST) is generally best, but you can pin to a specific version (e.g., Version.VERSION_18_0) for stability.
Permissions (Scopes)
You must request the correct permissions (called "scopes") from the user. For example:
public_profile: To get basic profile info (name, ID, picture).email: To get the user's email address.pages_read_engagement: To read engagement data on Pages you manage.publish_to_groups: To post to groups.
Always request the minimum permissions necessary. You can see a full list of permissions in the Facebook Login documentation.
Access Tokens and Security
- Never expose your App Secret in client-side JavaScript or in a public repository.
- Access tokens can expire. For long-lived access tokens, you can exchange a short-lived token for a long-lived one after the user authenticates.
- Use Client-Side Flow (the example above) for web apps where the user logs in directly. Use Server-Side Flow for server-to-server interactions or when you need to manage tokens for multiple users on your backend.
Error Handling
The SDK will throw exceptions if a request fails. You should handle these gracefully.
try {
User user = fbClient.fetchObject("me", User.class);
System.out.println(user.getName());
} catch (FacebookOAuthException e) {
System.err.println("OAuth error: " + e.getErrorMessage());
} catch (FacebookException e) {
System.err.println("Facebook API error: " + e.getMessage());
}
Complete Spring Boot Example
This is a very basic example of a Spring Boot controller that handles the login flow.
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.facebook</groupId>
<artifactId>facebook-java-api</artifactId>
<version>5.15.0</version>
</dependency>
</dependencies>
FacebookConfig.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "facebook")
public class FacebookConfig {
private String appId;
private String appSecret;
private String redirectUri;
// Getters and Setters
public String getAppId() { return appId; }
public void setAppId(String appId) { this.appId = appId; }
public String getAppSecret() { return appSecret; }
public void setAppSecret(String appSecret) { this.appSecret = appSecret; }
public String getRedirectUri() { return redirectUri; }
public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; }
}
application.properties
facebook.app-id=YOUR_APP_ID facebook.app-secret=YOUR_APP_SECRET facebook.redirect-uri=http://localhost:8080/callback
FacebookController.java
import com.restfb.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class FacebookController {
@Autowired
private FacebookConfig facebookConfig;
@GetMapping("/login")
public void login(HttpServletResponse response) throws IOException {
String permissions = "public_profile, email";
String facebookUrl = String.format(
"https://www.facebook.com/v18.0/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s",
facebookConfig.getAppId(),
facebookConfig.getRedirectUri(),
permissions
);
response.sendRedirect(facebookUrl);
}
@GetMapping("/callback")
public String callback(@RequestParam("code") String code) {
try {
FacebookClient.AccessToken accessToken = FacebookClient.obtainUserAccessToken(
facebookConfig.getAppId(),
facebookConfig.getAppSecret(),
facebookConfig.getRedirectUri(),
code
);
FacebookClient fbClient = new DefaultFacebookClient(accessToken.getAccessToken(), Version.LATEST);
User user = fbClient.fetchObject("me", User.class);
// Here you would typically save the user to your database
// and create a session for them.
return "redirect:/welcome?name=" + user.getName();
} catch (FacebookException e) {
// Handle error
return "redirect:/error?message=" + e.getMessage();
}
}
@GetMapping("/welcome")
public String welcome(@RequestParam String name) {
return "Welcome, " + name + "!";
}
}
This should give you a solid foundation for working with the Facebook API in Java. Remember to always refer to the latest Facebook Graph API documentation for the most up-to-date information on endpoints, fields, and features.
