Limiting Routes di API Platform
Secara default, API Platform membuat semua operasi CRUD (GET
, POST
, PUT
, PATCH
, DELETE
) untuk setiap resource. Namun, seringkali kita ingin membatasi route tertentu, misalnya:
- Hanya
GET
(read-only API) - Hanya
POST
(submit-only API) - Menonaktifkan
DELETE
agar data tidak bisa dihapus
API Platform memberikan fleksibilitas penuh untuk mengatur operasi ini melalui konfigurasi di #[ApiResource]
.
Membatasi Operasi (Operation Limiting)
Contoh: Resource Read-Only
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
#[ApiResource(
operations: [
new GetCollection(),
new Get()
]
)]
class Book
{
// Properti entity
}
Dengan konfigurasi ini, hanya route berikut yang tersedia:
Method | URL | Keterangan |
---|---|---|
GET | /api/books | Ambil daftar buku |
GET | /api/books/{id} | Ambil detail buku |
🚫 Tidak ada endpoint POST, PUT, PATCH, DELETE.
Membatasi Pada Item Saja Jika ingin membatasi hanya operasi terhadap single item:
#[ApiResource(
itemOperations: ['get'],
collectionOperations: ['get', 'post']
)]
class Book
{
// Properti entity
}
Artinya:
-
Collection (
/api/books
):GET
,POST
tersedia -
Item (
/api/books/{id}
): hanyaGET
tersedia
Menghapus Operasi Tertentu Untuk benar-benar menghapus semua operasi dari resource:
#[ApiResource(operations: [])]
class Book
{
// Properti entity
}
Resource ini tidak akan memiliki route sama sekali.
Membatasi dengan Http Methods (Legacy Syntax) Jika masih menggunakan konfigurasi berbasis array (gaya lama):
#[ApiResource(
collectionOperations: [
'get' => ['method' => 'GET'],
],
itemOperations: [
'get' => ['method' => 'GET'],
]
)]
class Book
{
// Properti entity
}
Tetapi disarankan memakai deklarasi berbasis objek (Get()
, Post()
) untuk proyek baru (API Platform 3+).
Membatasi Operasi Berdasarkan Role Anda juga bisa membatasi operasi berdasarkan peran user:
use ApiPlatform\Metadata\Delete;
#[ApiResource(
operations: [
new GetCollection(),
new Get(),
new Delete(security: "is_granted('ROLE_ADMIN')"),
]
)]
class Book
{
// Properti entity
}
Dalam contoh ini:
-
GET /api/books
danGET /api/books/{id}
bisa diakses semua orang. -
DELETE /api/books/{id}
hanya bisa diakses user denganROLE_ADMIN
.