Ivan Kozlov
Ivan Kozlov

Reputation: 561

Facebook graph api. Get photos from albums

Please help me to make a correct request to Facebook api. Now i've got:

https://graph.facebook.com/me/albums?fields=photos

As the result I get very big Json with a lot of unnecessary info. I tried to do something like this:

https://graph.facebook.com/me/albums?fields=photos?fields=source,name,id

or like this:

https://graph.facebook.com/me/albums?fields=photos&fields=source,name,id

But graph api explorer, returned the same big response, or i caught an error. Any ideas how to do more compact response with only necessary info?

Upvotes: 11

Views: 40315

Answers (12)

Volodymyr Zakharov
Volodymyr Zakharov

Reputation: 93

for android
        new GraphRequest(
                facebookToken,
                String.format("/%s/photos", idAlbum),
                parameters,
                HttpMethod.GET,
                response -> {
                    try {
                        JSONArray photoArray = response.getJSONObject().getJSONArray("data");
                        photosAlbumAfterPagination = response.getJSONObject().getJSONObject("paging").getJSONObject("cursors").getString("after");
                        Gson gson = new Gson();
                        Type type = new TypeToken<List<FacebookPhotoResponse>>() {
                        }.getType();
                        List<FacebookPhotoResponse> list = gson.fromJson(photoArray.toString(), type);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
        ).executeAsync();

Upvotes: -1

balkaran singh
balkaran singh

Reputation: 2786

for Swift 5

first get albums id like this

func getAlbumsData()
{

        GraphRequest.init(graphPath: "me", parameters: ["fields":"id,name,albums{name,picture}"]).start(completionHandler: { (connection, userResult, error) in

            if error != nil {

                print("error occured \(String(describing: error?.localizedDescription))")
            }
            else if userResult != nil {
                print("Login with FB is success")
                print()



                let fbResult:[String:AnyObject] = userResult as! [String : AnyObject]

                self.albumsPhotos = (fbResult["albums"] as! [String:AnyObject])["data"] as? [[String:AnyObject]]
                self.tblFbAlbums.reloadData()




            }
        })
    }

then get albums image with this method

func fetchalbumsPhotosWithID() {


        let graphRequest : GraphRequest  = GraphRequest(graphPath: "\(album_Id)/photos", parameters: ["fields": "source"] )

        graphRequest.start(completionHandler: { (connection, result, error) -> Void in

            if ((error) != nil)
            {
                // Process error
                print("Error: \(error)")
            }
            else
            {
                print("fetched user: \(result)")

                let data =  result as! [String:Any]


            }
        })

    }

album_Id is a number you get from getAlbumsData()

Upvotes: 1

Savan Kaneriya
Savan Kaneriya

Reputation: 79

request('GET', '/me/albums?fields=id,name,cover_photo,photos{images{source}},description')

it will show the albums with description and photos with different resolution of that album.
This will need access token

Upvotes: 1

Nikhil Prajapati
Nikhil Prajapati

Reputation: 1

loginButton.setReadPermissions("public_profile", "email","user_friends","user_photos");

this permistion required

Upvotes: 0

Rohan Dave
Rohan Dave

Reputation: 261

GETTING ALBUM_ID

    if((FBSDKAccessToken.current()) != nil)
    {
        FBSDKGraphRequest(graphPath: "me/albums", parameters: ["fields" : "id"], httpMethod: "GET").start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil)
            {
                let data:[String:AnyObject] = result as! [String : AnyObject]
                self.arrdata = data["data"]?.value(forKey: "id") as! [String ]
            }
        })
    }

with above code you will get album_Id and then with that id we can get image like this : GETTING IMAGES FROM ALBUM_ID

    FBSDKGraphRequest(graphPath: "\(album_Id)/photos", parameters: ["fields": "source"], httpMethod: "GET").start(completionHandler: { (connection, result1, error) -> Void in
       if (error == nil)
       {
           let data1:[String:AnyObject] = result1 as! [String : AnyObject]
           let arrdata:[String] = data1["data"]?.value(forKey: "source") as! [String ]
           for item in arrdata
           {
               let url = NSURL(string: item )
               let imageData = NSData(contentsOf: url! as URL)
               let image = UIImage(data: imageData! as Data)
               self.imgArr.append(image!)
           }
        }
     })

Upvotes: 1

M A Russel
M A Russel

Reputation: 1557

to get the album list type :

me?fields=albums

after that type :

album_id/photos?fields=source

to get the photos of that particular album

Upvotes: 1

pashaplus
pashaplus

Reputation: 3706

Each album is a object like user object in facebook, to get photos in that particular album you have to request some thing like below

http://graph.facebook.com/{ALBUM_ID}?fields=photos&access_token="xxxxx"

Upvotes: 2

Max
Max

Reputation: 1001

For photo urls:

  1. Ensure that you are an Admin of the Facebook Page.

  2. go to : http://developers.facebook.com/tools/explorer

  3. In the API Navigator, you can see "/me" will bring up the basic information of yourself.

  4. Try typing in "/me/accounts" to see if you can see anything. It should give you an error.

  5. Click on "Get Access Token"

  6. a window will pop-up. Navigate to "Extended Permissions"

  7. Select "manage_pages"

  8. Click "Get Access Token"

  9. Now try "/me/accounts" again. You should see a list of Groups inside the viewing window.

  10. Select the Page you want, and click on the "id" field

  11. Next, on the left window, you can see "Node: " and a + sign. Click on the + sign to see what are the options you have.

  12. Click on the + sign and scroll down to "connections" and select "Albums"

  13. The child-level, select "Photos"

  14. The "Photos" child-level, select "source"

  15. Now click "Submit" on the right hand side. You will see a JSON returned with the url of all the photos in your Facebook Page.

  16. Copy the URL - https://graph.facebook.com/?fields=albums.fields(photos.fields(source)) and plug it into your browser. You should see a JSON of all your photos.

Upvotes: 2

Sergio L&#243;pez
Sergio L&#243;pez

Reputation: 973

Actually there is a better way to achieve this, nesting the request

Passing albums as a parameter, and then filter the fields from the connection photos that you want to, for example here I got just everything I need from albums and photos, also this results can be limited

me?fields=albums.fields(id,name,cover_photo,photos.fields(name,picture,source))

Upvotes: 29

user743489
user743489

Reputation:

Another possible solution is getting album ids first and then iterate over them making this API call:

<ALBUM-ID>/photos?fields=name,source,id

I tested this in graph explorer and it retrieved a reasonable (and readable) json object

Upvotes: 3

user1031721
user1031721

Reputation:

Why is the data unnecessary? Did it return something like this:

{
   "data": [
      {
         "id": "ID",
         "from": {
            "name": "Hadrian de Oliveira",
            "id": "100000238267321"
         },
         "name": "Cover Photos",
         "link": "https://www.facebook.com/album.php?fbid=FBID&id=ID&aid=AID",
         "cover_photo": "ID",
         "privacy": "everyone",
         "count": 2,
         "type": "normal",
         "created_time": "2011-10-06T01:31:24+0000",
         "updated_time": "2012-02-22T17:29:50+0000",
         "can_upload": false
      },

?

Upvotes: 0

Juicy Scripter
Juicy Scripter

Reputation: 25918

You may only use fields with properties that exists for objects.

By issuing GET request to next URL you'll get list of albums ids only:

https://graph.facebook.com/me/albums?fields=id&access_token=...

Same can be achieved by running next FQL query on album table:

SELECT aid FROM album WHERE owner=me()

Actually albums connection of user doesn't really contain list of photo objects but album (which have photos connection). So to get photos owned by user you'll need iterate over all of his object and getting photos for every album. Again you may use fields argument to limit resulting data. This can be done faster if using batch requests.

Or With FQL it may be done like this (two tables photo and album involved):

SELECT pid FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner=me())

Upvotes: 10

Related Questions