An **API Gateway** is essential for managing **microservices**, acting as a single entry point to handle authentication, request routing, and load balancing. In this tutorial, we will create a **Laravel API Gateway** to efficiently manage microservices.
Step 1: Install Laravel
First, create a new Laravel project for the API Gateway:
composer create-project --prefer-dist laravel/laravel ApiGateway
Step 2: Setup API Routes
Modify `routes/api.php` to define routes that forward requests to respective microservices:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
Route::get('/users', function (Request $request) {
return Http::withToken($request->bearerToken())->get(env('USER_SERVICE_URL').'/users');
});
});
Step 3: Secure API Gateway with Authentication
Install Laravel Sanctum for API authentication:
composer require laravel/sanctum
Publish the Sanctum configuration:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Step 4: Create Middleware for API Requests
Generate a middleware for validating API requests:
php artisan make:middleware ApiGatewayMiddleware
Modify `app/Http/Middleware/ApiGatewayMiddleware.php`:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ApiGatewayMiddleware {
public function handle(Request $request, Closure $next) {
if (!$request->hasHeader('Authorization')) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
Step 5: Register Middleware
Add the middleware to `app/Http/Kernel.php`:
protected $routeMiddleware = [
'api.gateway' => \App\Http\Middleware\ApiGatewayMiddleware::class,
];
Step 6: Implement Rate Limiting
Modify `app/Providers/RouteServiceProvider.php`:
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
Step 7: Deploy API Gateway
Run the Laravel application:
php artisan serve
Conclusion
You have successfully built an **API Gateway in Laravel** to manage microservices securely. 🚀 Now, all microservices requests pass through the **centralized Laravel API Gateway**.
0 Comments