Home > Back-end >  Laravel 7 to an external API Response::setContent() must be of the type string or null
Laravel 7 to an external API Response::setContent() must be of the type string or null

Time:01-21

i have problem with HTTP API post request using laravel 7 i tried with with postman is work fine

this my code :

       $response = Http::withOptions([
                    'debug' => true,
                ])->asForm()->withToken('mybearertoken')->post('theurl',[
                    'tracking' => $getcolisdetails->ref_order,
                    'state_id' => $newStatus ,
                    'content'  => $content
                                ]);
                                $response->json() ;

the response that i get :

"Argument 1 passed to Symfony\\Component\\HttpFoundation\\Response::setContent() must be of the type string or null, object given

Note : i use laravel 7 , PHP 7.4 , guzzlehttp/guzzle": "^6.3

CodePudding user response:

Get the JSON content as a string, decode it, and set it as response content.

$response = Http::withOptions([
    'debug' => true,
])->asForm()->withToken('mybearertoken')->post('theurl',[
    'tracking' => $getcolisdetails->ref_order,
    'state_id' => $newStatus ,
    'content'  => $content
]);

$content = $response->getContent();
response(json_decode($content), 200)->header('Content-Type', 'application/json');

CodePudding user response:

the solution that i found using guzzle :

try {
    $response = (new Client([
      'debug' => true,
    ]))->post('theurl', [
      'headers' => [
          'Authorization' => 'Bearer mybearertoken',
      ],
      'json' => [
          'tracking' => $getcolisdetails->ref_order,
          'state_id' => $newStatus,
          'content'  => $content
      ],
    ]);
    $data = $response->getBody()->getContents();
  } catch (ClientException $exception) {
    dd($exception->getResponse()->getBody()->getContents());
  }
  • Related