#development #http #laravel #php

Every day, the Laravel framework amazes me in the way it handles very straightforward things.

One of these things is it's HTTP client.

It makes doing HTTP calls such as breeze.

Take a look at this example from Freek van der Herten:

1Http::timeout(5)
2    ->retry(times: 3, sleep: 1)
3    ->get($url)
4    ->json();

In this simple example, you get support for timeouts, retry and JSON parsing.

You want to specify a user agent, just add withUserAgent:

1Http::timeout(5)
2    ->retry(times: 3, sleep: 1)
3    ->withUserAgent('My Super Cool User Agent')
4    ->get($url)
5    ->json();

Specifying a proper user agent when calling an external API is a great way to make debugging on that side easier.

If you want to get an exception when the call fails, just add the throw call:

1Http::timeout(5)
2    ->retry(times: 3, sleep: 1)
3    ->withUserAgent('My Super Cool User Agent')
4    ->throw()
5    ->get($url)
6    ->json();

You want concurrent requests, no problem either:

 1use Illuminate\Http\Client\Pool;
 2use Illuminate\Support\Facades\Http;
 3
 4$responses = Http::pool(fn (Pool $pool) => [
 5    $pool->as('first')->get('http://localhost/first'),
 6    $pool->as('second')->get('http://localhost/second'),
 7    $pool->as('third')->get('http://localhost/third'),
 8]);
 9
10return $responses['first']->ok();

If you want to configure common settings for request, just use macros:

 1namespace App\Providers;
 2
 3use Illuminate\Support\Facades\Http;
 4use Illuminate\Support\ServiceProvider;
 5
 6class AppServiceProvider extends ServiceProvider
 7{
 8    public function boot()
 9    {
10        Http::macro('github', function () {
11            return Http::withHeaders([
12                'X-Example' => 'example',
13            ])->baseUrl('https://github.com');
14        });
15    }
16}

Once setup, you can use it like this:

1$response = Http::github()->get('/');

Even testing is easy as pie by using faking:

1Http::fake([
2    // Stub a JSON response for GitHub endpoints...
3    'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
4
5    // Stub a string response for all other endpoints...
6    '*' => Http::response('Hello World', 200, ['Headers']),
7]);

You can then do your HTTP calls as normal and inspect them afterwards:

 1Http::withHeaders([
 2    'X-First' => 'foo',
 3])->post('http://example.com/users', [
 4    'name' => 'Taylor',
 5    'role' => 'Developer',
 6]);
 7
 8Http::assertSent(function (Request $request) {
 9    return $request->hasHeader('X-First', 'foo') &&
10           $request->url() == 'http://example.com/users' &&
11           $request['name'] == 'Taylor' &&
12           $request['role'] == 'Developer';
13});

For me, I'm not using Guzzle (the library on which the HTTP client is based) never directly again…