API – (menggunakan API-Key) DI LARAVEL

💻 APLIKASI SIMPEG (Penyedia API)

1. Buat Tabel API Key (Misal: api_clients)

php artisan make:migration create_api_clients_table
Isi migrasinya:
Schema::create(‘api_clients’, function (Blueprint $table) {
$table->id();
$table->string(‘name’); // misal: koperasi
$table->string(‘api_key’)->unique();
$table->timestamps();
});
Lalu jalankan:
php artisan migrate

2. Simpan API Key

Contoh seeding manual:

use Illuminate\Support\Str;
use App\Models\ApiClient;

ApiClient::create([
‘name’ => ‘koperasi’,
‘api_key’ => Str::random(40), // contoh: 40 karakter acak
]);

3. Middleware untuk validasi API Key

php artisan make:middleware CheckApiKey

isi dengan :

// app/Http/Middleware/CheckApiKey.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\ApiClient;

class CheckApiKey
{
public function handle(Request $request, Closure $next)
{
$apiKey = $request->header(‘X-API-KEY’);

if (!$apiKey || !ApiClient::where(‘api_key’, $apiKey)->exists()) {
return response()->json([‘message’ => ‘Unauthorized. Invalid API Key.’], 401);
}

return $next($request);
}
}

4. Registrasi Middleware

Di bootstrap/app.php (Laravel 11) atau Kernel.php:

$app->routeMiddleware([
‘apikey’ => \App\Http\Middleware\CheckApiKey::class,
]);

5. Proteksi Route Data Pegawai

Di routes/api.php:

use App\Models\Pegawai;

Route::middleware(‘apikey’)->get(‘/pegawai’, function () {
return Pegawai::all();
});


🏛️ APLIKASI KOPERASI (Client)

1. Simpan API Key di .env:

SIMPEG_URL=http://simpeg.test
SIMPEG_API_KEY=abcdefgh1234567890apiKEYcontoh

2. config/services.php:

‘simpeg’ => [
‘url’ => env(‘SIMPEG_URL’),
‘key’ => env(‘SIMPEG_API_KEY’),
],

3. Controller untuk Ambil Data:

use Illuminate\Support\Facades\Http;

public function getPegawaiFromSimpeg()
{
$response = Http::withHeaders([
‘X-API-KEY’ => config(‘services.simpeg.key’),
])->get(config(‘services.simpeg.url’) . ‘/api/pegawai’);

if (!$response->ok()) {
return response()->json([‘error’ => ‘Gagal ambil data dari SIMPEG’]);
}

$pegawai = $response->json();

return view(‘pegawai_dari_simpeg’, [‘data’ => $pegawai]);
}


✅ Keuntungan API Key:

Keunggulan Penjelasan
🔐 Lebih aman Tidak perlu simpan username/password di client
⚡ Lebih ringan Tidak perlu proses login/token setiap request
🔄 Lebih stabil Bisa langsung akses endpoint selama API key valid
🔍 Bisa dilacak Setiap client bisa punya API key sendiri, mudah dilog aktivitasnya

Leave a Reply

Your email address will not be published. Required fields are marked *