Doing HTTP requests FROM Laravel to an external API
To make an HTTP request from Laravel to an external API, you can use the HTTP client of your choice.
To make an HTTP request from Laravel to an external API, you can use the HTTP client of your choice. Laravel provides several ways to send HTTP requests. One option is to use the Guzzle HTTP client library, which is included in Laravel by default.
Using Guzzle HTTP Client
Here is an example of using Guzzle to send an HTTP GET request to an external API:
<?php
use GuzzleHttp\Client;
$client = new Client();
$response = $client->get('http://example.com/api/endpoint');
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();
$body = $response->getBody();📺 Watch a video course: Learn Object Oriented PHP
You can also use the Http facade in Laravel, which provides a simpler interface for making HTTP requests. Here is an example of using the Http facade to send an HTTP GET request:
Using the Http Facade
<?php
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com/api/endpoint');
$statusCode = $response->status();
$headers = $response->headers();
$body = $response->body();Sending POST Requests
To send a POST request with a JSON payload, you can use Http::post():
<?php
use Illuminate\Support\Facades\Http;
$response = Http::asJson()->post('http://example.com/api/endpoint', [
'key' => 'value',
]);
$statusCode = $response->status();
$headers = $response->headers();
$body = $response->body();Handling HTTP Errors
For better reliability, you can enable automatic exception throwing on HTTP errors:
<?php
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
Http::throw();
try {
$response = Http::get('http://example.com/api/endpoint');
// Handle successful response
} catch (\Exception $e) {
// Handle HTTP errors (4xx, 5xx)
Log::error('HTTP request failed: ' . $e->getMessage());
}You can use any of these approaches to make HTTP requests from Laravel to an external API.