Laravel HTTP client, first connections and basic exception handling

- Andrés Cruz

En español
Laravel HTTP client, first connections and basic exception handling

The Laravel HTTP client is a built-in feature of the Laravel framework that allows you to make HTTP requests from your Laravel application; with this, we can connect to any system or API based on HTTP or that can receive HTTP requests; These requests can be of the basic types supported by HTTP such as GET, POST, PUT, DELETE. The Laravel client provides an easy-to-use and intuitive channel to make this type of request; this library is called as Guzzle PHP; which. provides a wide range of functions to handle these HTTP requests, since not everything is as easy as making the query, you may need to be authenticated, manage tokens, the time of the requests, the types of responses, embassy and a long etc of elements that you can customize. The response can then be captured and handled as desired within the application.

Laravel HTTP Client in Practice

We are going to know how we can send HTTP requests in Laravel, these requests that you can send are of the CRUD type for the get, put, patch delete and of course post type methods; We can send requests to any other system that allows us, of course, to make this type of request and interconnect applications; It does not matter if it is our own system or not, we can always send requests and do something with this data, be it a json data, text, an HTML page, an image, videos... etc etc etc.

If we check the official Laravel page which deals with this topic in detail:

https://laravel.com/docs/master/http-client

You will see that they tell us that they used a package called guzzlehttp/guzzle that has been installed with Laravel for a long time, you can see an example of the code of how we can make this type of request with this package:

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
   'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
   echo 'I completed! ' . $response->getBody();
});
$promise->wait();

And well, we can do anything: the problem is, if there is a problem, it is that the syntax is not entirely clean, it reminds us a lot of pure and simple PHP and we who use Laravel like things more organized, better readability, scalability and that damn it can be read without so much fuss... for that, Laravel now has a native package integrated by default in the framework, since the previous one is a package that comes installed by default and you can see it in your composer.json:

Anyway, to use the new package is much nicer *-*

$response = Http::get('https://google.com');
$response->body() : string;
$response->json() : array|mixed;

As you can see in the previous lines, with this we can even pass parameters, as the second parameter of the function that we are using:

$response = Http::get('https://tuwebapi.com',['p1=> 1, ... 'px'=>100]);

And it doesn't matter if you make a request of type get or post..., you just have to change the method you want to use and buala:

Http::post('https://jsonplaceholder.typicode.com/posts',[
           'title' => 'foo 2',
           'body' => 'bar',
           'userId' => 1, 
       ])

Of course, depending on the type of response you expect, you can do the conversion; if it is a json:

Http::post('https://jsonplaceholder.typicode.com/posts',[
           'title' => 'foo 2',
           'body' => 'bar',
           'userId' => 1, 
       ])->json()

Or if it's something else, you can consume it from the body:

Http::post('https://google.com,[
...
       ])->body()
Y hacer lo que quieras hacer con la respuesta; recuerda que puedes configurar más parámetros como los headers, preguntar el estatus y mucho más.
Route::get('/', function () {
   try {
       //code...
       dd(Http::post('https://jsonplaceholder.typicode.com/posts',[
           'title' => 'foo 2',
           'body' => 'bar',
           'userId' => 1, 
       ])->json()['userId']);
   } catch (\Illuminate\Http\Client\ConnectionException $e) {
       //throw $th;
       //report($e);
       echo $e;
   }
   //return view('welcome');
});

Exception handling

Optionally, it is always a good idea to handle possible exceptions that may occur when making connections.

try catch

The simplest is through the try catch in which you can place just the exception that is occurring or the generic one; these exceptions can occur when you put a route that doesn't exist or when the server is down...

Report to save in the log

In addition to the above, you can record the possible exception in a Laravel log with report($e), and this is quite useful in production, for that we use the function and pass the exception to it.

Conclusions

So, it's that easy to use or send HTTP requests using Laravel with the new scheme that we have internal to the framework, as you can see, it's much simpler and cleaner than the scheme we had before, and with this you can interconnect systems and evaluate the responses. be it json, a text or something else.

Remember that all this material is part of my course and complete book on Laravel.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.