Search code examples
facebookfacebook-graph-apiphoto

Get photo from post using Facebook graph API


I am attempting to display the latest post from a public Facebook page on a website using the graph API.

Using the following URL, I am able to get the latest posts data:

https://graph.facebook.com/MYPAGENAME/posts?access_token=MYACCESSTOKEN

Which returns:

 {
   "data": [
            {
             "story": "MYPAGENAME added a new photo.",
             "created_time": "2017-08-20T19:00:00+0000",
             "id": "MYID"
            }

      ...

The post in question displays on the Facebook page with a photo included, but there is not 'photo' object (or anything similar) returned in the API data. How do I access the picture URL for this post? Thanks in advance.


Solution

  • This request will fetch posts and the media information for the first image for each post.

    /posts?fields=attachments{media}?access_token=YOUR_ACCESS_TOKEN
    

    Sometimes posts contain multiple images. If you'd like to support that you need to fetch the subattachments also:

    /posts?fields=attachments{subattachments{media}}?access_token=YOUR_ACCESS_TOKEN
    

    Note that this method usually only provides image URLs that are up to 720px wide. If you want higher resolution imagery, you need to access data[0].attachments.data[0].subattachments.data[0].target.id to get the actual image ID which you can then use to perform an additional query /IMAGE_ID_HERE?fields=images to obtain the higher resolution image. Increment the numbers to get additional posts and images inside each post.