Content Overview
Getting Started
In this tutorial, we'll be learning how to consume external/third party API using Guzzle in Laravel 5 and Laravel 6.
What is Guzzle Client?
Guzzle is a PHP HTTP client that makes it easy to send or retrieve HTTP requests.
- It provides the interface where you can send both Synchronous and Asynchronous requests
- It uses PSR-7 interfaces for streams, requests, and responses.
- The middleware system allows you to augment and compose client behavior.
I am assuming you have already set up the laravel project. if not, you can follow below link
Install Laravel 5 in Ubuntu 16.04 and 18.04
Also, make sure the composer is installed in your system.
Install Guzzle Client in Laravel Project
To Install guzzle enter the following command in your terminal.
composer require guzzle/guzzle:~3.9
Method 1. Consume API from Route
To call the external API from the laravel route. copy and paste the following code in your web.php
#routes/web.php
<?php
use GuzzleHttp\Client;
Route::get('/json-api', function() {
$client = new Client();
$response = $client->request('GET', 'https://desertebs.com/api/dummy/posts');
$statusCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
return $body;
});
Import the guzzle client, create a new instance and make the request with request function. The first parameter is GET and the second one is the URL.
$response->getStatusCode
will return the HTTP Status Code
$response->getBody()->getContents()
will return the contents
Method 2. Consume API from Controller
To call the third-party API from the controller, First, we need to create a route. To do so copy and paste the following code into your web.php
file.
#routes/web.php
Route::get('json-api', 'ApiController@index');
Next, Create ApiController
. To do so navigate to your project directory and enter the following command in your terminal.
php artisan make:controller ApiController
This command will create a new ApiController file in app/Http/Controllers
directory. Next, create index function and write the logic to consume the API
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
class ApiController extends Controller
{
public function index()
{
$client = new Client();
$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/todos/1');
$statusCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
return $body;
}
}
What we did here is:
use GuzzleHttp\Client
: import Guzzle Client.
new Client();
Create a new instance of guzzle client
Next, call request()
method. I have passed two parameters. First is GET for making get request and the second parameter is URL.
getStatusCode()
: Get the HTTP status code.
getBody()->getContents()
is used to return the contents.
Method 3. Register the API with the Service Container
In this section, we'll be using the singleton method to consume the API.
Singleton: It allows to use one instance of itself.
We'll use the singleton with the laravel service container that should only resolve one time. once resolved the same instance will be returned on the subsequent calls into the container.
Let's get started.
Open and edit your AppServiceProvider.php
which will be located in app/Providers
directory and paste the following code.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$baseUrl = env('DESERT_EBS_BASE_URL');
$this->app->singleton('GuzzleHttp\Client', function($api) use ($baseUrl) {
return new Client([
'base_uri' => $baseUrl,
]);
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
$baseUrl = env('DESERT_EBS_BASE_URL')
base URL which I have put in my .env
Open your .env
file and paste the following code
#.env
DESERT_EBS_BASE_URL=https://desertebs.com/api
Note: If you are using php artisan serve
command to run your project. you need to restart to load the .env
file
Next, Create a helper class which will interact with the endpoint. To do so create a new file under app directory and paste the following code.
#app/Util/Post.php
<?php
namespace App\Util;
use GuzzleHttp\Client;
class Post
{
protected $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function all()
{
return $this->endpointRequest('/dummy/posts');
}
public function findById($id)
{
return $this->endpointRequest('/dummy/post/'.$id);
}
public function endpointRequest($url)
{
try {
$response = $this->client->request('GET', $url);
} catch (\Exception $e) {
return [];
}
return $this->response_handler($response->getBody()->getContents());
}
public function response_handler($response)
{
if ($response) {
return json_decode($response);
}
return [];
}
}
Next, Import this helper class into your controller use App\Util\Post
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Util\Post;
class ApiController extends Controller
{
protected $post;
public function __construct(Post $post)
{
$this->post = $post;
}
public function index()
{
// Get all the post
$posts = $this->post->all();
return view('someview', compact('posts'));
}
public function show($id)
{
$post = $this->post->findById($id);
return view('someview', compact('post'));
}
}
You can dd($posts)
to check the response.
Recommended Posts
Laravel social login with Facebook
Laravel social auth login with Google
Install Laravel 7 on ubuntu 18.04