HTTP Client – Laravel 7

Laravel 7 provides an expressive API around Guzzle HTTP Client. It allows us to quickly make outgoing HTTP requests to communicate with other web apps.

Before getting started be sure to have guzzle package installed.

composer require guzzlehttp/guzzle

Why use it?

Here are some features that will make you want to use this feature:

  • Easy access to JSON response data.
  • Convenient methods around authentication headers.
  • Tests fakes and test inspections.

Basics

Below is a basic example of its usage:

use Illuminate\Support\Facades\Http;

$response = Http::get('https://laravel.com');

// Get the response body
$response->body();

$response = Http::get( 'https://api.github.com/users/paulredmond/gists' );

// Array of data from the JSON response
$data = $response->json();

Handling Incoming Data

Incoming data comes in the form of JSON. There are some ways to access those incoming data which are:

// Access the response data via `json()`
$data = $response->json();
$data['name']; 

In the above example, we used json() method to access data. Similarly, another way to access data is by using array access.

// Array access from the Response object
Http::get( 'https://api.github.com/users/paulredmond/gists' )['name'];

// Return the response object and access directly
$response = Http::get('...');
$response['name'];

Error Handling

Sometimes, users may face errors while using Guzzle as we have to continually wrap calls in try and catch block.

One good thing is that laravel provides us methods that we can use to determine if any error occurs:


$response = Http::get( 'https://api.github.com/users/paulredmond/gists' );

// Boolean checks on the response
$response->ok() : bool;
$response->clientError(): bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;

Handling Timeout Problem

It is obvious to face timeout problem while talking about server and client. In laravel 7, users can specify the maximum number of seconds to wait for a response. We can set the timeout period as the default timeout is long.

Here is an example:

$response = Http::timeout(5)->get(...);

If the given timeout is exceeded, an instance of Illuminate\Http\Client\ConnectionException will be thrown.

These are basics of HTTP Client that every Laravel Users should know. Learn about more tutorials by clicking here.

You can also know more about HTTP Client from the official documentation.

Total
0
Shares
Leave a Reply

Your email address will not be published.

Related Posts
Total
0
Share