2

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 Guzzle 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 freegeoip.net/{format}/{IP_or_hostname}.

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);
        dd($response);
    }

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 dd($response); 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 dd($response) outputs

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.

1 Answer 1

4

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);
        dd(json_decode($response->getBody()));
    }

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.