API Cookbook
Panduan ini fokus ke pola implementasi endpoint yang paling sering dipakai di Customa.
Prasyarat cepat
| Item | Nilai / contoh |
|---|---|
| Base URL local | http://localhost |
| Auth mode utama | Session (web) + token (sanctum) sesuai route group |
| Header JSON | Accept: application/json, Content-Type: application/json |
| Cek daftar endpoint | /docs/api-catalog |
Resep 1 — Login lalu panggil endpoint protected
1) Login
curl -i -X POST "http://localhost/login" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{"email":"admin@example.com","password":"secret"}'
2) Simpan cookie / token lalu akses endpoint
curl -i "http://localhost/api/v1/memberships" \
-H "Accept: application/json" \
-H "Authorization: Bearer <access_token>"
Checklist debug jika 401/403
| Check | Cara cek | Aksi |
|---|---|---|
| Middleware guard | Lihat file route API/web | Samakan mekanisme login dengan guard |
| Token expired | Decode expiry / cek waktu login | Re-login dan retry |
| Scope/role tidak cukup | Cek policy + role user | Naikkan role atau pakai akun yang benar |
Resep 2 — Pagination + filter konsisten
Contoh query standar:
?page=1&per_page=20&sort=-created_at&status=active
| Parameter | Fungsi | Rekomendasi |
|---|---|---|
page | nomor halaman | default 1 |
per_page | jumlah per halaman | 10–50 untuk UI |
sort | urutan data | prefix - untuk descending |
status / filter lain | narrowing data | validasi allowlist di controller |
Resep 3 — Buat data + rollback aman saat gagal
Alur aman untuk endpoint create/update:
- Validasi request (FormRequest).
- Bungkus write operation dengan DB transaction.
- Tangani exception dengan response JSON konsisten.
- Logging error pakai correlation id.
Template respons error:
{
"success": false,
"message": "Validation failed",
"errors": {
"field": ["The field is required."]
},
"trace_id": "req_01H..."
}
Resep 4 — Idempotency untuk endpoint sensitif (checkout/booking)
Gunakan header Idempotency-Key untuk mencegah duplikasi request saat retry dari client.
| Skenario | Risiko tanpa idempotency | Mitigasi |
|---|---|---|
| User klik submit berulang | double insert/order ganda | simpan key + hash payload, return response lama |
| Network timeout lalu retry | data dobel | treat key yang sama sebagai request sama |
Resep 5 — Standarisasi observability endpoint
Minimum log fields per request:
| Field | Kegunaan |
|---|---|
trace_id | korelasi antar service/log |
route + method | identifikasi endpoint |
status_code | klasifikasi sukses/gagal |
latency_ms | baseline performa |
actor_id (jika ada) | audit akses |
Lanjutkan ke: