2
votes
$client = new Client();
$url = 'api-url';

$request = $client->post($url, [
    'headers' => ['Content-Type' => 'application/json'],
    'json' => ['token' => 'foo']
]);

return $request;

And I get back 502 Bad Gateway and Resource interpreted as Document but transferred with MIME type application/json

I need to make a POST request with some json. How can I do that with Guzzle in Laravel?

3

3 Answers

10
votes

Give it a try

$response = $client->post('http://api.example.com', [
    'json' => [
       'key' => 'value'
     ]
]);

dd($response->getBody()->getContents());
1
votes

Take a look..

$client = new Client();

$url = 'api-url';

$headers = array('Content-Type: application/json');

$data = array('json' => array('token' => 'foo'));

$request = new Request("POST", $url, $headers, json_encode($data));

$response = $client->send($request, ['timeout' => 10]);

$data = $response->getBody()->getContents();
1
votes

you can also try this solution. that is working on my end. I am using Laravel 5.7.

This is an easy solution of Make a POST Request from PHP With Guzzle

   function callThirdPartyPostAPI( $url,$postField  )
   {
     $client = new Client();
     $response = $client->post($url , [
        //'debug' => TRUE,
        'form_params' => $postField,
        'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        ]
     ]);
    return $body = $response->getBody();
  }

For Use this method

    $query['schoolCode'] =$req->schoolCode;
    $query['token']=rand(19999,99999);
    $query['cid'] =$req->cid;
    $query['examId'] =$req->examId;
    $query['userId'] =$req->userId;

    $tURL = "https://www.XXXXXXXXXX/tabulation/update";

    $response = callThirdPartyPostAPI($tURL,$query);

    if(  json_decode($response,true)['status'] )
    {
        return success(["data"=>json_decode($response,true)['data']]);
    }