HTTP Client – Laravel 10

Laravel 10 provides an expressive API around the 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 the 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 fake 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 to try and catch blocks.

One good thing is that Laravel provides us with 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 a timeout problem while talking about server and client. In Laravel 10, 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 the basics of HTTP Client that every Laravel User should know. Learn about more tutorials by clicking here.

You can also learn more about HTTP Clients from the official documentation.

Asmit Nepali, a Full Stack Developer, holds a Software Engineering degree from Gandaki College of Engineering and Science. Proficient in PHP Laravel, Vue.js, MySQL, Tailwind, Figma, and Git, he possesses a robust technical skill set.

Leave a Comment