Belajar API Laravel: Dari Problem ke Solusi!
Source: Dev.to
Kenapa API Itu Penting?
- API adalah jembatan antara frontend dan backend.
- Wajib untuk Single Page Application (SPA) & aplikasi mobile.
- Tanpa API, data tidak dapat ditampilkan ke user.
Contoh API Laravel: CRUD Artikel
Di artikel ini, kita akan membuat API Artikel (CRUD) menggunakan Laravel.
Sederhana, namun sangat berguna untuk blog, news, atau project latihan.
Alur Kerja API Laravel
Sebelum menulis kode, pahami alurnya:
Client (Postman / Frontend)
→ Request HTTP
→ Route API
→ Controller
→ Model
→ Database
→ Response JSON
Setiap kali client meminta data, request melewati route, diproses oleh controller, mengambil data dari model/database, lalu mengembalikan response JSON.
Step 1: Setup Project Laravel
- Laravel versi terbaru (misal 10.x)
- Pastikan Composer sudah terinstal
composer create-project --prefer-dist laravel/laravel belajar-api
Setting Database di .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=belajar_api
DB_USERNAME=root
DB_PASSWORD=
Step 2: Buat Model & Migration Artikel
Mengapa pakai -m?
-m otomatis membuat file migration, jadi tidak perlu membuatnya secara manual.
php artisan make:model Article -m
Edit Migration
Buka file database/migrations/..._create_articles_table.php dan ubah method up() menjadi:
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Jalankan Migrasi
php artisan migrate
Pentingnya $fillable
Di file model app/Models/Article.php, tambahkan:
protected $fillable = ['title', 'content'];
Kenapa harus diisi?
Jika tidak, Laravel tidak dapat menyimpan data karena proteksi mass assignment. Ini adalah fitur keamanan agar hanya kolom yang diizinkan yang dapat di‑insert atau di‑update.
Step 3: Membuat Controller API Artikel
Buat controller resource:
php artisan make:controller Api/ArticleController --resource
Penjelasan Fungsi Utama
| Method | Fungsi |
|---|---|
index() | Ambil semua artikel, kembalikan dalam bentuk JSON |
store() | Simpan artikel baru (validasi → create) |
show($id) | Ambil detail artikel berdasarkan ID |
update($id) | Ubah data artikel tertentu |
destroy($id) | Hapus artikel |
Contoh Implementasi (singkat)
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required',
'content' => 'required',
]);
$article = Article::create($validated);
return response()->json($article, 201);
}
public function show($id)
{
return Article::findOrFail($id);
}
public function update(Request $request, $id)
{
$article = Article::findOrFail($id);
$article->update($request->all());
return response()->json($article);
}
public function destroy($id)
{
Article::destroy($id);
return response()->json(null, 204);
}
Step 4: Menambahkan Route API
Edit file routes/api.php:
use App\Http\Controllers\Api\ArticleController;
Route::apiResource('articles', ArticleController::class);
Cara Testing API dengan Postman (atau cURL)
| Method | Endpoint | Fungsi | Contoh Request Body | Contoh Response |
|---|---|---|---|---|
| GET | /api/articles | List semua artikel | – | [{...}] |
| POST | /api/articles | Simpan artikel baru | { "title": "Belajar Laravel API", "content": "Tutorial lengkap & mudah!" } | { "id": 1, ... } |
| GET | /api/articles/{id} | Detail artikel | – | { "id": 1, ... } |
| PUT | /api/articles/{id} | Update artikel | { "title": "Update", "content": "Edit konten" } | { "id": 1, ... } |
| DELETE | /api/articles/{id} | Hapus artikel | – | null |
Contoh Lengkap Request & Response
Request POST
POST /api/articles HTTP/1.1
Content-Type: application/json
{
"title": "Belajar Laravel API",
"content": "Tutorial lengkap & mudah!"
}
Response 201 Created
{
"id": 1,
"title": "Belajar Laravel API",
"content": "Tutorial lengkap & mudah!",
"created_at": "2026-01-10T12:34:56.000000Z",
"updated_at": "2026-01-10T12:34:56.000000Z"
}
Request GET
GET /api/articles/1 HTTP/1.1
Response 200 OK
{
"id": 1,
"title": "Belajar Laravel API",
"content": "Tutorial lengkap & mudah!",
"created_at": "2026-01-10T12:34:56.000000Z",
"updated_at": "2026-01-10T12:34:56.000000Z"
}
Request PUT
PUT /api/articles/1 HTTP/1.1
Content-Type: application/json
{
"title": "Update Judul",
"content": "Konten sudah diupdate!"
}
Response 200 OK
{
"id": 1,
"title": "Update Judul",
"content": "Konten sudah diupdate!",
"created_at": "2026-01-10T12:34:56.000000Z",
"updated_at": "2026-01-11T08:15:30.000000Z"
}
Request DELETE
DELETE /api/articles/1 HTTP/1.1
Response 204 No Content
No body returned.
Penutup
Dengan mengikuti langkah‑langkah di atas, kamu sudah memiliki API Laravel yang lengkap untuk operasi CRUD artikel. Sekarang frontend React (atau aplikasi lain) dapat berkomunikasi dengan backend tanpa masalah—tidak ada lagi “muter‑muter” di Postman! Selamat mencoba dan semoga sukses. 🚀
API Laravel CRUD Example
Request & Response Samples
GET All Articles
Request
GET /api/articles
Response 200 OK
[
{
"id": 1,
"title": "First Article",
"content": "Lorem ipsum..."
},
{
"id": 2,
"title": "Second Article",
"content": "Dolor sit amet..."
}
]
GET Single Article
Request
GET /api/articles/1
Response 200 OK
{
"id": 1,
"title": "First Article",
"content": "Lorem ipsum..."
}
POST Create Article
Request
POST /api/articles
Content-Type: application/json
{
"title": "New Article",
"content": "Content here..."
}
Response 201 Created
{
"id": 3,
"title": "New Article",
"content": "Content here..."
}
PUT Update Article
Request
PUT /api/articles/1
Content-Type: application/json
{
"title": "Updated Title",
"content": "Updated content..."
}
Response 200 OK
{
"id": 1,
"title": "Updated Title",
"content": "Updated content..."
}
DELETE Article
Request
DELETE /api/articles/1
Response 204 No Content
null
Error Handling & Status Codes in Laravel
Laravel secara otomatis mengembalikan kode status HTTP yang tepat:
| Status Code | Meaning |
|---|---|
| 200 OK | Data retrieved/updated successfully |
| 201 Created | Data created successfully |
| 204 No Content | Data deleted successfully |
| 404 Not Found | Resource not found |
| 422 Unprocessable Entity | Validation failed |
| 500 Internal Server Error | Server error |
Contoh error response
{
"message": "No query results for model [App\\Models\\Article] 99"
}
Tip: Gunakan
findOrFail()di controller untuk otomatis mengembalikan 404 bila model tidak ditemukan.
Common Beginner Mistakes
- Lupa menambahkan
$fillable(atau$guarded) di model, menyebabkan mass‑assignment error. - Menggunakan GET alih‑alih POST untuk membuat resource.
- Melewatkan validasi input, menghasilkan data kotor.
- Mengekspos semua kolom tanpa filter (tidak pakai API Resources).
- Salah konfigurasi file
.env(credential DB, port, dll.). - Menaruh route API di
web.phpbukanapi.php. - Tidak me‑restart server setelah mengubah file konfigurasi.
Tips:
• Selalu periksa response untuk pesan error.
• Pastikan metode HTTP dan nama field sudah benar.
• Double‑check konfigurasi environment Anda.
Next Steps: Level Up Your API
Jangan berhenti di CRUD dasar—jelajahi fitur Laravel berikut:
- Laravel Sanctum / Passport – Amankan API dengan otentikasi.
- API Resources – Transform dan format JSON response secara bersih.
- Pagination – Tangani dataset besar secara efisien.
- Rate Limiting – Lindungi API dari penyalahgunaan.
Nantikan artikel lanjutan yang membahas topik‑topik tersebut!
🚀 Let’s Discuss & Share!
Jika kamu terjebak pada langkah mana pun, tinggalkan komentar di bawah. Bagikan pengalaman API Laravel kamu atau usulkan topik untuk artikel berikutnya (mis. otentikasi, resources, pagination).
Jangan lupa follow dan share artikel ini dengan sesama pembelajar!
Article Structure Overview
- Common beginner problems
- What we’ll build
- Laravel API workflow
- Quick setup
- Step‑by‑step CRUD API
- API testing
- Common mistakes
- Next‑level enhancements
References