DEV Community

Cover image for Let's Talk About HTTP-Client In Laravel.
Jeffrey Kwade
Jeffrey Kwade

Posted on

Let's Talk About HTTP-Client In Laravel.

Laravel provides an easy-to-use interface for making HTTP requests to remote servers or APIs. Whether you need to send a GET request to retrieve data, a POST request to create or update data, or any other type of HTTP request, Laravel's HTTP client can handle it all.
To make an HTTP request in Laravel, you can use the built-in HTTP client that utilizes Guzzle. This client offers a simple API for making requests, and it can handle things like setting headers, adding query parameters, and even sending JSON payloads.
In addition to the basic HTTP client, Laravel also provides several other features to make working with HTTP requests even easier. For example, you can use middleware to modify requests or responses, and you can use the cache system to cache responses for improved performance.

Sending HTTP requests to a RESTful API endpoint is a common task in web development. Laravel provides a convenient Http facade that allows developers to easily send HTTP requests using the GET, POST, PUT, PATCH, and DELETE methods.

Let's take a closer look at how to use the Http facade in Laravel.

use Illuminate\Support\Facades\Http;

$response = Http::get('https://rest.coinapi.io/v1/exchangerate/BTC/USD');

$response = Http::post('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

$response = Http::put('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

$response = Http::patch('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

$response = Http::delete('https://rest.coinapi.io/v1/exchangerate/BTC/USD', [
    'name' => 'Steve',
]);
Enter fullscreen mode Exit fullscreen mode

The get method returns an instance of Illuminate\Http\Client\Response, which provides a variety of methods that may be used to inspect the response.

The following methods are available on the response object:

  • body() returns the response body as a string.

  • json($key = null, $default = null) returns the response body as an array or object.

  • object() returns the response body as an object.

  • collect($key = null) returns the response body as a collection.

  • status() returns the HTTP status code of the response.

  • successful() returns true if the HTTP status code is in the 200-299 range.

  • redirect() returns true if the HTTP status code is in the 300-399 range.

  • failed() returns true if the HTTP status code is in the 400-599 range.

  • clientError() returns true if the HTTP status code is in the 400-499 range.

  • header($header) returns the value of the specified HTTP header.

  • headers() returns an array of HTTP headers.

While sending HTTP requests to an external API endpoint, it's essential to handle errors that might occur. Laravel's Http facade provides a straightforward way to handle HTTP errors using the throw() method.
For example, to throw an exception if the HTTP status code is not in the 200-299 range, you can use the following code:

$response = Http::get('https://api.example.com');

$response->throw();
Enter fullscreen mode Exit fullscreen mode

Laravel also provides a method to dump a request. This helps a developer to confirm that they are sending the intended parameters and headers. You may add the 'dd()' method to the beginning of your request definition:

Http::dd()->withUrlParameters([
    'endpoint' => 'https://api.example.com',
    'page' => 'docs',
    'version' => '9.x',
    'topic' => 'validation',
])->get('{+endpoint}/{page}/{version}/{topic}');
Enter fullscreen mode Exit fullscreen mode

Now let's make a GET request to coinapi and dump the response body.

"""
{


  "time": "2023-04-02T18:19:49.0000000Z",


  "asset_id_base": "BTC",


  "asset_id_quote": "USD",


  "rate": 28192.38334862458369820384358


}
""" // app\Http\Livewire\Admin\Admin.php:24
Enter fullscreen mode Exit fullscreen mode

The Http response in Laravel also implements PHP's array access allowing us to directly access json response data.

Http::accept('application/json')->withHeaders([
'X-CoinAPI-Key' => 'Example'
])->get('https://rest.coinapi.io/v1/exchangerate/BTC/USD')['rate'];
.

In our HTTP request, we added the acceptJson method to quickly specify that our application expects the application/json content type in response to our request, as well as the withHeaders method. This withHeaders method accepts an array of key/value pairs.

After making the HTTP GET request, let's dump our response:

28212.751030531 // app\Http\Livewire\Admin\Admin.php:24

we easily grab our desired data with less code.

If you would like, you may use the withToken method to quickly add a bearer token to the request's Authorization header:
$response = Http::withToken('token-key')->post(/* ... */);

In conclusion, the HTTP facade allows a developer to easily make HTTP requests in an efficient and clean manner compared to other methods of making HTTP requests in PHP.

Let's compare the HttpRequest in PHP to Laravel's HTTP facade:

<?php
$request = new HttpRequest();
$request->setUrl('https://rest.coinapi.io/v1/exchangerate/BTC/USD');
$request->setMethod(HTTP_METH_GET);
$request->setHeaders(array(
  'X-CoinAPI-Key' => '73034021-THIS-IS-SAMPLE-KEY'
));

try {
  $response = $request->send();
  echo $response->getBody();
} catch (\HttpException $ex) {
  echo $ex;
}
?>

<?php

Http::accept('application/json')->withHeaders([
            'X-CoinAPI-Key' => 'Example'
        ])->get('https://rest.coinapi.io/v1/exchangerate/BTC/USD')['rate'];


?>
Enter fullscreen mode Exit fullscreen mode

We have a shorter and cleaner code syntax when implementing Laravel's Http request compared to PHP's HttpRequest api.

These are just a few use cases for the Http facade in laravel, take a look through Laravel's documentation for a comprehensive list of options available with the Http facade.

Thank you for taking the time to read this post. For more tips and tutorials on web development, feel free to follow me on twitter, github and subscribe to my youtube.

Top comments (0)