Sharedevto
Search

Facebook API

FACEBOOK GRAPH API

The Graph API is the primary way to retrieve and input data into Facebook's social graph. It's a low-level HTTP-based API that you can use to query data, post statuses, upload photos, and perform a variety of other actions that applications need. Facebook's Open Graph lets you define new objects and actions within the social network of users using your app, as well as create new instances of those actions and objects through the Graph API.

The Graph API is also the underlying method used by Facebook’s SDKs for iOS, Android, PHP, and JavaScript. It's utilized by many third-party toolkits across various languages. Many developers prefer using high-level toolkits because they abstract common actions, but to read and write data on the graph, using the Graph API is essential.

The social graph itself is a graph in the terms of computer science. It isn't just a data table; it's a series of nodes linked with other nodes. You can not only query nodes in the graph, but you can also query the connections between nodes. Understanding when you need a node versus when you need to create a relationship between nodes is crucial. These connections enable you to create posts on people's timelines, tag locations in posts, and interact with photos.

It's also important to be aware that another Facebook API offers a method to access the social graph. FQL (Facebook Query Language) features quite similar functionality to the Graph API, providing a set of APIs that resemble an SQL-like interface. To use FQL, you need to understand the basics of the Graph API, as FQL endpoints adhere to the Graph API. Thus, it's advisable to learn how to use the Graph API even if you prefer using FQL.

WHY LEARN ABOUT THE GRAPH API

Facebook offers three core advantages for app developers:

  1. Broad Distribution: Facebook provides an excellent distribution method for app creators. If your app is a game, it can post high scores or game results on Facebook. Your app might also publish recent runs from users or create posts about locations. These posts appear on your friends' news feeds, who might be inclined to try out your application. The Open Graph is a great way for people to discover your app.

  2. Enhanced Social Connectivity: Facebook's social graph makes it easier to build more engaging applications because you can integrate social context into your app. Having friends involved adds fun to the experience.

  3. Simplified User Access: Using Facebook Login reduces barriers for users logging into your app, offering an identity token usable across devices.

USING GRAPH API

Fundamentals

The Graph API is named after the concept of a “social graph.” Information in Facebook consists of:

  • Nodes: these are the basic elements like User, Photo, Page, Comment.
  • Edges: the connections between those basic elements, for example, Photos of a Page or Comments on a Photo.
  • Fields: information about nodes such as the User's birthday, the name of a Page.

The Graph API is based on HTTP, so it works with programming languages that have HTTP libraries like cURL or URL lib. You can even use the Graph API directly from your browser. For instance, the following request: http://graph.facebook.com/facebook/picture?redirect=false can be expressed as

GET graph.facebook.com
/facebook/picture?
redirect=false

Most Graph API requests require an access token, which your application can generate using Facebook Login.

How is the Graph API Structured?

In general, you can read APIs by making HTTP GET requests to nodes or edges of those nodes.

Most requests need to go through the API at graph.facebook.com, except for video uploads which use graph-video.facebook.com.

Object IDs

Every node has a unique ID used to access it through the Graph API. The format of node or object IDs can change over time and across applications, so we won't focus on that here.

Here's how you use an ID to create a request to a node:

GET graph.facebook.com
/{node-id}

Or to an edge:

GET graph.facebook.com
/{node-id}/{edge-name}

You can send data to the API by making HTTP POST requests to a node:

POST graph.facebook.com
/{node-id}

Or to an edge:

POST graph.facebook.com
/{node-id}/{edge-name}

Deleting through the API is carried out using HTTP DELETE requests, and updates are made via POST requests to similar addresses.

API Versions

The Graph API features multiple versions available for access at any time. Each version comprises a set of core fields and edge operations. These core APIs will be guaranteed to remain usable and unchanged for two years after their release. The platform changelog https://developers.facebook.com/docs/apps/changelog can inform you about available versions.

Elements outside of these core APIs are called extended APIs. These APIs can still be accessed through versioned routes but are subject to change or removal at any time, depending on the 90-day data migration process mentioned on the platform roadmap. However, they may be included in the next version of the API.

This is how to call a specific version of the Graph API:

The call is straightforward; just prefix the request with the version identifier. For example, here, we are calling v1.0:

GET /v1.0/me HTTP/1.1
Host: graph.facebook.com

This method can be applied to all versions. Here's the general format:

GET graph.facebook.com
/v{n}/{request-path}

Where n represents the version you wish to call. The Facebook changelog provides a complete list of existing API versions. The reference for Facebook's Graph API gives information for each version, so you should check to confirm you're using the correct version, as each has different edges and nodes.

Using the Graph API Explorer

The easiest way to understand the Graph API is to use the Graph API Explorer, a lightweight tool that allows you to query, add, and delete data. This is a very handy resource you should consult while building your application.

  1. Go to the page: https://developers.facebook.com/tools/explorer.

  2. Create a basic Access Token:

    When developing your app, you'll need to explore access tokens and how to generate one when using Facebook Login. However, you can quickly retrieve an access token using the Graph API Explorer.

    Click the “Get Access Token” button at the top right of the Explorer.

    In the subsequent dialog, don’t check any boxes, just click the green Get Access Token button. You’ll see the Login Dialog; press OK to continue.

  3. Create your first Graph API request:

    Now that you're ready to create your first request, we’ll start with a "read" request. In the text field below the dropdown for GET (let's call this the path field), delete the existing text and type me.

    Now, click the Submit button. It will take a few seconds to execute, but you should see all the information displayed in the return section below. What appears here will depend on the privacy settings of your profile, but it will at least include these basic fields:

{
“id”: “140001874101178“,
“first_name”: “Huong”,
“gender”: “female”,
“last_name”: “Le Thu”,
“link”: “http://www.facebook.com/100001874101178“,
“locale”: “en_US”,
“name”: “Le Thu Huong”,
“timezone”: 7,
“updated_time”: “2014-08-18T14:18:11+0000″,
“verified”: true
}

What you just did corresponds to the following read request for the Graph API:

GET graph.facebook.com
/me

The /me endpoint is special and resolves to the ID of the user associated with the access token in use.

  1. Gain permissions:

    Next, we’ll try to send something to Facebook using the Graph API. First, click the Get Access Token button again, this time selecting the publish_actions permission from the Extended Permissions tab.

    Now click the green Get Access Token button, and you will see the Login Dialog once more. Here you will be asked for permission for the Graph API Explorer to post on your behalf. If you want to restrict visibility of these posts to only yourself, select Only Me, then agree in this dialog before proceeding.

  2. Send a post:

    Now, you’ll click the dropdown labeled GET and change it to POST. In the path field, type me/feed and then click Add a Field.

    In the new field that appears, set the name to message and the value to Hello, World. Click the Submit button, and after a few seconds, the response will appear as follows:

{
“id: “{new-post-id}”
}

This means you’ve successfully sent your first post through the Graph API! You can check your Facebook account to see the post live.

What you’ve done here corresponds to sending the following Graph API request:

POST graph.facebook.com
/me/feed?
message=”Hello, World.”&
access_token={your-access-token}

Using the Graph API

  1. Reading Data:

    All nodes and edges in the Graph API can be read by making an HTTP GET request to the appropriate endpoint. For instance, if you want to retrieve information about the current user, you would create a request like this:

GET /me HTTP/1.1
Host: graph.facebook.com

Most APIs require an access token. You can determine which permissions are needed for your access token by checking the Graph API reference documentation. You can also use the Graph API Explorer to quickly create access tokens to understand how the API functions.

The response you receive will depend on the node and edge you're reading, but it will broadly look like this:

{
“fieldname”: {field-value},
…..
}
  1. Selecting Fields:

    By default, not all fields of a node are returned when you make a query. You can select the fields (or edges) you need to return using the field parameter in your query. This is useful because it makes the API quicker and more efficient.

    For example, the following query will only return the id, name, and profile picture of Ben:

GET graph.facebook.com
/bgolub?
field=id,name,picture
  1. Getting by URL:

    Most objects can be fetched using their IDs, but there are cases where you may not have an ID and only possess a URL for identification.

    You can use the URL node introduced in version 2.1 to obtain the ID of an Open Graph Object URL or to find data associated with an App URL.

  2. Modifying API Requests:

    Some API endpoints can be used with additional parameters to modify requests. Below is a list of common modifiers that can be utilized across most endpoints:

    Name Description Data Type
    return_ssl_resources Use this when you need an image returned through a secure link (HTTPS) to avoid browser warnings. bool
    locale Use this when your app needs content in a specific language. locale
    date_format In the Graph API, the date type returns an ISO-8601 string, but this modifier can convert it to a date. PHP, date(), string

    Additional modifiers are available for pagination and self-testing.

  3. Creating Nested Requests:

    The Graph API's extended field feature allows you to bundle multiple queries into a single request efficiently.

    For instance, you could fetch the first N photos from the first K albums in one call. The returned response maintains the data structure, so developers won’t need to stitch data back together on the client side.

    Batch Request is another feature allowing you to make multiple unrelated queries in a single request.

    Here’s the general format of a request with extended fields:

GET graph.facebook.com
/{node-id}?
fields=<first-level>{<second-level>}

<first-level> could be one or more fields or edges from the parent node (separated by commas). <second-level> could also be one or more fields or edges from first-level nodes (again separated by commas).

There is no limit to the number of nesting levels here. You can use a .limit(n) parameter on each field or edge to restrict how many objects you wish to retrieve.

It becomes clearer when you see an example of a query fetching at most 5 albums created by someone, along with the last 5 posts on that person's feed.

GET graph.facebook.com
/me?
fields=albums.limit(5), posts.limit(5)

We can further expand this query for each album object, also retrieving the first two photos and the people tagged in those photos:

GET graph.facebook.com
/me?
fields=albums.limit(5){name, photos.limit(2)}, posts.limit(5)

Now we can expand it another layer by also retrieving the names of each photo, the URL, and the tagged individuals.

GET graph.facebook.com
/me?
fields=albums.limit(5){name, photos.limit(2){name, picture, tags.limit(2)}}, posts.limit(5)

This illustrates how the extended fields handle nodes, edges, and fields to return truly complex data in a single request.

  1. Paginated Results:

    When making an API request to a node or edge, you usually won't retrieve all results in just one response. This is because responses can include thousands of objects, and they are, by default, paginated.

  2. Cursor-Based Pagination:

    Cursor-based pagination is the most efficient method and should always be utilized when possible. A cursor is a randomly generated string that points to a specific item or list of data. Unless the item is deleted, the cursor will always point to that part of the list but becomes useless if the item is removed. Therefore, your application shouldn't store old cursors.

    When reading an edge that supports cursor pagination, you'll receive a JSON response like:

{
“data”: [
... Endpoint data is here
],
“paging”: {
“cursors”: {
“after”: “MTAxNTExOTQ1MjAwNzI5NDE=”,
“before”: “NDMyNzQyODI3OTQw”
},
“previous”: “https://graph.facebook.com/me/albums?limit=25&before=NDMyNzQyODI3OTQw”,
“next”: “https://graph.facebook.com/me/albums?limit=25&after=MTAxNTExOTQ1MjAwNzI5NDE=”
}
}

An edge with cursor pagination supports the following parameters:

  • before: This cursor points to the beginning of the returned data page.
  • after: This cursor points to the end of the returned data page.
  • limit: This sets the maximum number of individual objects returned per page. Note that this is an upper limit; if there aren't enough objects left in the data, fewer objects than that limit will be returned.
  • next: Points to the next data page. If this parameter isn't present, the current page is the last one.
  • previous: Points to the previous data page. If this parameter isn't present, the current page is the first one.

Note: Cursors shouldn't be stored for long periods. They're meant for short-term pagination.

There are also two other pagination types: time-based pagination and offset pagination.

  1. Making Multiple Requests:

    The default version of the Graph API is designed for ease in retrieving data for a single object and for searching relationships between objects. It also accommodates (within limits) retrieving data for multiple objects at once.

    If your application needs access to a large amount of data in one call, or if you need to modify several objects simultaneously, creating a batch request will be more efficient than making multiple individual HTTP requests.

    To enable this, the Graph API supports several functions, including viewing multiple IDs and grouping requests.

  2. Publishing:

    Most nodes in the Graph API have edges that can accept posts (like /{user-id}/feed or /{album-id}/photos). All publishes via the Graph API can be completed with an HTTP POST request to the appropriate edge with the necessary parameters included. For example, if you want to post on someone's wall, you would create an HTTP POST request like this:

POST graph.facebook.com
/{user-id}/feed?
message={message}&
access_token={access-token}

All publishing requests require an accompanying access token. There are numerous edges you can post to.

You can publish multiple posts simultaneously with a Batch Request.

  1. Updating:

All Graph API updates are completed with an HTTP POST request to the appropriate node with the necessary parameters:

POST graph.facebook.com
/{node-id}?
{update-field}={new-value}&
access_token={access-token}

All update requests must include an access token with the necessary permissions to publish to that endpoint.

  1. Deleting:

You can remove nodes from the graph using an HTTP DELETE request:

DELETE graph.facebook.com
/{node-id}?
access_token=

Generally speaking, only content created by an application can be deleted by that application.

For clients unable to implement all HTTP methods, you can send a POST request to the endpoint with an additional field of method=delete to override the HTTP method. For example, you could delete a comment using the following request:

POST graph.facebook.com
/{comment-id}?
method=delete
  1. Searching:

You can search for various public objects in the social graph with the /search endpoint. Its structure is as follows:

GET graph.facebook.com
/search?
q={your-query}&
[type={object-type}](#searchtypes)

All search queries must include an access token. The token type will depend on your search type.

  • Searching for Pages and Place objects requires an app access token.
  • All other endpoints require a user access token.
  1. Error Handling:

Requests sent to the Graph API may return various error response types, and there are a few straightforward recovery strategies.

  1. Receive Error Codes:

Here’s a common structure for an unsuccessful API request error:

{
“error”: {
“message”: “Message describing the error”,
“type”: “OAuthException”,
“code”: 190,
“error_subcode”: 460,
“error_user_title”: “A title”,
“error_user_msg”: “A message”
}
}
  • message: Explanation of the error.
  • code: Error code.
  • error_subcode: Provides further clarification on the error.
  • error_user_msg: When encountered, you should directly relay this error to the user. It will be accurately translated for each language accompanying the API request.
  • error_user_title: If displaying an error dialog, this will be the title of that dialog. It will also be accurately translated according to the language accompanying the API request.

Overview of Facebook Query Language (FQL)

Facebook Query Language, or FQL, allows you to use an SQL-like interface to query data in the Graph API. It offers advanced features not available in the Graph API.

Example:

Running the query: SELECT uid2 FROM friend WHERE uid1=me()

Will correspond to

GET /fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=me()&access_token=…

  1. Reading Data:

    You can create an HTTP GET request to /fql?q=query where the query is either a single FQL query or a JSON encoded dictionary of queries.

  2. Query Structure:

    Queries will take the format SELECT [fields] FROM [table] WHERE [conditions]. Unlike SQL, the FROM clause in FQL can only contain one table. You can use the IN keyword in SELECT or WHERE to call subqueries, but subqueries cannot refer to variables outside their parent query limits.

    FQL can perform basic operations, simple logic like AND or NOT, and utilize ORDER BY and LIMIT. ORDER BY can only include a single table.

    For queries involving uid, you can use me() to return the logged-in user's data.

    Example: SELECT name FROM user WHERE uid = me()

    Other supported functions include: now(), strlen(), substr(), and strpos().

    Here is an example of a subquery to gather all information about the logged-in user and their friends.

SELECT uid, name, pic_square FROM user WHERE uid = me()
OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())
  1. Multiple Queries:

    Evaluate a series of FQL queries in one call and return data in a single response.

    This method utilizes a JSON encoded dictionary to call queries, where each query shares the syntax of a single query. However, this approach allows for the creation of complex multiple queries. You can fetch data from one query and use it in another in the same call. The WHERE clause is optional in subsequent queries, as the necessary data has already been fetched. To reference the result of one query in another within the same call, you prefix its name with a #.

    For example, if you want to gather data about a user attending an event, typically you'd have to call two queries, waiting for the first to complete in order to obtain data before calling the second. However, with fql.multiquery, you can call both at once and fetch all the data you need, achieving better performance than sequential SQL queries. First, you'd request the user ID and RSVP status of each attendee as follows for query1:

    “query1”:”SELECT uid, rsvp_status FROM event_member WHERE eid=12345678”

    Then to retrieve profile data for each attendee (name, URL, picture), you'd create query2, which references the data from query1. You'd structure query 2 like this:

    “query2”:”SELECT name, url, pic FROM profile WHERE id IN (SELECT uid FROM “query1”)

Relative