1. 程式人生 > >Using the Graph API

Using the Graph API

Reading

Nodes

Reading operations almost always begin with a node. A node is an individual object with a unique ID. For example, there are many User node objects, each with a unique ID representing a person on Facebook. To read a node, you query a specific object's ID. So, to read your User node you would query its ID:

curl -i -X GET \
 "https://graph.facebook.com/v3.2/{your-user-id}?fields=id,name&access_token={user-access-token}"
GraphRequest request = GraphRequest.newMeRequest(
  accessToken,
  new GraphRequest.GraphJSONObjectCallback() {
    @Override
    public void onCompleted(JSONObject object, GraphResponse response) {
      // Insert your code here
    }
});

Bundle parameters = new Bundle();
parameters.putString("fields", "id,name");
request.setParameters(parameters);
request.executeAsync();
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/me"
           parameters:@{ @"fields": @"id,name",}
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];
FB.api(
  '/me',
  'GET',
  {"fields":"id,name"},
  function(response) {
      // Insert your code here
  }
);
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/me',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

This request would return the following fields (node properties) by default, formatted using JSON:

{
  "name": "Your Name",
  "id": "your-user-id"
}

Edges

Nodes have edges, which usually can return collections of other nodes which are attached to them. To read an edge, you must include both the node ID and the edge name in the path. For example, /user nodes have a /feed edge which can return all Post nodes on a User. You'll need to get a new access token and select user_posts permissions during the Get access token flow. Here's how you could use the edge to get all your Posts:

curl -i -X GET "https://graph.facebook.com/{your-user-id}/feed?access_token={user-access-token}"
GraphRequest request = GraphRequest.newGraphPathRequest(
  accessToken,
  "/me/feed",
  new GraphRequest.Callback() {
    @Override
    public void onCompleted(GraphResponse response) {
      // Insert your code here
    }
});

request.executeAsync();
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/me/feed"
           parameters:nil
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];
FB.api(
  '/me/feed',
  'GET',
  {},
  function(response) {
      // Insert your code here
  }
);
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/me/feed',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

The JSON response would look something like this:

{
  "data": [
    {
      "created_time": "2017-12-08T01:08:57+0000",
      "message": "Love this puzzle. One of my favorite puzzles",
      "id": "post-id"
    },
    {
      "created_time": "2017-12-07T20:06:14+0000",
      "message": "You need to add grape as a flavor.",
      "id": "post-id"
    }
  ]
}

Notice that the response contains not only the IDs of the Post nodes in the collection, but the created_time and message fields as well. This is common. Most edges will include one or more fields by default.

Fields

Fields are node properties. When you query a node it will return a set of fields by default, as the examples above show. However, you can specify which fields you want returned by using the fields parameter and listing each field. This will override the defaults and return only the fields you specify, and the ID of the object, which is always returned.

For example, the User node reference indicates which fields you can ask for when reading a User node. If you wanted to get your birthday, hometown, and email fields, you'll need to get a new access token with user_birthday, email, and 'user_hometown` permissions during the Get access token flow and try this:

curl -i -X "GET https://graph.facebook.com/{your-user-id}?fields=birthday,email,hometown&access_token={user-access-token}"
GraphRequest request = GraphRequest.newGraphPath
        
        Request(
  accessToken,
  new GraphRequest.GraphJSONObjectCallback() {
    @Override
    public void onCompleted(JSONObject object, GraphResponse response) {
      // Insert your code here
    }
});

Bundle parameters = new Bundle();
parameters.putString("fields", "birthday,email,hometown");
request.setParameters(parameters);
request.executeAsync();
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/{your-user-id}"
           parameters:@{ @"fields": @"birthday,email,hometown",}
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];
FB.api(
  '/{your-user-id}',
  'GET',
  {"fields":"birthday,email,hometown"},
  function(response) {
      // Insert your code here
  }
);
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}',
    array (
      'fields' => 'birthday','email','hometown'
    ),
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

This would return the following response:

{
  "hometown": "Your, Hometown"
  "birthday": "01/01/1985",
  "email": "[email protected]",
  "id": "{your-user-id}"
}

Edges, which typically return collections of objects, also return fields about each object in the collection. Let's say you used the /photos edge to get all of the Photo nodes from your timeline:

curl -i -X GET "https://graph.facebook.com/{your-user-id}/photos?access_token={user-access-token}"
GraphRequest request = GraphRequest.newGraphPathRequest(
  accessToken,
  "/{your-user-id}/photos",
  new GraphRequest.Callback() {
    @Override
    public void onCompleted(GraphResponse response) {
      // Insert your code here
    }
});

request.executeAsync();
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/{your-user-id}/photos"
           parameters:nil
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];
FB.api(
  '/{your-user-id}/photos',
  'GET',
  {},
  function(response) {
      // Insert your code here
  }
);
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}/photos',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

This would generate a response that looks similar to this:

{
  "data": [
    {
      "created_time": "2016-08-23T13:12:10+0000",
      "id": "1308573619175349"        // Photo ID
    },
    {
      "created_time": "2016-08-05T22:34:19+0000",
      "id": "1294456907253687"        // Photo ID
    },
    {
      "created_time": "2016-04-29T16:17:02+0000",
      "id": "1228552183844160"        // Photo ID
    }
  ]
}

As you can see, the /photos edge by default will return a collection of Photo node IDs as well as the created_time property for each photo. Just like with nodes, you can use the fields parameter to specify which fields you want returned for each of the objects returned in the collection.

Let's say you wanted to get the height, and width fields for each Photo node returned by the /photos edge:

curl -i -X GET "https://graph.facebook.com/{your-user-id}/photos?fields=height,width&access_token={user-access-token}"
GraphRequest request = GraphRequest.newGraphPathRequest(
  accessToken,
  "/{your-user-id}/photos",
  new GraphRequest.Callback() {
    @Override
    public void onCompleted(GraphResponse response) {
      // Insert your code here
    }
});

Bundle parameters = new Bundle();
parameters.putString("fields", "height,width");
request.setParameters(parameters);
request.executeAsync();
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/{your-user-id}/photos"
           parameters:@{ @"fields": @"height,width",}
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];
FB.api(
  '/{your-user-id}/photos',
  'GET',
  {"fields":"height,width"},
  function(response) {
      // Insert your code here
  }
);
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}/photos',
    array (
      'fields' => 'height','width'
    )
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

Here's what the response would look like:

{
  "data": [
    {
      "height": 720,
      "width": 720,
      "id": "1308573619175349"        // Photo ID
    },
    {
      "height": 720,
      "width": 720,
      "id": "1294456907253687"        // Photo ID
    },
    {
      "height": 180,
      "width": 180,
      "id": "1228552183844160"        // Photo ID
    }
  ]
}

Note that you can specify an edge with the fields parameter as well, which is useful when you are using field expansion.

Field Expansion

If you happened to test the GET /page/photos query above in the Graph API Explorer, you probably noticed that the request returned more than three objects and also paginated the results. This is common for most edges. We'll cover traversing results soon, but for now let's look at field expansion, which allows you to not only perform nested queries, but also limit and order the results.

Limiting Results

Limiting allows you to control the number of objects returned in each set of paginated results. To limit results, add a .limit() argument to any field or edge.

For example, performing a GET request on your /feed edge may return hundreds of Posts. You can limit the number of Posts returned for each page of results by doing this:

curl -i -X GET "https://graph.facebook.com/{your-user-id}?fields=feed.limit(3)&access_token={your-access-token}"
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}',
    array (
      'fields' => 'feed.limit(3)' 
    )
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

This returns all of the Posts on your User node, but limits the number of objects in each page of results to three. Notice that instead of specifying the Feed edge in the path URL (/user/feed), you specify it in the fields parameter (?fields=feed), which allows you to append the .limit(3) argument.

Here are the query results:

{
  "feed": {
    "data": [
      {
        "created_time": "2017-12-12T01:24:21+0000",
        "message": "This picture of my grandson with Santa",
        "id": "{your-user-id}_1809387339093972"       // Post ID
      },
      {
        "created_time": "2017-12-11T23:40:17+0000",
        "message": ":)",
        "id": "{your-user-id}_1809316002434439"       // Post ID
      },
      {
        "created_time": "2017-12-11T23:31:38+0000",
        "message": "Thought you might enjoy this.",
        "id": "{your-user-id}_1809310929101613"       // Post ID
      }
    ],
    "paging": {
      "previous": "https://graph.facebook.com/v3.2/{your-user-id}/feed?format=json&limit=3&since=1542820440&access_token={your-user-access-token}&__paging_token=enc_AdCgj6RSGWTYV7EXj2cFlOWJjbZCq8oI3ogIpLrxPCVK3U8Kad0EgsZA2vri3YKIwl71XGRDJz9C8TgqMeyiu8U5CD&__previous=1",
      "next": "https://graph.facebook.com/v3.2/{your-user-id}/feed?format=json&limit=3&access_token={your-user-access-token}&until=1542583212&__paging_token=enc_AdDLmzUgWiLo6oHGCI53S5begiKOfNZBY0affrLMWgheBzfwMA7XSKmgjyNbuZBIptdXc18j1Se0Dm7vEsePh1SoM3"
    }
  },
  "id": "{your-user-id}"
}

As you can see, only three objects appear in this page of paginated results, but the response included a next field and URL which you can use to fetch the next page. Note: Notice that the Post ID is a combination of the ID the object was published on, in this case the User node, and a new ID string.

Ordering Results

You can order results based on object creation time. To do this, use a .order() argument with one of the following values on either a field or edge.

  • chronological — orders results with the oldest created objects first.
  • reverse_chronological — orders results with the newest created objects first.

For example, let's get all of your Posts, order the results chronologically (oldest first), and limit the number of objects per paginated result to three:

curl -i -X GET "https://graph.facebook.com/{your-user-id}?fields=feed.order(chronological).limit(3)&access_token={your-user-access-token}"
GraphRequest request = GraphRequest.newGraphPathRequest(
  accessToken,
  "/{your-user-id}",
  new GraphRequest.Callback() {
    @Override
    public void onCompleted(GraphResponse response) {
      // Insert your code here
    }
});

Bundle parameters = new Bundle();
parameters.putString("fields", "feed.order(chronological).limit(3)");
request.setParameters(parameters);
request.executeAsync();
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/{your-user-id}"
           parameters:@{ @"fields": @"feed.order(chronological).limit(3)",}
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];
FB.api(
  '/{your-user-id}',
  'GET',
  {"fields":"feed.order(chronological).limit(3)"},
  function(response) {
      // Insert your code here
  }
);
try {
  // Returns a `FacebookFacebookResponse` object
  $response = $fb->get(
    '/{your-user-id}',
    '{access-token}'
  );
} catch(FacebookExceptionsFacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
$graphNode = $response->getGraphNode();

Again, notice that in order to use an argument on an edge you have to specify the edge in the fields parameter. And as you can see, you can combine .limit() and .order() arguments on a single field or edge.

Here are the results:

{
  "feed": {
    "data": [
      {
        "created_time": "2017-12-12T01:24:21+0000",
        "message": "This picture of my grandson with Santa",
        "id": "{your-user-id}_1809387339093972"       // Post ID
      },
      {
        "created_time": "2017-12-11T23:40:17+0000",
        "message": ":)",
        "id": "{your-user-id}_1809316002434439"       // Post ID
      },
      {
        "created_time": "2017-12-11T23:31:38+0000",
        "message": "Thought you might enjoy this.",
        "id": "{your-user-id}_1809310929101613"       // Post ID
      }
    ],
    "paging": {
      "previous": "https://graph.facebook.com/v3.2/{your-user-id}/feed?format=json&limit=3&since=1542820440&access_token={your-user-access-token}&__paging_token=enc_AdCgj6RSGWTYV7EXj2cFlOWJjbZCq8oI3ogIpLrxPCVK3U8Kad0EgsZA2vri3YKIwl71XGRDJz9C8TgqMeyiu8U5CD&__previous=1",
      "next": "https://graph.facebook.com/v3.2/{your-user-id}/feed?format=json&limit=3&access_token={your-user-access-token}&until=1542583212&__paging_token=enc_AdDLmzUgWiLo6oHGCI53S5begiKOfNZBY0affrLMWgheBzfwMA7XSKmgjyNbuZBIptdXc18j1Se0Dm7vEsePh1SoM3"
    }
  },
  "id": "{your-user-id}"
}

相關推薦

Using the Graph API

ReadingNodes Reading operations almost always begin with a node. A node is an individual object with a unique ID. For example, there are many User node ob

Using the SSL API【Erlang手冊翻譯】

如何使用SSL的API 翻譯得捉雞,拿捏不好的地方保留英文。 通過使用ssl:versions/0可以檢視到ssl的版本資訊 ssl:cipher_suites/0檢視所支援的cipher_suites,並不是所有的SSL的連線都是可用的,這要考慮到證書的問題。預設

A practical ES6 guide on how to perform HTTP requests using the Fetch API

In this guide, I’ll show you how to use the Fetch API (ES6+) to perform HTTP requests to an REST API with some practical examples you’ll most likely encoun

Getting Started With the Slack API Using Python and Flask

The slick hosted chat application Slack is all the rage this year. The tool’s adoption isn’t empty hype - it’s incredibly useful for communicating with

SaltStack – Using the Mysql Module

saltstacksalt ‘*‘ saltutil.refresh_pillar官網的例子真的沒看懂,英文菜。其實就簡單一步。參考文檔https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.mysql.htmlhttps://z90

facebook graph api 報錯SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)')

asa res http ner none object odin bundle dap 使用facebook graph api,報錯如下 一開始以為是https證書驗證失敗,查了一下午源碼,沒有看到問題,於是把Python27\lib\site-packages\re

Agent admitted failure to sign using the key

連接服務器 用戶 sin col p s 服務 failure sig round SSH生成id_rsa, id_rsa.pub後,連接服務器卻報:Agent admitted failure to sign using the key錯誤。解決方法:在當前用戶下執行命令

Instruction of Using The AMI

ron default see note reat gpu external lease window Step 1: GPU Instance and AMI The first thing we‘ll do is select the AMI and an in

[Typescript] Installing Promise Type Definitions Using the lib Built-In Types

efi null gpo module div col ice -c dice To fix Promise is not recolized in TypeScript, we can choose to use a lib: npm i @types/es6-pr

圖神經網絡 The Graph neural network model

結果 最新 mode 相關 論文 總結 關註 del 展開 1 圖神經網絡(原始版本) 圖神經網絡現在的威力和用途也再慢慢加強 我從我看過的最原始和現在慢慢最新的論文不斷寫上我的看法和見解 本人出身數學 所以更喜歡數學推導 第一篇就介紹圖神經網絡想法的開端 之後的圖神經

[Python] Create a minimal website in Python using the Flask Microframework

() turn ini pass work def col out code How to install Flask Use Flask to create a minimal website Build routes in Flask to respond to web

CodeForces - 724G Xor-matic Number of the Graph

examples pro compute sizeof sam class 路徑 fin dir Discription You are given an undirected graph, constisting of n vertices and m edges. Ea

[BZOJ1322]Destroying The Graph

bzoj names graph spa cap esp end 操作 網絡流 題目大意:有一張有向圖,對於每個點,有兩種操作:1. 刪掉它的所有入邊2. 刪掉它的所有出邊對每個點的每個操作均有不同的價值。求使得圖上沒有邊的最小價值。解題思路:考慮把點拆成入點和出點,然後就

CF.724G.Xor-matic Number of the Graph(線性基)

sizeof () har 構造 .com 路徑 getch tps add 題目鏈接 \(Description\) 給定一張帶邊權無向圖。若存在u->v的一條路徑使得經過邊的邊權異或和為s(邊權計算多次),則稱(u,v,s)為interesting triple。

some understanding of《Inferring Decision Trees Using the Minimum Description Length Principle*》

《Inferring Decision Trees Using the Minimum Description Length Principle*》 Information And Computation 80, 227-248(1989) My difficulty is: how

Author name disambiguation using a graph model with node splitting and merging based on bibliographic information

分隔 需要 sin 相似性度量 進行 ati 判斷 特征向量 edi Author name disambiguation using a graph model with node splitting and merging based on bibliographic

JNI(5)The Invocation API

呼叫API允許軟體提供商載入Java VM 到任意的本地應用中。供應商可以提供支援Java的應用程式而無需連結Java VM的程式碼。 概述 下面程式碼展示了通過呼叫API如何使用函式。這個例子中C++程式碼建立了一個Java VM 和呼叫一個靜態方法,方法為Main.test.為了程

[WASM] Run WebAssembly in Node.js using the node-loader

WebAssembly is great for targeting performance bottlenecks in the browser. Now with node-loader, we can do the same on the server through Node.js While No

Open restaurant using the business density report

Sometimes, we will confuse where to open a restaurant while we are rich enough. So, can we find the way to do the assessments? Of course, yes. So, let’s do

Face Detection and Tracking Using the KLT Algorithm

Face Detection and Tracking Using the KLT Algorithm from: https://cn.mathworks.com/help/vision/examples/face-detection-and-tracking-using-