Introduction
Laravel isn’t just great at serving APIs – it’s also excellent at consuming external APIs. Whether you’re integrating a payment gateway, weather service, or AI API, Laravel provides tools like the HTTP client (powered by Guzzle) to make API calls seamless.
1. The HTTP Client in Laravel
Laravel’s wrapper around Guzzle simplifies external API requests:
use Illuminate\Support\Facades\Http;
$response = Http::get('https://api.openweathermap.org/data/2.5/weather', [
'q' => 'London',
'appid' => env('WEATHER_API_KEY')
]);
$data = $response->json();
This makes it easy to consume third-party APIs without boilerplate.
2. Error Handling
The HTTP client makes error handling elegant:
if ($response->successful()) {
return $response->json();
} elseif ($response->clientError()) {
return ['error' => 'Invalid request'];
} elseif ($response->serverError()) {
return ['error' => 'Server issue'];
}
3. Working with Services
For clean code, put API logic into a service class:
class WeatherService {
public function getWeather($city) {
return Http::get('https://api.openweathermap.org/data/2.5/weather', [
'q' => $city,
'appid' => env('WEATHER_API_KEY')
])->json();
}
}
Use it in your controller:
public function show(WeatherService $weather) {
return $weather->getWeather('London');
}
4. Asynchronous Requests
Need speed? You can make concurrent requests easily:
$responses = Http::pool(fn (Pool $pool) => [
$pool->get('https://api.service1.com/data'),
$pool->get('https://api.service2.com/data'),
]);
Conclusion
Laravel’s HTTP client makes consuming APIs clean, elegant, and efficient. Whether it’s simple GET requests or complex concurrent calls, Laravel equips you to connect with external services effortlessly.
