James James -4 years ago 115
PHP Question

Learning how to access data from an API using Guzzle

I'm building a new application that requires the use of an API, in particular one that uses OAuth, but to begin with I'm trying to just use a simple API to wrap my head around how to use one in an application as I've never used an API before.

I'm running a fresh Laravel 5.1 project on my localhost with the

library installed.

Following the instructions from the Guzzle documentation, I believe I have set this up right, but I can't make heads or tales of the response I am getting.

The API I am trying to use is http://freegeoip.net/ and the format for making a request is

I've set up a page where I can type in an IP address and submit this, to which it is then run by the following function in my controller:

public function retrieve(Request $request)
$url = "http://freegeoip.net/json/" . $request->ipaddress;
$client = new Client();
$response = $client->request('GET', $url);

My routes and everything are set up correctly, and I am referencing Guzzle at the top of my controller with:

use GuzzleHttp\Client;

But the response I get from
doesn't make any sense to me or give any hints as to how I could get any information from it.

This is what the

Response {#195 ▼
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:8 [▶]
-headerLines: array:8 [▶]
-protocol: "1.1"
-stream: Stream {#186 ▶}

But when I run the equivalent URL through my browser I get

{"ip":"202.21.xxx.xxx","country_code":"NZ","country_name":"New Zealand","region_code":"WGN","region_name":"Wellington","city":"Wellington","zip_code":"6011","time_zone":"Pacific/Auckland","latitude":-41.283,"longitude":174.784,"metro_code":0}

Can anyone help out with what I'm doing wrong or point to some good resources on how to get started using APIs with Laravel. There's a lot on how to build a Laravel API but not how to access one from Laravel.

Answer Source

Well after a huge amount of digging, it turns out I was simply missing json_decode().

The request works fine when I run it like:

public function retrieve(Request $request)
        $url = "http://freegeoip.net/json/" . $request->ipaddress;
        $client = new Client();
        $response = $client->request('GET', $url);

Answering this for anyone else who has trouble like this in the future :).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download