Build API Request Classes in Laravel with Transporter
Published on by Paul Redmond
Laravel Transporter
Transporter is a "futuristic way to send API requests in PHP. This is an OOP approach to handle API requests":
// Using HTTP client directlyHttp::withToken(config('jsonplaceholder.api.token')) ->get("https://jsonplaceholder.typicode.com/todos", [ 'completed' => 'true', ]); // Using TransporterTodoRequest::build()->send();
To get a visual of the magic happening behind the TodoRequest
extending the Transporter package, here’s the TodoRequest
class:
namespace App\Transporter; use Illuminate\Http\Client\PendingRequest;use JustSteveKing\Transporter\Request; class TodoRequest extends Request{ protected string $method = 'GET'; protected string $baseUrl = 'https://jsonplaceholder.typicode.com'; protected string $path = '/todos'; protected array $data = [ 'completed' => true, ]; protected function withRequest(PendingRequest $request): void { $request->withToken(config('jsonplaceholder.api.token')); }}
The above class will send completed=true
to the API by default, but the package does allow you to override the defaults at runtime:
TodoRequest::build()->withData([ 'completed' => false,])->send();
This package uses the Laravel HTTP Client, so you can use the same API, including support for fake responses in tests:
use JustSteveKing\Transporter\Request; Request::fake(); TestRequest::build() ->withToken('foobar') ->withData([ 'title' => 'Build a package' ]) ->withFakeData([ 'data' => 'faked' ]) ->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.