To consume external APIs in Laravel 11, you can use Laravel's built-in HTTP client, which is a wrapper around Guzzle. This allows you to make HTTP requests without adding additional dependencies. Here's a step-by-step guide on how to do it the "Laravel way":
Step 1: Making HTTP Requests
Laravel provides a fluent interface for making HTTP requests. You can use the Http facade to make requests to external APIs.
use Illuminate\Support\Facades\Http;
$response = Http::get('https://api.example.com/data');
if ($response->successful()) {
$data = $response->json();
// Process the data
} else {
// Handle the error
}
Step 2: Organizing Code
To keep your code organized, consider the following best practices:
-
Service Classes: Create a dedicated service class for handling API requests. This keeps your controllers clean and separates the logic.
namespace App\Services; use Illuminate\Support\Facades\Http; class ApiService { public function fetchData() { $response = Http::get('https://api.example.com/data'); return $response->json(); } } -
Service Providers: If you have complex logic or need to bind interfaces to implementations, consider using a service provider. However, for simple API consumption, a service class is usually sufficient.
-
Environment Configuration: Store API URLs and keys in your
.envfile and access them usingconfig().API_URL=https://api.example.com API_KEY=yourapikey$response = Http::withHeaders([ 'Authorization' => 'Bearer ' . config('services.api.key'), ])->get(config('services.api.url') . '/data');
Step 3: Rate Limiting Outbound Requests
To rate limit outbound requests, you can use Laravel's built-in rate limiting features. Here's a simple example using a middleware:
-
Create a Middleware:
php artisan make:middleware RateLimitMiddleware -
Implement Rate Limiting Logic:
namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\RateLimiter; class RateLimitMiddleware { public function handle($request, Closure $next) { $key = 'api-rate-limit:' . $request->ip(); if (RateLimiter::tooManyAttempts($key, 60)) { return response('Too many requests', 429); } RateLimiter::hit($key, 60); return $next($request); } } -
Register Middleware:
Register the middleware in
app/Http/Kernel.php.protected $routeMiddleware = [ // ... 'rate.limit' => \App\Http\Middleware\RateLimitMiddleware::class, ]; -
Apply Middleware:
Apply the middleware to routes or controllers that make API requests.
Route::get('/api/data', [ApiController::class, 'getData'])->middleware('rate.limit');
By following these steps, you can effectively consume external APIs in Laravel 11 while keeping your code organized and adhering to best practices.