Laravel Guzzle Tutorial With GET & POST Examples

The Guzzle package is the answer to all HTTP request use-cases. Whether it be a GET, POST, or others, Guzzle has your back. In today’s era, there is a rapidly growing consumption of APIs and web services.

Guzzle is what is more commonly known as an HTTP Client for PHP. It has vast flexibility, with the ability to send payloads to specific endpoints, execute DELETE method requests on API’s and so much more.

As you are probably aware, you can use Guzzle without any framework. But, in this tutorial, each example has been executed in a Laravel framework environment.

In this article, we will explore examples of each of the following methods

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH

Prerequisites

This tutorial assumes that the following requirements have been met

  • PHP 5.5+ Installed
  • A working webserver with Laravel installed (If the intention is to use it with Laravel!)
  • Composer installed – if you need to install Composer check out my guide on installing and using Composer here.
  • A simulating restful API service or your own REST-API, for this tutorial, the great web-tool https://reqres.in/ will be used to simulate a real API.

Installing Guzzle for Laravel

First of all, we need to instruct Composer to install the Guzzle package.

With the CLI, navigate to the root directory of your project and execute the following command

composer require guzzlehttp/guzzle:~6.0

During installation, there will be some type of response in the console as shown below

composer install guzzle

Now that’s taken care of, we can move on to the working tutorial, let’s go!

Important Note: With any of the following examples, please ensure you’ve imported the Guzzle class with a use statement –

use GuzzleHttp\Client;

The Guzzle HTTP Client Response

I thought it was worth pointing out that this response variable holds a lot of helpful information when working with HTTP requests, so it’s something to keep in mind.

With any type of HTTP request executed with Guzzle, there will be an HTTP response returned. if we look at the following code –

$client = new Client([(['base_uri' => 'https://reqres.in/']);

$response = $client->request('GET', '/api/users?page=1');

And then look at the contents of the $response variable.

guzzle http response

As you can see in the output of the $response variable, it holds some very helpful HTTP information. Key information such as

  • Status Code
  • Reason Phrase
  • Content-Type
  • Content-Length

Using The GET HTTP Request Examples

One of the most used HTTP requests is the HTTP GET request and of course, Guzzle supports this method of request with ease.

Example 1

The first example uses no options and is a basic GET request.

The URL we call to is /api/users and we are passing in the parameters URL itself.

$client = new Client([(['base_uri' => 'https://reqres.in/']);

$response = $client->request('GET', '/api/users?page=1');
        
echo $response->getBody();

Output of getBody()

{"page":1,"per_page":1,"total":12,"total_pages":12,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}],"ad":{"company":"StatusCode Weekly","url":"http://statuscode.org/","text":"A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."}}

Example 2

Using the same request principles but placing the parameters into the Guzzle options.

$client = new Client(['base_uri' => 'https://reqres.in/']);

$response = $client->request('GET', '/api/users', ['query' => ['page' => '1', "per_page" => 1]]);

echo $response->getBody();

The client again sends a request to the /api/users URL and rather than explicitly stating the parameters inside the URL, we can get Guzzle to do that by passing it in query parameters.

Output of getBody()

{"page":1,"per_page":1,"total":12,"total_pages":12,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}],"ad":{"company":"StatusCode Weekly","url":"http://statuscode.org/","text":"A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."}}

Using The POST HTTP Request Example

Next up is the POST request, which of course doesn’t allow parameters to be passed as part of a URL. Instead it throws an invisible cloak over the data and secretly passes the values with the request.

In this following example, we will use the API service’s create method which is accepted on the API’s base URL.

$client = new Client(['base_uri' => 'https://reqres.in/']);

$response = $client->request('POST', '/api/users', ['form_params' => [
    'name' => 'Dan',
    'job' => 'Full Stack Dev'
]]);

echo $response->getBody();

Output of getBody()

{"name":"Dan","job":"Full Stack Dev","id":"916","createdAt":"2020-05-22T13:21:20.484Z"}

Using The PUT HTTP Request Example

Next up is the PUT HTTP method which in terms of Guzzles syntax there isn’t much difference. See the example to update a resource below –

Example

$client = new Client(['base_uri' => 'https://reqres.in/']);

$response = $client->request('PUT', '/api/users/916', ['form_params' => [
     'name' => 'DAN',
     'job' => 'DEV',
]]);

echo $response->getBody();

Using The PATCH HTTP Request Example

Similarly to PUT, we have the PATCH method which again looks essentially the same syntax again.

Example

$client = new Client(['base_uri' => 'https://reqres.in/']);

$response = $client->request('PATCH', '/api/users/916', ['form_params' => [
     'name' => 'Dan Englishby',
     'job' => 'Developer',
]]);

echo $response->getBody();

Output of getBody()

{"name":"Dan Englishby","job":"Developer","updatedAt":"2020-05-22T13:55:53.260Z"}

Using The DELETE HTTP Request Example

Lastly, we have the DELETE method which Guzzle can handle for us too. This method requires no parameters to be sent in the payload but an identifier in the URL, specifically the ID of the resource.

For this example, ID 916 will be used and a DELETE request will be sent to the API service.

$client = new Client(['base_uri' => 'https://reqres.in/']);

$response = $client->request('DELETE', '/api/users/916');

Due to this being a DELETE request, there isn’t a body response from this particular API. But if we look at the $response variable, it looks like the following –

guzzle http response for delete request

Summary

Guzzle is the perfect answer for all HTTP requests, it’s not only extremely flexible but easy to understand too. Guzzle has a vast documentation base for all of the out-of-the-ordinary requests that may be made during development.

Leave a Reply

Your email address will not be published.