In this tutorial, I will let you know the use of Guzzle HTTP client and how to send request to server from Laravel application using Guzzle HTTP client and get the HTTP response.
It's very easy to send an HTTP request using Guzzle with a simple interface that you do with the cURL.
You can use Guzzle to make authenticable request.
In this example, I will show you how to get the user details registered with "github" by their credentials.
InstallationFirst, I will have to install the Guzzle through Composer by running following command :
composer require guzzlehttp/guzzle:~6.0
Now you can use the GuzzleHttp\Client
class in your PHP application to make a request on server.
Sending GET request is very common form of HTTP requests. Normally you open the any website in the browser then the HTML pages of the website is downloaded by HTTP GET request.
Example 1 :
- $client = new \GuzzleHttp\Client();
- // Create a request
- $request = $client->get('example.com');
- // Get the actual response without headers
- $response = $request->getBody();
- return $response;
- $client = new \GuzzleHttp\Client();
- // Create a request with auth credentials
- $request = $client->get('https://api.github.com/user',['auth'=>['username','password']]);
- // Get the actual response without headers
- $response = $request->getBody();
- return $response;
POST request is basically used to submit form data to a website, There can be number of reasons to use POST request.
- $client = new \GuzzleHttp\Client();
- $body['name'] = "Testing";
- $url = "http://my-domain.com/api/v1/post";
- $response = $client->createRequest("POST", $url, ['body'=>$body]);
- $response = $client->send($response);
- return $response;
You can also send the PUT/DELETE/PATCH request in following way :
GET: $client->get('http://my-domain.com/get', [/** options **/]) POST: $client->post('http://my-domain.com/post', [/** options **/]) HEAD: $client->head('http://my-domain.com/get', [/** options **/]) PUT: $client->put('http://my-domain.com/put', [/** options **/]) DELETE: $client->delete('http://my-domain.com/delete', [/** options **/]) OPTIONS: $client->options('http://my-domain.com/get', [/** options **/]) PATCH: $client->patch('http://my-domain.com/put', [/** options **/])