Laravel 9 Guzzle HTTP Client Example
If i talk about the primordial era of web development, then that time we used to rely on cURL for the similar task. But as time went by, there were many improvements. Out of that development, Guzzle is one, i would talk about Guzzle Http client today.
In this tutorial, we will look at how to create the Guzzle Http Client in Laravel and learn to send the HTTP requests.
Install Guzzle Http Package
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. It provides the simple yet powerful interface for sending POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc…
Ideally, to send HTTP requests, we require to install the guzzlehttp/guzzle package using Composer package manager.
composer require guzzlehttp/guzzle
The best thing about Guzzle 6, which attracts my attention towards it, you can simultaneously make synchronous and asynchronous requests from the same interface. Likewise, this offers boundless configurations to play along with http requests.
Guzzle HTTP Client CRUD Requests
Information provided below can give you a rough idea about making GET, POST, PUT, and DELETE requests with Guzzle 6 HTTP Client library in laravel.
Guzzle GET Request
public function guzzleGet()
{
$client = new GuzzleHttpClient();
$request = $client->get('http://testmyapi.com');
$response = $request->getBody();
dd($response);
}
Guzzle POST Request
public function guzzlePost()
{
$client = new GuzzleHttpClient();
$url = "http://testmyapi.com/api/blog";
$myBody['name'] = "Demo";
$request = $client->post($url, ['body'=>$myBody]);
$response = $request->send();
dd($response);
}
Guzzle PUT Request
public function guzzlePut()
{
$client = new GuzzleHttpClient();
$url = "http://testmyapi.com/api/blog/1";
$myBody['name'] = "Demo";
$request = $client->put($url, ['body'=>$myBody]);
$response = $request->send();
dd($response);
}
Guzzle DELETE Request
public function guzzleDelete()
{
$client = new GuzzleHttpClient();
$url = "http://testmyapi.com/api/blog/1";
$request = $client->delete($url);
$response = $request->send();
dd($response);
}
