[Python] Why do i keep getting bad request when trying to send GraphApi batch request

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

  1. Stack

    Stack Membro Participativo

    My goal is to send a batch request of with the conversation id so I could get all the conversations that the user have in their inbox , I tried to read the docs many times but I find their docs difficult to understand, they have different type of batch request, I tried to use the sample batch request but I'm a little bit confused, I think the problem is with the way im jsonifying the requests.

    batch_request.append({
    "method": "GET",
    "relative_url": f"{conversation_id}?fields=messages{{id,created_time}}"
    })

    batch_json = json.dumps(batch_request)


    has anyone succeeded sending a batch request and can help me make this work?

    Im simply trying to get many conversation by conversation_id but i keep getting bad request...

    @staticmethod
    def get_inbox_messages(ig_user_id: str, access_token: str):
    try:
    # Get list of conversations
    url = (
    f"https://graph.instagram.com/v17.0/me/conversations?platform=instagram"
    f"&access_token={access_token}"
    )

    logger.info(f"Fetching inbox messages from: {url.replace(access_token, 'TOKEN_HIDDEN')}")
    response = requests.get(url)
    response.raise_for_status()
    conversations_data = response.json()

    if 'error' in conversations_data:
    raise ValueError(f"Instagram API error: {conversations_data['error'].get('message', 'Unknown error')}")

    # Extract conversation IDs
    conversation_ids = [conversation.get('id') for conversation in conversations_data.get('data', [])]

    # Prepare batch request to fetch conversation details including messages for all conversations
    batch_request = []
    for conversation_id in conversation_ids:
    # For each conversation, get the messages
    batch_request.append({
    "method": "GET",
    "relative_url": f"{conversation_id}?fields=messages{{id,created_time}}"
    })

    # Convert the batch request list to JSON
    batch_json = json.dumps(batch_request)

    # Prepare the batch request
    batch_url = "https://graph.facebook.com" # Note: this is the correct endpoint for batch requests

    params = {
    'batch': batch_json,
    'include_headers': 'false',
    'access_token': access_token
    }

    # Make the batch request
    batch_response = requests.post(batch_url, params=params)
    print("Batch response:")
    print(batch_response.text)
    batch_response.raise_for_status()

    # Process batch response
    batch_data = batch_response.json()

    # Continue processing the batch data...
    return batch_data

    except Exception as e:
    logger.error(f"Error getting inbox messages: {str(e)}")
    raise

    Continue reading...

Compartilhe esta Página