Tutorial: Introduction to APIs (Facebook & Google+)
Description
This tutorial will guide you through the basics of using 3rd party APIs, such as those in use by Facebook and Google. By the end of this tutorial you should have a grasp on how APIs transmit data, how you can access this data, and how you can parse this data so that it can be accessed by your application. This tutorial was completed using Eclipse, a free open source IDE.
Begin the tutorial by reading the introduction displayed here.
Tutorial Overview:
| Resources: | Download the SKELETON : Download the COMPLETE VERSION : JavaDoc : Further Reading |
| Setting up the Skeleton: | Initial Setup : Add the project to Eclipse : Add Libraries |
| Google+ API: | Overview : Understand the Exception : Step 1 : Building the API Request : Step 2 : Executing the Request |
| Facebook Graph API: | Understand the Exception : What you'll need to know |
API Output

Setting up the Skeleton
Initial Setup
First thing's first, make sure you have downloaded the Tutorial Skeleton. Once the file has been downloaded, Right Click -> Extract the ZIP file. Extract to the location of your choosing.
Add the project to Eclipse
- In Eclipse, Click the File Menu -> Select Import
- From the Import Menu, Expand the General menu
- Select Existing Projects into Workspace, then click Next
- Select the root directory by clicking Browse and then selecting the skeleton's extracted directory
- Ensure that ACM-API-Tutorial_Skeleton is checked, then click Finish
Add Needed Libraries
Note: This may not be necessary, depending on how you imported the project:
Before proceeding, check to see if
gson-1.7.1.jar appears under Referenced Libraries.
Luckily our skeleton only needs one library in order to function. This is the GSON Library, provided by Google. It allows for powerful parsing of JSON strings into usable data structures.
Library Location :
my_project_folder/libraries/gson-1.7.1Step 1 (Picture)
- Begin by locating your newly imported project in your Eclipse Package Explorer.
- Right Click on the Project (e.g. ACM-API-Tutorial-Skeleton)
- Choose Properties from the Context Menu
Step 2 (Picture)
- Click Java Build Path from the left menu
- Click Add JARS
Step 3 (Picture)
- Select
gson-1.7.1.jarfrom the menu (Project Name -> libraries ->gson-1.7.1.jar) - Click OK (returning to the Properties window)
- Click OK (from the properties window, returning to the main window)
Google+ API
Overview
Most of the Google+ API follows a RESTful API design, meaning that you use standard HTTP methods to retrieve and manipulate resources. For example, to get the profile of a user, you might send an HTTP request like:
GET https://www.googleapis.com/plus/v1/people/{userId}
Once we have sent a request to the REST API we are sent back a response. The server doesn't know what context we're sending the request from, so it needs to send a response that is capable of being understood by virtually any language.
This is where JSON comes into play. You can think of JSON as a light-weight alternative to XML.
Google sends back this type of response:
{
"kind": "plus#person",
"id": "118051310819094153327",
"displayName": "Chirag Shah",
"url": "https://plus.google.com/118051310819094153327",
"image": {
"url": "https://lh5.googleusercontent.com/-XnZDEoiF09Y/AAAAAAAAAAI/AAAAAAAAYCI/7fow4a2UTMU/photo.jpg"
}
}
We then can use various tools to decode this JSON response and parse the data into usable data structures (like Arrays, Strings, Maps, etc.). In this tutorial we will be using the GSON library, mentioned above.
Understand the Exception
A custom Java Exception has been created and provided for you:
GooglePlusAPIException (see JavaDoc).
This is used when we make a request to the Google+ API. If the Google+ API sends an error, this exception will decode the error and return it to us.
Step 1 : Building the API Request
We're in File GooglePlusAPI.java, in the get() method
The first, and most important concept, is making the connection. In my example, I have used Java's
URLConnection and URL. URL is a Java class designating a pointer to an internet resource (URL). URLConnection, on the other hand, represents a communications link between the application and the URL.
Now, we need to understand a few things:
- We know that we must request from
GET https://www.googleapis.com/plus/v1/people/{userId}. -
We know that Google's API requires an API Key (this has been preset for you at the beginning of the
GooglePlusAPIclass asAPI_KEY)
- The API Key assigned to our application in the Google API Console. This is needed so that Google can determine which application is making the request, which Google then uses to limit API usage (no more than X a day).
- An alternative to using the API Key is using OAUTH to authenticate a user. The process of authenticating a user ties the request back to our application in a similar way. Either the API_KEY or OAUTH Authentication must be present in order to execute a request.
So, given the above, we know that we have:
URLConnection gpAPI = new URL( "https://www.googleapis.com/plus/v1/people/{userId}?key=" + API_KEY ).openConnection();
Now, {userId} won't cut it in a URL. We'll get an error, because that isn't actually a User ID! Luckily we've anticipated the need for a User ID so the get() method in the skeleton has a parameter of UID. All we need to do is use this UID in our request's query string:
URLConnection gpAPI = new URL( "https://www.googleapis.com/plus/v1/people/" + UID + "?key=" + API_KEY ).openConnection();Calling the above line opens a connection to the server which effectively makes the request. As soon as we did that the server sent a response now we need to listen for it.
In order to check and see if the API sent back an error, we'll need to get the Response Code from our request. A response code is a number which cooresponds to a certain state. 200 means everything went well. 400 means "Bad Request," 404 means "File not found," "403" is unauthorized, etc. Getting the response code requires a different Java structure. For our purposes, we'll use
HttpURLConnection:
// Declare an HTTPURLConnection resource, used to get the response code (and in the error case, evaluate) HttpURLConnection gpConnection = ( ( HttpURLConnection ) gpAPI ); // ^___________________^ // Here we're casting our gpAPI variable to the HTTPURLConnection class
Potential Problem! What if the request was unsuccessful? Java requires that we catch a possible
IOException. Adding an Exception catch will satisfy this.
At this stage, our code is now displayed as such:
public GPObject_PublicUser get( String UID ){
GPObject_PublicUser result = null;
try {
// Open a connection to the URL at our URI API request string
URLConnection gpAPI = new URL( "https://www.googleapis.com/plus/v1/people/" + UID + "?key=" + API_KEY ).openConnection();
// Declare an HTTPURLConnection resource, used to get the response code (and in the error case, evaluate)
HttpURLConnection gpConnection = ( ( HttpURLConnection ) gpAPI );
}catch( Exception e ){
System.out.println( "Google+ API Fatal Error: " + e.getMessage() );
}
return result;
}
So, what does this code do? It makes a connection to Google's servers at the API link. Google detects our request, and sends back a response based on the
{userId} (UID) we specified.
But what if Google sent back an error response? Great question! Let's add some code to handle that (scroll below the code for explanation):
public GPObject_PublicUser get( String UID ){
String json = "";
GPObject_PublicUser result = null;
try {
// Open a connection to the URL at our URI API request string
URLConnection gpAPI = new URL( "https://www.googleapis.com/plus/v1/people/" + UID + "?key=" + API_KEY ).openConnection();
// Declare an HTTPURLConnection resource, used to get the response code (and in the error case, evaluate)
HttpURLConnection gpConnection = ( ( HttpURLConnection ) gpAPI );
// Determine if the request was a success (Code 200)
if( gpConnection.getResponseCode() != 200 ){
// Request was not successful, pull error message from the server
BufferedReader reader = new BufferedReader( new InputStreamReader( gpConnection.getErrorStream() ) );
String input;
while( ( input = reader.readLine() ) != null )
json += input;
reader.close();
// Generate a custom exception that parses the JSON output and displays to the user
throw new GooglePlusAPIException( json );
}
}catch( GooglePlusAPIException e ){
e.show();
}catch( Exception e ){
System.out.println( "Google+ API Fatal Error: " + e.getMessage() );
}
return result;
}
Snap! We've just added quite a bit there. Let's take it by each line: (Understand everything? Skip ahead)
String json = "";Added above the try{}catch{} block, we'll use this in both our error response handling and our success response handling.
if( gpConnection.getResponseCode() != 200 ){ ... }
This checks to see if the response code of our connection indicated an error or not.Remember: A response of 200 means everything went okay. Otherwise there's an error.
BufferedReader reader = new BufferedReader( new InputStreamReader( gpConnection.getErrorStream() ) );Woah! A lot to take in on one line. Java's Reader classes allow us to parse text into our program. This line gets the text stream from our connection, sends it to an input reader, which we then pass to a buffered reader which will later allow us to add the output to our response string one line at a time.
Still don't understand? Read more on these classes here:
BufferedReader, InputStreamReader
String input; while( ( input = reader.readLine() ) != null ) json += input; reader.close();Our
BufferedReader allows us to get our input one line at a time. We want to compile all this data into one gigantic string. So, we continue looping while there is still a next line and add the line to our json string.
throw new GooglePlusAPIException( json );After executing the above loop, we now have the complete JSON error string sent to us from Google. Send this information to the
GooglePlusAPIException.
catch( GooglePlusAPIException e ){
e.show();
}
Since we throw our GooglePlusAPIException on an error, we need to add a catch statement.
Doing good so far?!
No. Superman does good. You're doing well.
Next, we need to build in the ability to get the response text if there isn't an error. Luckily this is almost identical to the above:
// Get the response text from the server BufferedReader reader = new BufferedReader( new InputStreamReader( gpAPI.getInputStream() ) ); String input; while( ( input = reader.readLine() ) != null ) json += input; reader.close(); // Convert the JSON request to our class object Gson gson = new Gson(); return gson.fromJson( json, GPObject_PublicUser.class );There are two main differences here:
- We use
gpAPI.getInputStream()instead ofgpConnection.getErrorStream() -
Since we don't have a pre-built class to handle parsing this JSON, we need to build one ourselves.
The trick is in creating a data structure which lines up with the JSON request. In many ways this is trial and error. More on this shortly.
So, putting it all together this is our final
get() method:
public GPObject_PublicUser get( String UID ){
// Initialize our return value
String json = "";
GPObject_PublicUser result = null;
try {
// Open a connection to the URL at our URI API request string
URLConnection gpAPI = new URL( "https://www.googleapis.com/plus/v1/people/" + UID + "?key=" + API_KEY ).openConnection();
// Declare an HTTPURLConnection resource, used to get the response code (and in the error case, evaluate)
HttpURLConnection gpConnection = ( ( HttpURLConnection ) gpAPI );
// Determine if the request was a success (Code 200)
if( gpConnection.getResponseCode() != 200 ){
// Request was not successful, pull error message from the server
BufferedReader reader = new BufferedReader( new InputStreamReader( gpConnection.getErrorStream() ) );
String input;
while( ( input = reader.readLine() ) != null )
json += input;
reader.close();
// Generate a custom exception that parses the JSON output and displays to the user
throw new GooglePlusAPIException( json );
}
// Get the response text from the server
BufferedReader reader = new BufferedReader( new InputStreamReader( gpAPI.getInputStream() ) );
String input;
while( ( input = reader.readLine() ) != null )
json += input;
reader.close();
// Convert the JSON request to our class object
Gson gson = new Gson();
return gson.fromJson( json, GPObject_PublicUser.class );
}catch( GooglePlusAPIException e ){
e.show();
}catch( Exception e ){
System.out.println( "Google+ API Fatal Error: " + e.getMessage() );
}
return result;
}
Now, as we mentioned earlier, we need to create a data structure that is capable of handling the JSON string.
This is achieved by looking at the output of the API and determining what types of structures can handle it.
Below I have included the data structure capable of handling a Google+ Public User request. The explanation for how to create one of your own is involved. Click here to learn more about how to make them.
Note: In other languages this is much easier. In PHP
$GPObject_PublicUser = json_decode( $json, true ); will return an associative array matching the structure of the object below.
public class GPObject_PublicUser implements GP_PublicUser {
/*
* These are cases where the result is just a string, no special data structure is needed.
* Example: { "displayName": "Jane Smith" }
*/
private String kind;
private String id;
private String displayName;
private String tagline;
private String gender;
private String aboutMe;
private String url;
/*
* The Java variable type needs to be correct for the values JSON is returning back to us.
* We know from the JSON string that "image," for example, looks like this:
* "image": { "url": "https://server.googleusercontent.com/.../photo.jpg" }
* As such, we need to make the image variable type match that. An associative array will work nicely.
*/
private Map<String,String> image;
private Collection<Map<String,String>> urls;
private Collection<Map<String,String>> organizations;
private Collection<Map<String,String>> placesLived;
public String getKind(){ return kind; }
public String getId(){ return id; }
public String getDisplayName(){ return displayName; }
public String getTagline(){ return tagline; }
public String getGender(){ return gender; }
public String getAboutMe(){ return aboutMe; }
public String getURL(){ return url; }
public Map<String,String> getImage(){ return image; }
public Collection<Map<String,String>> getURLs(){ return urls; }
public Collection<Map<String,String>> getOrganizations(){ return organizations; }
public Collection<Map<String,String>> getPlacesLived(){ return placesLived; }
}
The final step in building the API request is adding the methods to the interface. Since the GPObject_PublicUser is nested in the GooglePlusAPI class you will need an interface in order to access the methods:
interface GP_PublicUser {
/** Identifies this resource as a person. Value: "plus#person". */
public String getKind();
/** The ID of this person. */
public String getId();
/** The name of this person, suitable for display. */
public String getDisplayName();
/** The brief description (tagline) of this person. */
public String getTagline();
/** The person's gender. Possible values are: {male|female|other}. */
public String getGender();
/** A short biography for this person. */
public String getAboutMe();
/** The URL of this person's profile. */
public String getURL();
/** The representation of the person's profile photo. */
public Map<String,String> getImage();
/** A list of URLs for this person. */
public Collection<Map<String,String>> getURLs();
/** A list of current or past organizations with which this person is associated. */
public Collection<Map<String,String>> getOrganizations();
/** A list of places where this person has lived. */
public Collection<Map<String,String>> getPlacesLived();
}
Step 2 : Executing the Request
We're in File Main.java, in the doGooglePlus() method
Most of this is straight forward. First we need to instantiate the GooglePlusAPI class:
GooglePlusAPI gpAPI = new GooglePlusAPI();Next, we make the request using any UID. In this case the DEFAULT one specified at the beginning of the class:
GP_PublicUser user = gpAPI.get( DEFAULT_GOOGLEPLUS_UID );Finially, we can use our interface to output information to the console:
// Output the data we've received from our API GET request! printHeader( "Google+ API Results" ); System.out.println( "Google Plus Full Name: " + user.getDisplayName() );Putting this all together we get:
public static void doGooglePlus(){
// Initialize the Google+ API.
GooglePlusAPI gpAPI = new GooglePlusAPI();
// Load our public user object.
// DEFAULT_GOOGLEPLUS_UID is set in the beginning of this class as a constant.
// Defaults to Shane Chism's Google+ page;
// To change, replace DEFAULT_GOOGLEPLUS_UID with a string containing a Google+ User ID number.
GP_PublicUser user = gpAPI.get( DEFAULT_GOOGLEPLUS_UID );
// Output the data we've received from our API GET request!
printHeader( "Google+ API Results" );
System.out.println( "Google Plus Full Name: " + user.getDisplayName() );
// The Google+ API only returns the full name, so to match the Facebook API let's go ahead and cut
// the string off at the first occurrence of a space (the ' ' character).
String userFirstName = user.getDisplayName().substring( 0, user.getDisplayName().indexOf(' ') );
System.out.println( "See " + userFirstName + "'s Profile Here: " + user.getURL() + "\n" );
// Print out the user's publicly listed URLs.
// (This is a good example of iterating through user data which contains multiple records)
for( Map<String,String> url : user.getURLs() )
System.out.println( "One of " + userFirstName + "'s URLs: " + url.get( "value" ) );
}
And you're done!
API Output

Facebook Graph API
Overview
The Graph API is the core of Facebook Platform, enabling you to read and write data to Facebook. It provides a simple and consistent view of the social graph, uniformly representing objects (like people, photos, events, and pages) and the connections between them (friendships, likes, and photo tags).
GET https://graph.facebook.com/{userId}
Once we have sent a request to the Graph API we are sent back a response. The server doesn't know what context we're sending the request from, so it needs to send a response that is capable of being understood by virtually any language.
This is where JSON comes into play. You can think of JSON as a light-weight alternative to XML.
Facebook sends back this type of response:
{
"id": "1106460174",
"name": "Shane Chism",
"first_name": "Shane",
"last_name": "Chism",
"link": "https://www.facebook.com/chism",
"username": "chism",
"gender": "male",
"locale": "en_US",
"type": "user"
}
Test Out Various Facebook API Methods!
Direct Link
We then can use various tools to decode this JSON response and parse the data into usable data structures (like Arrays, Strings, Maps, etc.). In this tutorial we will be using the GSON library, mentioned above.
Understand the Exception
A custom Java Exception has been created and provided for you:
GooglePlusAPIException (see JavaDoc).
This is used when we make a request to the Google+ API. If the Google+ API sends an error, this exception will decode the error and return it to us.
What you'll need to know
Now it's your turn! Constructing a request to the Facebook API is almost identical to that of the Google+ API. Have questions? Post in the comments section and I'll respond with help!
Considerations:
- The Request URL is different. We're now using
GET https://graph.facebook.com/{userId} - We no longer need an API Key
Facebook doesn't limit incoming API requests by application - Our data structure for parsing the JSON response is different
A different format for our JSON response means a different data structure to contain it
Further Reading:
- OAuth / API Authentication
- Introducing JSON
- Google+ API
- Google+ API Documentation
-
Google+ Java API Starter Project
Includes all the pre-built Google SDKs to allow for hyper-functional API calls
- Facebook Graph API
- Graph API Documentation
-
Facebook API Sandbox
Play with the different types of API requests, including trying out authentication -
Facebook API SDKs
(available for JavaScript, PHP, iOS, and Android)
Java
OCTOBER
12
2011

