Dhaval
Dhaval

Reputation: 1436

GuzzleHttp - 400 error exception but with curl working perfectly

I'm calling a third party rest API with GuzzleHttp but it gives me a 400 Bad Request every time.

Development environment:

  1. Laravel / PHP framework
  2. Guzzle version in composer.json file - "guzzlehttp/guzzle": "^6.3"
  3. Ubuntu 16.04 LTS

Guzzle call to URL with data:

try{

$client = new \GuzzleHttp\Client();

$res= $client->request('post',
            env('FLIGHT_API').'FlightSearch',
            ['headers' => ['Content-Type' => 'application/json' , 'Accept' => 'application/json'],'form_params' => $body]);

}catch (ClientException $e){



        $response['status'] = false;
        $response['message'] = $e->getMessage().$e->getCode();

        return $response;

    }

Guzzle response:

{
"status": false,
"message": "Client error: `POST http://stagingapi.trip.com/Search` resulted in a `400 Bad Request` response:\n\ufeff<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3 (truncated...)\n400"
}

So, at last I tried same API with curl and it's working perfect and get result.

Curl code with URL and data:

$curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => env('FLIGHT_API').'FlightSearch',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($body),
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/json",
                "Accept: application/json"
            ),
        ));

        $response = curl_exec($curl);
        //return $response;
        $err = curl_error($curl);

        curl_close($curl);

        if($response){

            return json_decode($response , true);

        }

        return $err;

How can I determine where the fault is?

Upvotes: 1

Views: 2641

Answers (1)

Alexey Shokov
Alexey Shokov

Reputation: 5030

You need

'json' => $body

instead of

'form_params' => $body

Upvotes: 5

Related Questions