Laravel - Guzzle not returning any data even though URL is correct

4k Views Asked by At

I am trying to return the JSON data from a third party API - http://postcodes.io/. I currently have in my controller:

 $client = new Client();
    $request = $client
        ->get('https://api.postcodes.io/postcodes/'.Input::get('postcode'));

    $statusCode = $request->getStatusCode();

    if ($statusCode >= 200 && $statusCode < 300) 
    {
       $json = Response::json($request); // Returns JSON decoded array of data.
    }

I'm trying to return the postcode information as such:

https://api.postcodes.io/postcodes/OX495NU

If I dd($request), then this is printed out, with a 200 status code but with no data associated with it:

JsonResponse {#245 ▼
  #jsonOptions: 0
  #data: "{}"
  #callback: null
  #encodingOptions: 15
  +headers: ResponseHeaderBag {#242 ▶}
  #content: "{}"
  #version: "1.0"
  #statusCode: 200
  #statusText: "OK"
  #charset: null
}

Any help why this is happening would be greatly appreciated.

1

There are 1 best solutions below

6
On BEST ANSWER

What you are seeing is the raw response back from Guzzle and it needs to be formatted. A simple way is $response->getBody();.

Think of this like a collection in Laravel. When you get the data back, it is in a collection with a bunch of extra data that may be useful but if you only want the data you would run $user->toJson(); For Guzzle, if you want to strip out all the extra curl data, the protocol info, the headers, etc, you would want only the payload, or body. $response->getBody();