Posts Learn Components Snippets Categories Tags Tools new About

How to Perform HTTP Request from Laravel to External API

Learn the ways to perform HTTP requests from Laravel backend application to an external API the easy way

Created on Oct 28, 2021


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.

use Illuminate\Support\Facades\Http;

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

$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.

$client = new GuzzleHttp\Client();
$res = $client->request('POST', '', [ '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.

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