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. 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.
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();
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:
<?php
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com/api/endpoint');
$statusCode = $response->status();
$headers = $response->headers();
$body = $response->body();
You can also use the Request
facade to make HTTP requests. Here is an example of using the Request
facade to send an HTTP POST request with a JSON payload:
<?php
use Illuminate\Support\Facades\Request;
$response = Request::post('http://example.com/api/endpoint', [
'headers' => [
'Content-Type' => 'application/json',
],
'json' => [
'key' => 'value',
],
]);
$statusCode = $response->status();
$headers = $response->headers();
$body = $response->body();
You can use any of these approaches to make HTTP requests from Laravel to an external API.