[Python] Facebook Graph API - "Invalid OAuth access token" error despite using valid token

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    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? [​IMG]

    Continue reading...

Compartilhe esta Página