Build API Request Classes in Laravel with Transporter

Packages

June 29th, 2021

laravel-transporter.png

Laravel Transporter

Transporter is a "futuristic way to send API requests in PHP. This is an OOP approach to handle API requests":

1// Using HTTP client directly
2Http::withToken(config('jsonplaceholder.api.token'))
3 ->get("https://jsonplaceholder.typicode.com/todos", [
4 'completed' => 'true',
5 ]);
6 
7// Using Transporter
8TodoRequest::build()->send();

To get a visual of the magic happening behind the TodoRequest extending the Transporter package, here’s the TodoRequest class:

1namespace App\Transporter;
2 
3use Illuminate\Http\Client\PendingRequest;
4use JustSteveKing\Transporter\Request;
5 
6class TodoRequest extends Request
7{
8 protected string $method = 'GET';
9 protected string $baseUrl = 'https://jsonplaceholder.typicode.com';
10 protected string $path = '/todos';
11 
12 protected array $data = [
13 'completed' => true,
14 ];
15 
16 protected function withRequest(PendingRequest $request): void
17 {
18 $request->withToken(config('jsonplaceholder.api.token'));
19 }
20}

The above class will send completed=true to the API by default, but the package does allow you to override the defaults at runtime:

1TodoRequest::build()->withData([
2 'completed' => false,
3])->send();

This package uses the Laravel HTTP Client, so you can use the same API, including support for fake responses in tests:

1use JustSteveKing\Transporter\Request;
2 
3Request::fake();
4 
5TestRequest::build()
6 ->withToken('foobar')
7 ->withData([
8 'title' => 'Build a package'
9 ])
10 ->withFakeData([
11 'data' => 'faked'
12 ])
13 ->send();

You can learn more about this package, get full installation instructions, and view the source code on GitHub. The author Steve McDougall also wrote a post Introducing - Laravel Transporter, that explains more background and examples of this package.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.