Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

caercam's avatar

Retrieve HTTP POST request response body

I'm sending data to an API using this code:

$request = Http::withHeaders($this->headers())
            ->post($url, $fields);

$this->headers() returns an array with the API key, $fields is an array of fields to send to the API. When I send the request using an HTTP client like Postman or RESTClient I get a JSON response when the request fails; but when I send the request in Laravel, I only end with an empty response body. I tried fiddling with the headers, sendind Accept and Content-Type headers, no difference.

What am I missing? Why is the response body empty when it shouldn't?

0 likes
7 replies
tykus's avatar

Try specifying that you accept application/json using the acceptJson() convenience method:

$request = Http::acceptJson()
    ->withHeaders($this->headers())
    ->post($url, $fields);
caercam's avatar

Just tried, still getting an empty response body.

Shaden's avatar

can you share a dd() of $this->headers() output.

caercam's avatar
array:3 [
  "Accept" => "application/json"
  "Content-type" => "application/json"
  "X-Key" => "SECRET_KEY"
]
Randy_Johnson's avatar

$request = Http::withHeaders($this->headers()) ->post($url, $fields);

Newbie response but try $response[0] and fiddle a bit. Hope the answer finds you.

caercam's avatar
caercam
OP
Best Answer
Level 1

OK, solved it. Don't ask me why, but using this makes it work:

Http::withHeaders($this->headers())
    ->withBody(json_encode($fields), 'application/json')
    ->post($url);

No idea why manually filling the request body with JSON instead of using Http::post($url, ['foo' => 'bar']) has an influence on the response body, but still, seems to work.

John Subut's avatar

To see the response body I use the printf()

printf(Http::withHeaders($this->headers())
            ->post($url, $fields));

Please or to participate in this conversation.