CRUD di API Platform
API Platform menyediakan mekanisme otomatis untuk membuat operasi CRUD (Create, Read, Update, Delete) tanpa harus menulis controller manual. Cukup dengan mendefinisikan sebuah entitas dan menambahkan anotasi atau attribute #[ApiResource]
, API Platform akan menghasilkan endpoint REST dan/atau GraphQL.
Contoh: Entitas Book
<?php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ApiResource]
class Book
{
#[ORM\Id, ORM\GeneratedValue, ORM\Column]
private ?int $id = null;
#[ORM\Column]
private string $title;
#[ORM\Column]
private string $author;
// Getter dan Setter
}
Dengan definisi di atas, API Platform secara otomatis menyediakan:
Endpoint REST
Method | URI | Deskripsi |
---|---|---|
GET | /api/books | Ambil daftar semua buku |
POST | /api/books | Tambah buku baru |
GET | /api/books/{id} | Ambil detail buku |
PUT | /api/books/{id} | Perbarui seluruh data buku |
PATCH | /api/books/{id} | Perbarui sebagian data buku |
DELETE | /api/books/{id} | Hapus buku |
Operasi Default
Secara default, #[ApiResource]
menyertakan operasi berikut:
-
Collection:
GET
,POST
-
Item:
GET
,PUT
,PATCH
,DELETE
Anda bisa menyesuaikan operasi ini.
Menyesuaikan Operasi Menonaktifkan Operasi
#[ApiResource(operations: [])]
class Book { ... }
Menyertakan Operasi Tertentu Saja
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Post;
#[ApiResource(
operations: [
new Get(),
new Post()
]
)]
class Book { ... }
Validasi Input (Create/Update) Gunakan constraint Symfony Validator:
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Column]
#[Assert\NotBlank]
#[Assert\Length(min: 3)]
private string $title;
Jika input tidak valid, API akan mengembalikan error 400 dengan pesan validasi.
Response Otomatis Response yang dikembalikan oleh API Platform sesuai standar:
-
200 OK – sukses ambil data
-
201 Created – sukses buat data
-
204 No Content – sukses hapus data
-
400 Bad Request – validasi gagal
-
404 Not Found – data tidak ditemukan
Testing CRUD dengan CURL Contoh penggunaan endpoint menggunakan curl:
# Tambah buku
curl -X POST http://localhost/api/books \
-H "Content-Type: application/json" \
-d '{"title": "Belajar API Platform", "author": "Ari"}'
# Ambil semua buku
curl http://localhost/api/books
# Ambil buku id 1
curl http://localhost/api/books/1
# Update buku id 1
curl -X PUT http://localhost/api/books/1 \
-H "Content-Type: application/json" \
-d '{"title": "API Platform Update", "author": "Ari"}'
# Hapus buku id 1
curl -X DELETE http://localhost/api/books/1