Home / Snippets / How to Perform HTTP Request from Laravel to External API
How to Perform HTTP Request from Laravel to External API cover

How to Perform HTTP Request from Laravel to External API

3.3K

3 years ago

0 comments

Sometimes you might need to perform HTTP request from the Laravel backend and to do that you can make use of Http Client for Laravel version 7+ and GuzzleHttp for the older Laravel version.
  • Http Client => Laravel 7+
  • GuzzleHttp => Old Laravel Version < 7

Performing HTTP Request with Http Client in Laravel


To perform HTTP requests with Laravel Http Client you can directly import and use the facade right away like below. The Http facade comes with "get", "post", "put", "patch" and "delete" methods as follows.
<?php

use Illuminate\Support\Facades\Http;

$response = Http::get('https://test.com');
$response = Http::post('https://test.com');
$response = Http::put('https://test.com');
$response = Http::patch('https://test.com');
$response = Http::delete('https://test.com');
And the response will be an instance of "Illuminate\Http\Client\Response" which you can access the method like the following.
<?php

$response->body() : string;
$response->json() : array|mixed;
$response->object() : object;
$response->collect() : Illuminate\Support\Collection;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
But do note that underlying this Facade, Laravel still uses GuzzleHttp so make sure to have it installed in your project.
composer require guzzlehttp/guzzle

Performing HTTP Request with GuzzleHttp in Laravel


The 2nd method is to use the GuzzleHttp client and you can install it using composer.
composer require guzzlehttp/guzzle
Once you have done so now you can perform the HTTP request from anywhere within your Laravel application such as the controller or directly from the routes method body.
<?php

$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'https://test.com', [ 'form_params' => [ 'your' => 'form-param', ] ]); // If the status code is 200 theng et the body contents if ($res->getStatusCode() == 200) { $response_data = $res->getBody()->getContents(); }
Do note that you can perform "POST", "GET", "PUT", "PATCH", "DELETE", and more requests just like you would perform Ajax call from the front-end client. Do refer to GuzzleHttp documentation for more details.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this