d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

Build API Request Classes in Laravel with 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 AppTransporter;

2

3use IlluminateHttpClientPendingRequest;

4use JustSteveKingTransporterRequest;

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 JustSteveKingTransporterRequest;

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.


Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this