0

I'm trying to use the Facebook Graph API with Python to access user profile data, posts, and photos. Despite generating a valid access token through the Graph API Explorer, I keep getting the error:

C:\Users\ferre\Projects\AutomateEverithingPython\AcessingAPIs>python exercio2.py 🕒 Iniciando execução em 2025-07-10 16:08:02

🔍 Obtendo perfil do usuário... ❌ Erro ao obter perfil: Unsupported get request. Object with ID 'me' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api

📝 Obtendo postagens... ❌ Erro ao obter postagens: Unsupported get request. Object with ID 'me' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api

🖼️ Obtendo fotos... ❌ Erro ao obter fotos: Unsupported get request. Object with ID 'me' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api

🏁 Execução concluída!

C:\Users\ferre\Projects\AutomateEverithingPython\AcessingAPIs>

here's my current code:

import requests
import json
import facebook
from datetime import datetime

# Configurações
ACCESS_TOKEN = "EAA....Removed for security question"  # Substitua pelo novo token
BASE_URL = "https://graph.facebook.com/v13.0"

def get_user_profile():
    """Obtém informações básicas do perfil"""
    try:
        url = f"{BASE_URL}/me?fields=id,name,email&access_token={ACCESS_TOKEN}"
        response = requests.get(url)
        data = json.loads(response.text)
        
        if 'error' in data:
            print(f"❌ Erro ao obter perfil: {data['error']['message']}")
            return None
        return data
    except Exception as e:
        print(f"❌ Erro inesperado: {str(e)}")
        return None

def get_user_posts():
    """Obtém as postagens do usuário"""
    try:
        url = f"{BASE_URL}/me/posts?fields=id,message,created_time&access_token={ACCESS_TOKEN}"
        response = requests.get(url)
        data = json.loads(response.text)
        
        if 'error' in data:
            print(f"❌ Erro ao obter postagens: {data['error']['message']}")
            return None
        return data
    except Exception as e:
        print(f"❌ Erro inesperado: {str(e)}")
        return None

def get_user_photos():
    """Obtém as fotos do usuário"""
    try:
        url = f"{BASE_URL}/me/photos?fields=id,images&access_token={ACCESS_TOKEN}"
        response = requests.get(url)
        data = json.loads(response.text)
        
        if 'error' in data:
            print(f"❌ Erro ao obter fotos: {data['error']['message']}")
            return None
        return data
    except Exception as e:
        print(f"❌ Erro inesperado: {str(e)}")
        return None

def download_photo(photo_url, filename):
    """Baixa uma foto e salva localmente"""
    try:
        response = requests.get(photo_url)
        with open(filename, 'wb') as file:
            file.write(response.content)
        print(f"✅ Foto salva como {filename}")
    except Exception as e:
        print(f"❌ Erro ao baixar foto: {str(e)}")

if __name__ == "__main__":
    print(f"🕒 Iniciando execução em {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 1. Obter perfil do usuário
    print("\n🔍 Obtendo perfil do usuário...")
    profile = get_user_profile()
    if profile:
        print("👤 Perfil do usuário:")
        print(f"ID: {profile.get('id')}")
        print(f"Nome: {profile.get('name')}")
        print(f"Email: {profile.get('email', 'Não disponível')}")
    
    # 2. Obter postagens
    print("\n📝 Obtendo postagens...")
    posts = get_user_posts()
    if posts and 'data' in posts:
        print(f"📚 Total de postagens: {len(posts['data'])}")
        for i, post in enumerate(posts['data'][:3], 1):  # Mostra apenas 3 postagens
            print(f"\n📌 Postagem {i}:")
            print(f"ID: {post.get('id')}")
            print(f"Data: {post.get('created_time')}")
            print(f"Mensagem: {post.get('message', 'Sem texto')[:50]}...")
    
    # 3. Obter fotos
    print("\n🖼️ Obtendo fotos...")
    photos = get_user_photos()
    if photos and 'data' in photos:
        print(f"📸 Total de fotos: {len(photos['data'])}")
        if photos['data']:
            first_photo = photos['data'][0]
            print("\n📷 Primeira foto:")
            print(f"ID: {first_photo.get('id')}")
            print(f"URL da imagem: {first_photo['images'][0]['source'][:50]}...")
            
            # 4. Baixar uma foto
            print("\n⬇️ Baixando foto...")
            photo_url = first_photo['images'][0]['source']
            download_photo(photo_url, "foto_facebook.jpg")
    
    print("\n🏁 Execução concluída!")

Why does the token work in Graph API Explorer but not in my Python code?

Are there additional app settings I need to configure?

Could this be related to token expiration? (Though it fails immediately with new tokens)

Is there a way to debug the token validation process?

I still don't know how to use Facebook's developer resource properly, can you help me? enter image description here

5
  • Graph API Explore can work because you are already logged in and it knows what to use in place of /me Commented Jul 11 at 2:30
  • shorter: data = response.json() Commented Jul 11 at 2:43
  • maybe simpler requests.get(url, params={"fields": ["id", "name","email"], "access_token": ACCESS_TOKEN}) Commented Jul 11 at 2:45
  • your code works for me with token generated in Graph API Explorer (I used app only with Permissions: public_profile so I get my name but emply list for photos and posts) Commented Jul 11 at 2:50
  • It's strange when I can't add permissions; only 1 permission appears for me to add, the others I type but are not inserted. And when I try to create a token, I receive the message that is created in a new tab of my browser: Resource unavailable. As we are updating additional details for this application, Facebook Login is currently unavailable for it. Please try again later. Commented Jul 16 at 17:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.