The built-in client for Laravel allows users to connect to external APIs (r)

May 6, 2023
Using Laravel's built-in client

Please share this with your friends.

In this piece we'll look at methods to make use of Laravel HTTP The Laravel HTTP client that allows you to sending requests, analyzing responses, build macros and middleware, in addition to numerous other tasks.

Laravel HTTP Client is in charge of the bulk of the lifting required for APIs

Guzzle is a simple HTTP client that is designed to be run by PHP. Guzzle can handle various types of requests, including those such as GET, POST, PUT, and DELETE as well as streaming capabilities as also multipart requests. Utilizing Guzzle as an Guzzle HTTP client, you can make either Asynchronous or synchronous request to servers is doable. Additionally, it includes a powerful middleware software which can alter the way the client performs.

This wrapper for the Laravel HTTP Client wrapper that was built upon Guzzle however, it comes with additional attributes. It permits failed requests be tried repeatedly, and it also supports some assistive apps that make use of JSON data. Most functions of Laravel HTTP clients function similarly with Guzzle.

The rules

In the subsequent sections, we'll give further details about Laravel HTTP client. Laravel HTTP client. To follow the tutorial it is required to:

  • Composer, as well as PHP both run in the computer
  • Postman

How to Request Information

If you're curious about how you can use this HTTP client to send an request, you are able to make use of a variety of APIs provided by the host like ReqRes.

Start by installing the HTTP package when you're developing your app. Inside the App/Http/Controllers/UserController.php file, add the following code, starting with the use statement at the beginning of the file and the remaining code inside the index function.

use Illuminate\Support\Facades\Http; return Http::get("https://reqres.in/api/users?page=2");

Notice: For complex use situations, you may also send the request via headers use of headers. using an headers method.

In the same folder, create a new folder using the following code:

function post() $response = Http::withHeaders([ 'Content-Type' => 'application/json', ])->post('https://reqres.in/api/users', [ 'name' => 'morpheus', 'job' => 'leader', ]); return $response; 

Create a brand fresh route using the routes/web.phpfile:

Route::get('post',[UserController::class,'post']);

In the meantime, Postman can be used to confirm the method. Open Postman and add http://127.0.0.1:8000/post as the URL, with the type of request as GET. When you click submit and you receive the message:

Making requests using Postman
Postman asks Postman for information.

Concurrent Demands

The performance of parallel requests is significantly improved because you are able to access a greater amount of data at the same time. It is the Laravel HTTP client permits you to perform simultaneous requests by using the pool technique.

Inside App/Http/Controllers/UserController.php, add the following code:

use Illuminate\Http\Client\Pool; function concurrent() $responses = Http::pool(fn (Pool $pool) => [ $pool->get('https://reqres.in/api/users?page=2'), $pool->get('https://reqres.in/api/users/2'), $pool->get('https://reqres.in/api/users?page=2'), ]); return $responses[0]->ok() && $responses[1]->ok() && $responses[2]->ok(); 

After you've completed that you can add the route in the directory routes/web.phpfile.

Route::get('concurrent',[UserController::class,'concurrent']);

Every time you visit the website:

Concurrent requests
Additionally, it's asking for

Macros Request Macros

Request macros are useful for communicating with API routes common to all.

To create the macro, you need to define the macro inside the boot method of the app/Http/Providers/AppServiceProvider.php file using the code below:

use Illuminate\Support\Facades\Http; Http::macro('reqres', function () return Http::baseUrl('https://reqres.in/api'); );

Note: Make sure to put the usage statement on the very first line in the document.

You can then use the macro in the UserController by adding the below code:

function macro() $response = Http::reqres()->get('/users?page=2'); return $response; 

The macro is in place therefore you don't have to type in the URL each time.

The final step is that you could create a new route in the routes/web.php file using the following codes:

Route::get('macro',[UserController::class,'macro']);
Macro request
Macro request

How do you best to learn how responses are interpreted?

In order to decode the reply and verify that the API request is authentic You can use the option of displaying the status message in your browser. The method is used to obtain the status information from the server, and then display the status message.

To test this out, replace the previous macro code with the code below inside the App/Http/Controllers/UserController.php file:

function macro() $response = Http::reqres()->get('/users?page=2'); return $response->status(); 

A status code 200 means that the request has been processed correctly.

Successful decoding response
Successful decoding response

How can I best use JSON APIs to check JSON APIs?

Laravel has a number of available tools that enable you to look at the JSON APIs and their responses. The helper functions include JSON, GetJson, PostJson putJson, patchJson. deleteJson and on.

To comprehend Testing more clearly, you should create an experiment an elaboration of the entire GET users' experience. Once you have bootstrapped the Laravel application then you will be able to see how the test scenario has been built. Inside the tests/Feature/ExampleTest.php file, replace the existing code with the following:

getJson('/users'); $response->assertStatus(200); 

The additional code retrieves JSON information from the point of origin and checks if the status number is 200 or not.

After you've added the test code, after you have added the test code, execute this command on your terminal in order to run the tests:

./vendor/bin/phpunit

When the test is over at the end of the test, you'll be able to see the tests were administered two times and both tests were successful.

Testing JSON APIs
Testing JSON APIs

It's possible to run tests to test different types of questions and employ different techniques of assistance to conduct tests that are more complex.

How do you deal by situations?

  • RequestSending that takes place prior to the date on which the request is sent.
  • ResponseReceived This is the response that is received.
  • ConnectionFailed it is the situation where there's no response.

All three events include the $request property to inspect the Illuminate\Http\Client\Request instance, and ResponseReceived has an additional $response property. They are very useful to take actions during after the incident. As an example, you may need to send an email to react to an event which is successfully in response.

To create an event and listener, navigate to the app/Providers/EventServiceProvider.php file and replace the listen array with the following code.

protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], 'Illuminate\Http\Client\Events\ResponseReceived' => [ 'App\Listeners\LogResponseReceived', ], ];

The following command should be run on your terminal

php artisan event:generate

The above command will create the app/Listeners/LogResponseReceived.php listener. Replace the code from this file by following these steps:

info($response->status()); /** * Handle the event. * * @param \Illuminate\Http\Client\Events\ResponseReceived $event * @return void */ public function handle(ResponseReceived $event)

The information log which contains an indicator code for status is going to be displayed in the terminal.

Terminal logs showing the status code
The terminal's logs contain the status code

Summary

When a site or app is made by an organisation or by a developer who is on their own APIs play a significant part in the achievement of their business. But, using APIs could make it a challenge.

  • The dashboard is easy to create and maintain the dashboard. My dashboard
  • Support is available 24 hours a day.
  • The most reliable Google Cloud Platform hardware and network are driven by Kubernetes for maximum capacity
  • An extremely high-end Cloudflare integration to improve performance and security
  • International reach with the possibility of having 35 data centers and around 275 PoPs throughout the globe.

This article was originally posted on this web site.

This article first appeared here. here

This post was posted on here