Problem with altering the response object (body and content type)

Hello,

I’m trying to pass on the response of an external API call (via Guzzle) but I’m not quite getting what I want:

// here setting the body overwrites the content type I just set. (back to text/html)
   $gResponse = $client->request('GET', 'datas/' . $id);
   $response = $response->withHeader('Content-type', 'application/json');
   $response = $response->getBody()->write($gResponse->getBody());

// here I get an error: "Call to a member function withHeader() on integer" 
// (don't know what it means)
   $gResponse = $client->request('GET', 'datas/' . $id);
   $response = $response->getBody()->write($gResponse->getBody());
   $response = $response->withHeader('Content-type', 'application/json');

How would I get the body form the gResponse into my own response object and that with the content type header that I want (application/json)? Why does $response->getBody()->write(‘xyz’); change the content type?

Also while I’m already here: Is directly passing on the response from an external API call a good Idea? Like:

$gResponse = $client->request('GET', 'datas/' . $id);
return gResponse;

$response->getBody()

returns a StreamInterface. Calling

write

on a StreamInterface returns the number of bytes write, so after

$response = $response->getBody()->write($gResponse->getBody());

$resonse is an int.

Try removing the assignment, so just

$response->getBody()->write($gResponse->getBody());

1 Like

Yes, you are right. I mixed things up here (response->withBody()). Thanks for your help.