How to Install guzzle and use a third party API in laravel

You’re not alone. At any given moment, somewhere in the world someone struggles with the same software design problems you have. You know you don’t want to reinvent the wheel (or worse, a flat tire), so you look to Design Patterns – the lessons learned by those who’ve faced the same problems. With Design Patterns, you get to take advantage of the best practices and experience of others, so that you can spend your time on … something else. Something more challenging. Something more complex. Something more fun.

Head First Design Patterns – A Brain-Friendly Guide – by O’Reilly Media

Today I was implementing an IP location API in my college project. Of course, it is a Laravel project. I was thinking about making some cURL requests and processing the output. Oh… boy I found guzzle, a beautiful wheel that I never need to reinvent, also guzzle is super friendly with Laravel, and it made my day… Let’s see guzzle in action.

  • First, we need to install guzzle in our Laravel project, refer to my previous post on installing a package in Laravel via composer. anyway, make sure you install the correct guzzlehttp/guzzle Package
  • Then we need to use the guzzle namespace in out project like this
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
  • Then use the guzzle package
$client = new Client(); 
$result = $client->post('your-request-uri', [
    'form_params' => [
        'sample-form-data' => 'value'
    ]
]);

Let’s see how can we use the free jioip location API, it is a free API that does not require any API keys, so no registrations and all. When we query the API like this,

http://freegeoip.net/json/shobi.

we get a JSON output like following,

{"ip":"2400:cb00:2048:1::681b:ab89",
"country_code":"US",
"country_name":"United States",
"region_code":"",
"region_name":"",
"city":"",
"zip_code":"",
"time_zone":"",
"latitude":37.751,
"longitude":-97.822,
"metro_code":0}

it also possible to get result’s back in XML format. But for now, we’ll stick with JSON. So our code will look like this

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

$client = new Client();
$query_string="http://freegeoip.net/json/shobi.in"
$iplocation = $client->get($query_string); //this will be guzzle object

$iplocation_jsoned=json_decode((string)$client->get($query_string)->getBody()); //this will be a json object

var_dump($iplocation); //this will dump the result object
dd($iplocation_jsoned); //this will dump the json object

Let me know about your experience with guzzle. Happy coding…

Programmer, Hacker, Trainor, Speaker, and Blogger. Opensource Lover. Built LeHacker.com.

Leave a reply:

Your email address will not be published.

Site Footer