Today, developing often requires integrating third-party APIs, and external APIs provide a wide level of integration. For that, applications require users to call their URLs to access the content, and for that, laravel provides support with a package called GuzzleHttp to communicate with third parties.
An HTTP client wrapper for Guzzle is offered by Laravel. It enables you to interact with external APIs fast by sending HTTP queries.
First of all need to include HTTP client in our controller as,
use Illuminate\Support\Facades\Http;
Then in the next step, we need to call the get method to retrieve the response from third-party API as get() shown below,
$response = Http::get('https://dummyurl.com/api/v1/fetchdata');
As a result of the above request, it returns the response in JSON format so we can handle it by decoding it like,
$response = json_decode($response->body());
Also, it allows us to pass parameter data as an array in the second argument, if any APIs are required to get a response from it (i.e. most often apikey and then any record or pagination or another query parameter)
$response = Http::get('https://dummyurl.com/api/v1/fetchdata', [‘apikey’=>’value’, ’recordid’=>’idnumber’]);
Additionally, it also supports the post method if we want to store/filter data in any third-party library, with the same first parameter as the URL of the API, followed by an array of post-key data value pairs.
$response = Http::post('https://dummyurl.com/api/v1/storedata', [‘apikey’=>’value’, ’recordid’=>’idnumber’]);
It also supports baseUrl() to set the prefix common part of the third-party API, and then later on we can call multiple requests with different endpoint functions by using the get or post method.
$request = Http::baseUrl('https://dummyurl.com/api/v1/'); $response = $request->get(‘retrievedata’);
It supports methods called successful(), status(), failed() to be sure that requests we make to API endpoints are perfectly working or not. And if there is any error in fetching or calling this API then it can be returned in clientError() or onError(callback object) of the response object.
Go through this package’s in-depth details by clicking the link below.
laravel