2017 © Pedro Peláez
 

library facebook-query-builder

An elegant and efficient way to generate nested requests for Facebook's Graph API.

image

sammyk/facebook-query-builder

An elegant and efficient way to generate nested requests for Facebook's Graph API.

  • Sunday, July 23, 2017
  • by SammyK
  • Repository
  • 10 Watchers
  • 90 Stars
  • 91,366 Installations
  • PHP
  • 2 Dependents
  • 0 Suggesters
  • 16 Forks
  • 4 Open issues
  • 15 Versions
  • 10 % Grown

The README.md

Facebook Query Builder

Build Status Latest Stable Version Total Downloads License, (*1)

A query builder that makes it easy to create complex & efficient nested requests to Facebook's Graph API to get lots of specific data back with one request., (*2)

Facebook Query Builder has no production dependencies., (*3)

$fqb = new SammyK\FacebookQueryBuilder\FQB;

$photosEdge = $fqb->edge('photos')->fields(['id', 'source'])->limit(5);
$request = $fqb->node('me')->fields(['id', 'email', $photosEdge]);

echo (string) $request;
# https://graph.facebook.com/me?fields=id,email,photos.limit(5){id,source}

Introduction

The Facebook Query Builder uses the same Graph API nomenclature for three main concepts:, (*4)

  1. Node: A node represents a "real-world thing" on Facebook like a user or a page.
  2. Edge: An edge is the relationship between two or more nodes. For example a "photo" node would have a "comments" edge.
  3. Field: Nodes have properties associated with them. These properties are called fields. A user has an "id" and "name" field for example.

When you send a request to the Graph API, the URL is structured like so:, (*5)

https://graph.facebook.com/node-id/edge-name?fields=field-name

To generate the same URL with Facebook Query Builder, you'd do the following:, (*6)

$edge = $fqb->edge('edge-name')->fields('field-name');
echo $fqb->node('node-id')->fields($edge);

If you were to execute that script, you might be surprised to see the URL looks a little different because it would output:, (*7)

https://graph.facebook.com/node-id?fields=edge-name{field-name}

The two URL's are functionally identical with the exception of how the Graph API returns the response data. What makes the URL generated with Facebook Query Builder different is that it is being expressed as a nested request., (*8)

And that is what makes Facebook Query Builder so powerful. It does the heavy lifting to generate properly formatted nested requests from a fluent, easy-to-read PHP interface., (*9)

Installation

Facebook Query Builder is installed using Composer. Add the Facebook Query Builder package to your composer.json file., (*10)

{
    "require": {
        "sammyk/facebook-query-builder": "^2.0"
    }
}

Usage

Initialization

To start interfacing with Facebook Query Builder you simply instantiate a FQB object., (*11)

// Assuming you've included your composer autoload.php file before this line.
$fqb = new SammyK\FacebookQueryBuilder\FQB;

There are a number of configuration options you can pass to the FQB constructor., (*12)

A basic example

Below is a basic example that gets the logged in user's id & email (assuming the user granted your app the email permission)., (*13)

$fqb = new SammyK\FacebookQueryBuilder\FQB;

$request = $fqb->node('me')
               ->fields(['id', 'email'])
               ->accessToken('user-access-token')
               ->graphVersion('v3.1');

echo $request;
# https://graph.facebook.com/v3.1/me?access_token=user-access-token&fields=id,email

$response = file_get_contents((string) $request);

var_dump($response);
# string(50) "{"id":"12345678","email":"foo-bar\u0040gmail.com"}"

Get data across multiple edges

The bread and butter of the Facebook Query Builder is its support for nested requests. Nested requests allow you to get a lot of data from the Graph API with just one request., (*14)

The following example will get the logged in user's name & first 5 photos they are tagged in with just one call to Graph., (*15)

$fqb = new SammyK\FacebookQueryBuilder\FQB([/* . . . */]);

$photosEdge = $fqb->edge('photos')->fields(['id', 'source'])->limit(5);
$request = $fqb->node('me')->fields(['name', $photosEdge]);

echo $request;
# https://graph.facebook.com/me?fields=name,photos.limit(5){id,source}

// Assumes you've set a default access token
$response = file_get_contents((string) $request);

var_dump($response);
# string(1699) "{"name":"Sammy Kaye Powers","photos":{"data":[{"id":"123","source":"https:\/\/scontent.xx.fbcdn.net\/hphotos-xfp1 . . .

And edges can have other edges embedded in them to allow for infinite deepness. This allows you to do fairly complex calls to Graph while maintaining very readable code., (*16)

The following example will get user 1234's name, and first 10 photos they are tagged in. For each photo it gets the first 2 comments and all the likes., (*17)

$fqb = new SammyK\FacebookQueryBuilder\FQB([/* . . . */]);

$likesEdge = $fqb->edge('likes');
$commentsEdge = $fqb->edge('comments')->fields('message')->limit(2);
$photosEdge = $fqb->edge('photos')
                  ->fields(['id', 'source', $commentsEdge, $likesEdge])
                  ->limit(10);

$request = $fqb->node('1234')->fields(['name', $photosEdge]);

echo $request;
# https://graph.facebook.com/1234?fields=name,photos.limit(10){id,source,comments.limit(2){message},likes}

// Assumes you've set a default access token
$response = file_get_contents((string) $request);

var_dump($response);
# string(10780) "{"name":"Some Foo User","photos":{"data":[ . . .

Sending the nested request

Since Facebook Query Builder is just a tool that generates nested request syntax, it doesn't make any requests to the Graph API for you. You'll have to use some sort of HTTP client to send the requests., (*18)

We'll assume you've already created an app in Facebook and have obtained an access token., (*19)

Requests with The Facebook PHP SDK

The recommended way to send requests & receive responses is to use the official Facebook PHP SDK v5. You'll need to create an instance of the Facebook\Facebook super service class from the native Facebook PHP SDK., (*20)

$fb = new Facebook\Facebook([
    'app_id' => 'your-app-id',
    'app_secret' => 'your-app-secret',
    'default_graph_version' => 'v3.1',
    ]);
$fqb = new SammyK\FacebookQueryBuilder\FQB;

$fb->setDefaultAccessToken('my-access-token');

$request = $fqb->node('me')->fields(['id', 'name', 'email']);

echo $request->asEndpoint();
# /me?fields=id,name,email

try {
    $response = $fb->get($request->asEndpoint());
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo $e->getMessage();
    exit;
}

var_dump($response->getDecodedBody());

You'll noticed we're using the asEndpoint() method to send the generated request to the SDK. That's because the SDK will automatically prefix the URL with the Graph API hostname. The asEndpoint() method will return an un-prefixed version of the URL., (*21)

The official Facebook PHP SDK will automatically add the Graph API version, the app secret proof, and the access token to the URL for you, so you don't have to worry about setting those options on the FQB object., (*22)

Requests with native PHP

As you've already seen in the basic examples above, you can simply use PHP's flexible file_get_contents() to send the requests to the Graph API. Just be sure to set your Graph API version prefix with default_graph_version & set your app secret with app_secret to ensure all the requests get signed with an app secret proof., (*23)

$fqb = new SammyK\FacebookQueryBuilder\FQB([
    'default_graph_version' => 'v3.1',
    'app_secret'            => 'your-app-secret',
]);

// Grab Mark Zuckerberg's public info
$request = $fqb->node('4')->accessToken('my-access-token');

echo $request;
# https://graph.facebook.com/v3.1/4?access_token=my-access-token&appsecret_proof=2ad43b865030f51531ac36bb00ce4f59d9f879ecce31b0977dbfd73fa4eca7b6

$response = file_get_contents((string) $request);

var_dump($response);

For more info about handling the response, check out responses with native PHP below., (*24)

Obtaining an access token

As the Facebook Query Builder is exclusive to building nested request syntax, it cannot be used directly to obtain an access token., (*25)

The Facebook login process uses OAuth 2.0 behind the scenes. So you can use any OAuth 2.0 client library to obtain a user access token from Facebook. Here are a few recommendations:, (*26)

Configuration settings

A number of configuration settings can be set via the FQB constructor., (*27)

$fqb = new SammyK\FacebookQueryBuilder\FQB([
    'default_access_token'  => 'your-access-token',
    'default_graph_version' => 'v3.1',
    'app_secret'            => 'your-app-secret',
]);

Setting the access token

If you're using the Facebook PHP SDK and have set a default access token for the SDK to use, then you won't need to worry about appending the access token to the request., (*28)

If you're using some other HTTP client, you can set the default fallback access token when you instantiate the FQB service with the default_access_token option or you can append the access token to the nested request using the accessToken() method., (*29)

$fqb = new SammyK\FacebookQueryBuilder\FQB([
    'default_access_token' => 'fallback_access_token',
]);

$request = $fqb->node('me');
echo $request->asEndpoint();
# /me?access_token=fallback_access_token

$request = $fqb->node('me')->accessToken('bar_token');
echo $request->asEndpoint();
# /me?access_token=bar_token

Setting the Graph version

It's important that you set the version of the Graph API that you want to use since the Graph API is subject to a breaking change schedule., (*30)

If you're using the Facebook PHP SDK and have set a default Graph version for the SDK to use, then you won't need to worry about setting the Graph version in the Facebook Query Builder., (*31)

If you're using some other HTTP client, you can set the default fallback Graph version when you instantiate the FQB service with the default_graph_version option or you can set it on a per-request basis using the graphVersion() method., (*32)

$fqb = new SammyK\FacebookQueryBuilder\FQB([
    'default_graph_version' => 'v3.1',
]);

$request = $fqb->node('me');
echo $request->asEndpoint();
# /v3.1/me

$request = $fqb->node('me')->graphVersion('v1.0');
echo $request->asEndpoint();
# /v1.0/me

PS: Graph v1.0 is dead. :skull:, (*33)

Enabling app secret proof

As an added security feature, you can sign each request to the Graph API with an app_secretproof. It is highly recommended that you edit your app settings to require the app secret proof for all requests., (*34)

If you're using the Facebook PHP SDK to send requests to the Graph API, it will automatically append the app secret proof for you., (*35)

If you're using some other HTTP client, the app secret proof will be generated for a request if both an access token and app secret are set for a request. You can set the app secret when you instantiate the FQB service using the app_secret option., (*36)

$fqb = new SammyK\FacebookQueryBuilder\FQB([
    'app_secret' => 'foo_secret',
]);

$request = $fqb->node('me')->accessToken('bar_token');
echo $request->asEndpoint();
# /me?access_token=bar_token&appsecret_proof=2ceec40b7b9fd7d38fff1767b766bcc6b1f9feb378febac4612c156e6a8354bd

Enabling the beta version of Graph

Before changes to the Graph API are rolled out to production, they are deployed to the beta tier first., (*37)

By default, when you generate a nested request, it will be prefixed with the production hostname for the Graph API which is https://graph.facebook.com/., (*38)

echo (string) $fqb->node('4');
# https://graph.facebook.com/4

To enable the beta tier for the requests generated by FQB, set the enable_beta_mode option to true. Once enabled, all generated URL's will be prefixed with the beta hostname of the Graph API which is https://graph.beta.facebook.com/., (*39)

$fqb = new SammyK\FacebookQueryBuilder\FQB([
    'enable_beta_mode' => true,
]);

echo (string) $fqb->node('4');
# https://graph.beta.facebook.com/4

Method reference

node()

node(string $graphNodeName): FQB

Returns a new mutable instance of the FQB entity. Any valid Graph node or endpoint on the Graph API can be passed to node()., (*40)

$userNode = $fqb->node('me');

edge()

node(string $edgeName): GraphEdge

Returns an mutable instance of GraphEdge entity to be passed to the FQB::fields() method., (*41)

$photosEdge = $fqb->edge('photos');

fields()

fields(mixed $fieldNameOrEdge[, mixed $fieldNameOrEdge[, ...]]): FQB

Set the fields and edges for a GraphNode or GraphEdge entity. The fields and edges can be passed as an array or list of arguments., (*42)

$edge = $fqb->edge('some_edge')->fields(['field_one', 'field_two']);
$node = $fqb->node('some_node')->fields('my_field', 'my_other_field', $edge);

modifiers()

modifiers(array $modifiers): FQB

Some endpoints of the Graph API support additional parameters called "modifiers"., (*43)

An example endpoint that supports modifiers is the /{object-id}/comments edge., (*44)

// Order the comments in chronological order
$commentsEdge = $fqb->edge('comments')->modifiers(['filter' => 'stream']);
$request = $fqb->node('1044180305609983')->fields('name', $commentsEdge);

limit()

limit(int $numberOfResultsToReturn): FQB

You can specify the number of results the Graph API should return from an edge with the limit() method., (*45)

$edge = $fqb->edge('photos')->limit(7);

Since the "limit" functionality is just a modifier in the Graph API, the limit() method is a convenience method for sending the limit param to the modifiers() method. So the same functionality could be expressed as:, (*46)

$edge = $fqb->edge('photos')->modifiers(['limit' => 7]);

accessToken()

accessToken(string $accessToken): FQB

You can set the access token for a specific request with the accessToken() method., (*47)

$request = $fqb->node('BradfordWhelanPhotography')->accessToken('foo-token');

echo $request->asEndpoint();
# /BradfordWhelanPhotography?access_token=foo-token

graphVersion()

graphVersion(string $graphApiVersion): FQB

You can set the Graph version URL prefix for a specific request with the graphVersion() method., (*48)

$request = $fqb->node('me')->graphVersion('v3.1');

echo $request->asEndpoint();
# /v3.1/me

asUrl()

asUrl(): string

You can obtain the generated request as a full URL using the asUrl() method., (*49)

$request = $fqb->node('me');

echo $request->asUrl();
# https://graph.facebook.com/me

The magic method __toString() is a alias to the asUrl() method so casting the FQB instance as a string will perform the same action., (*50)

$request = $fqb->node('me');

echo (string) $request;
# https://graph.facebook.com/me

asEndpoint()

asEndpoint(): string

The asEndpoint() is identical to the asUrl() method except that it will return the URL without the Graph API hostname prefixed to it., (*51)

$request = $fqb->node('me');

echo $request->asEndpoint();
# /me

This is particularly handy for working with the official Facebook PHP SDK which will automatically prefix the Graph hostname to the URL for you., (*52)

Handling the response

Responses will vary depending on what HTTP client you're using to interface with the Graph API., (*53)

Responses with the Facebook PHP SDK

All responses from the get(), post(), and delete() methods return a Facebook\FacebookResponse from the native Facebook PHP SDK., (*54)

$fb = new Facebook\Facebook([/* . . . */]);
$fqb = new SammyK\FacebookQueryBuilder\FQB([/* . . . */]);

$fb->setDefaultAccessToken('my-access-token');

$request = $fqb->node('me')->fields(['email', 'photos']);

echo $request->asEndpoint();
# /me?fields=email,photos

try {
    $response = $fb->get($request->asEndpoint());
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo $e->getMessage();
    exit;
}

$userNode = $response->getGraphUser();

// Access properties like an array
$email = $userNode['email'];

// Get data as array
$userNodeAsArray = $userNode->asArray();

// Get data as JSON string
$userNodeAsJson = $userNode->asJson();

// Iterate over the /photos edge
foreach ($userNode['photos'] as $photo) {
    // . . .
}

// Morph the data with a closure
$userNode['photos']->each(function ($value) {
    $value->new_height = $value->height + 22;
});

See the official documentation for more information on the FacebookResponse entity., (*55)

Responses with native PHP

If you're using file_get_contents() to send requests to the Graph API, the responses will be a string of JSON from the Graph API. You can decode the JSON responses to a plain-old PHP array., (*56)

$fqb = new SammyK\FacebookQueryBuilder\FQB([/* . . . */]);

$request = $fqb->node('4')
               ->fields(['id', 'name'])
               ->accessToken('user-access-token');

echo $request;
# https://graph.facebook.com/4?access_token=user-access-token&fields=id,name

$response = file_get_contents((string) $request);

$data = json_decode($response, true);

var_dump($data);
# array(2) { ["id"]=> string(1) "4" ["name"]=> string(15) "Mark Zuckerberg" }

If there was an error response from the Graph API, file_get_contents() will return false and raise a warning. This can be problematic since the Graph API returns error details in the body of the response., (*57)

To get the error response data we need to tell file_get_contents() to return the response body even when the response contains an error HTTP status code. We can do this by setting ignore_errors to true with the stream_context_create() function., (*58)

You can also investigate the error response further by examining the response headers. The headers are stored in the $http_response_header variable which gets set automatically by file_get_contents()., (*59)

$fqb = new SammyK\FacebookQueryBuilder\FQB([/* . . . */]);

$request = $fqb->node('Some-Invalid-Node')->accessToken('user-access-token');

echo $request;
# https://graph.facebook.com/Some-Invalid-Node?access_token=user-access-token

$context = stream_context_create(['http' => ['ignore_errors' => true]]);
$response = file_get_contents((string) $request, null, $context);

$data = json_decode($response, true);
var_dump($data);
/*
array(1) {
  ["error"]=>
  array(4) {
    ["message"]=>
    string(27) "Invalid OAuth access token."
    ["type"]=>
    string(14) "OAuthException"
    ["code"]=>
    int(190)
    ["fbtrace_id"]=>
    string(11) "A8oB9BtqtZ4"
  }
}
*/

var_dump($http_response_header);
/*
array(14) {
  [0]=>
  string(24) "HTTP/1.1 400 Bad Request"
  [1]=>
  string(89) "WWW-Authenticate: OAuth "Facebook Platform" "invalid_token" "Invalid OAuth access token.""
  [2]=>
  string(30) "Access-Control-Allow-Origin: *"
  [3]=>
  string(44) "Content-Type: text/javascript; charset=UTF-8"
  [4]=>
  string(26) "X-FB-Trace-ID: h8oB7BtrtZ3"
  [5]=>
  string(17) "X-FB-Rev: 4971439"
  [6]=>
  string(16) "Pragma: no-cache"
  [7]=>
  string(23) "Cache-Control: no-store"
  [8]=>
  string(38) "Expires: Sat, 01 Jan 2000 00:00:00 GMT"
  [9]=>
  string(21) "Vary: Accept-Encoding"
  [10]=>
  string(100) "X-FB-Debug: FOOE54KJadh9P2HOSUlSFQmNEEf/9CF4ZtgZQ=="
  [11]=>
  string(35) "Date: Fri, 09 Oct 2015 04:43:44 GMT"
  [12]=>
  string(17) "Connection: close"
  [13]=>
  string(19) "Content-Length: 113"
}
*/

Testing

Just run phpunit from the root directory of this project., (*60)

bash $ ./vendor/bin/phpunit, (*61)

Contributing

Please see CONTRIBUTING for details., (*62)

CHANGELOG

Please see CHANGELOG for history., (*63)

Credits

License

The MIT License (MIT). Please see License File for more information.## License, (*64)

Security

If you find a security exploit in this library, please notify the project maintainer privately to get the issue resolved., (*65)

The Versions

23/07 2017

dev-master

9999999-dev https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to generate nested requests for Facebook's Graph API.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

sdk facebook graph api

11/05 2015

2.0.0

2.0.0.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to generate nested requests for Facebook's Graph API.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

sdk facebook graph api

09/11 2014

1.1.x-dev

1.1.9999999.9999999-dev https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

09/11 2014

1.1.3

1.1.3.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

06/11 2014

1.1.2

1.1.2.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

05/09 2014

1.1.1

1.1.1.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

16/07 2014

1.1.0

1.1.0.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

10/06 2014

1.0.7

1.0.7.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

06/06 2014

1.0.6

1.0.6.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

03/06 2014

1.0.5

1.0.5.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

31/05 2014

1.0.4

1.0.4.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

30/05 2014

1.0.3

1.0.3.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

29/05 2014

1.0.2

1.0.2.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

08/05 2014

1.0.1

1.0.1.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api

07/05 2014

1.0.0

1.0.0.0 https://github.com/SammyK/FacebookQueryBuilder

An elegant and efficient way to interface with Facebook's Graph API

  Sources   Download

MIT

The Requires

 

The Development Requires

sdk facebook graph api