Search code examples
phpguzzlesendbird

Sendbird/Guzzle returns "The request body is an invalid JSON"


I got an error message when trying to send a request to SendBird API using Guzzle.

Error message

"message": "Client error: `POST https://api.sendbird.com/v3/group_channels` resulted in a `400 BAD REQUEST` response:\n{\"message\":\"Not valid JSON body.\",\"code\":400403,\"error\":true}\n",
    "exception": "GuzzleHttp\\Exception\\ClientException",

My code

$client = new Client([
                        'headers' => [
                            'Accept' => 'application/json',
                            'Authorization' => 'Bearer XXXXX',
                            'Content-Type' => 'application/json',
                        ],
                    ]); 
                    $response = $client->post('https://api.sendbird.com/v3/group_channels', [
                        'form_params' => [
                            'user_ids' => [$user_id_1,$user_id_2],
                            'operator_ids' => [$user_id_1,$user_id_2]
                        ]
                    ]);

Solution

  • You're using form_params, use json instead like so:

    $response = $client->post('https://api.sendbird.com/v3/group_channels', [
        'json' => [
            'user_ids' => [$user_id_1, $user_id_2],
            'operator_ids' => [$user_id_1, $user_id_2]
        ]
    ]);