The Laravel Built-In Client allows users to connect with external APIs (r)

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

Share this on

In this article, we will look at the techniques to make use of Laravel HTTP, the Laravel HTTP client for send requests, analyze responses, build macros and middleware in addition to many other things.

Laravel HTTP Client is in charge of the heavy lifting for APIs

Guzzle is an easy HTTP client designed to run PHP. Guzzle can handle various types of requests like the ones that are such as GET, POST, PUT, and DELETE as well as streaming functions as well as multipart request. By using Guzzle as a Guzzle HTTP client making either Asynchronous or synchronous request to servers is possible. Additionally, it includes an excellent middleware program that can modify the way the client behaves.

This is the Laravel HTTP client wrapper was built on Guzzle however it has other features. It supports the ability unsuccessful requests to be tried again and also some assistive applications that use JSON data. A majority of functions in Laravel HTTP clients work comparable to Guzzle.

The requirements

In the subsequent sections, we'll give more details on Laravel HTTP client. Laravel HTTP client. To follow the tutorial it will need:

  • Composer as well as PHP both reside both available on the computer
  • Postman

How To Make Requests

If you're interested in knowing how you can use the HTTP client to send a request, you can use a broad variety of APIs hosted by the host, like ReqRes.

Begin by installing the HTTP package when you're creating your application. 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");

Note: For complex use situations, you may also send the request via headers, using the using headers. employing the headers method.

In the same folder, create a new file with this 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 new route in the routes/web.phpfile:

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

While you wait, Postman can be used to confirm this method. Open Postman and add http://127.0.0.1:8000/post as the URL, with the type of request as GET. Once you press send and receive the following message:

Making requests using Postman
Postman makes requests to Postman

Concurrent Demands

The performance of parallel requests improves significantly because you can access more data in the same time. The Laravel HTTP client lets you perform simultaneous requests by using the pool method.

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(); 

Once you have that done, add the route to the file routes/web.phpfile.

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

This message every whenever you go to the site:

Concurrent requests
In addition, it is requesting

Macros Request Macros

Request macros can help in interfacing with common API routes.

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'); );

Notice: Make sure to include the usage declaration on the very first line of the file.

Then, you can apply the macro within the UserController to include the following code:

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

The macro is in place, so you don't need to input the URL completely every time.

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

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

What's the most efficient way to understand responses?

To decode the response and ensure the API request is legitimate, you can utilize the option to display status in your client. The method is used to retrieve the status message by the server and present 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 was processed successfully.

Successful decoding response
Successful decoding response

What's the most effective way to test JSON APIs?

Laravel has a number of tools available that allow you to examine the JSON APIs as well as their responses. The helper functions include JSON, GetJson, PostJson putJson, patchJson. deleteJson, and so on.

To understand Testing better, create an experiment that is based on the entire GET user's experience. Once you have bootstrapped the Laravel application then you will see that the test case is already created. 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 place of origin and checks if the status value is 200 or not.

Once you have added the test code After adding the test code, run this command in your terminal, in order to perform the tests:

./vendor/bin/phpunit

After the test is completed following the completion of the test and you'll see tests that were conducted twice and both were successful.

Testing JSON APIs
Testing JSON APIs

It is feasible to conduct tests for various types of inquiries and also employ other assistance techniques for tests that are more sophisticated.

How do you deal by events

  • RequestSending that occurs before the date at which the request is sent.
  • ResponseReceived This is the response has been received.
  • ConnectionFailed this is, in the case when there is no response.

All three events include the $request property to inspect the Illuminate\Http\Client\Request instance, and ResponseReceived has an additional $response property. These properties are extremely useful to take actions during after the incident. For example, you might need to send an email as a reaction 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 instructions:

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 the status code will be displayed inside the terminal.

Terminal logs showing the status code
Logs of the terminal that display 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 development success of their venture. However, the use of APIs can make it difficult.

  • The dashboard is easy to set up and manage the dashboard My dashboard
  • Support is available 24/7.
  • The most efficient Google Cloud Platform hardware and network is powered by Kubernetes for maximum capacity
  • A very premium Cloudflare integration to improve performance and also security
  • Global reach through the potential of having 35 data centers and 275 PoPs all over the world.

This article was originally posted this site.

Article was first seen on here