PRAKTEK RESTful API dengan
PHP
REST API PHP MySQL (CRUD)
Kita akan membuat API untuk mengelola data users di basis
data.
Tujuan:
•Membuat basis data dan tabel.
•Membuat API PHP untuk:
•GET: Mengambil semua pengguna atau satu pengguna
berdasarkan ID.
•POST: Menambahkan pengguna baru.
•PUT: Memperbarui pengguna yang sudah ada.
•DELETE: Menghapus pengguna.
•Menguji API menggunakan Postman.
Persyaratan :
Web Server dengan PHP: Kamu perlu menginstal web server
seperti Apache atau Nginx,dan PHP. Cara termudah adalah
menggunakan paket seperti:
XAMPP (untuk Windows, Linux, macOS) htdoc
WAMP (untuk Windows) www
MAMP (untuk macOS) Pastikan Apache dan MySQL (atau
MariaDB) berjalan.
Postman: Aplikasi untuk menguji API.
Code Editor: Visual Studio Code, Sublime Text, PHPStorm, dll.
Langkah 1: Siapkan Basis Data
Kita akan membuat database db_api dan tabel users.
(Database)
1. Mulai MySQL: Pastikan layanan MySQL/MariaDB kamu berjalan
(melalui control panel XAMPP/WAMP/MAMP).
2. Akses phpMyAdmin: Buka browser dan kunjungi
http://localhost/phpmyadmin (atau alamat lain sesuai konfigurasi
kamu).
3. Buat Database:
•Di sidebar kiri phpMyAdmin, klik New.
•Pada "Create database", masukkan nama: db_api
•Klik tombol Create.
4. Buat Tabel users
Ketikan query berikut :
USE db_api;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
);
Langkah ke 2 :
buat stuktur folder
Di dalam folder htdocs (XAMPP)
Di dalam folder WWW (WAMP)
Langkah ke 3 :
Tulis kode kedalam file (db.php)
<?php
// db.php
$host = 'localhost'; // Host database (biasanya localhost)
$username = 'root'; // Username database (default XAMPP/WAMP)
$password = ''; // Password database (default XAMPP/WAMP, biasanya
kosong)
$database = 'db_api';// Nama database yang sudah kita buat
// Buat koneksi baru
$conn = new mysqli($host, $username, $password, $database);
// Cek koneksi
if ($conn->connect_error) {
die("Koneksi database gagal: " . $conn->connect_error);
}
// Set karakter encoding ke UTF-8 (penting untuk data multilinguage)
$conn->set_charset("utf8mb4");
?>
Langkah ke 3 :
Tulis kode kedalam file (.htaccess)
# .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
# Mengizinkan semua metode HTTP untuk CORS
# Ini penting agar Postman atau klien lain bisa mengirim PUT/DELETE
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers,
Authorization, X-Requested-With"
</IfModule>
# Khusus untuk Apache jika ada masalah dengan PUT/DELETE methods
# Kadang mod_rewrite perlu diberitahu untuk meneruskan metode yang benar
RewriteCond %{REQUEST_METHOD} ^(PUT|DELETE) [NC]
RewriteRule ^ index.php [L]
Tulis kode kedalam file (index.php) logika API Utama
<?php
// Header untuk mengizinkan CORS dan menentukan tipe konten JSON
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers,
Authorization, X-Requested-With");
// Untuk menangani Preflight OPTIONS request (CORS)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// Memuat koneksi database
require_once 'db.php';
// Mendapatkan metode HTTP dari permintaan
$method = $_SERVER['REQUEST_METHOD'];
// Mengambil ID dari URL jika ada (contoh: /users?id=1 atau /products?
id=1)
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
// MENGAMBIL PARAMETER RESOURCE DARI URL
$resource = isset($_GET['resource']) ? $_GET['resource'] : null;
// Mengambil data dari body permintaan (untuk POST, PUT)
$data = json_decode(file_get_contents("php://input"));
// Routing berdasarkan metode HTTP dan resource
switch ($resource) {
case 'users':
switch ($method) {
case 'GET':
handleGetRequestUsers($conn, $id);
break;
case 'POST':
handlePostRequestUsers($conn, $data);
break;
case 'PUT':
handlePutRequestUsers($conn, $id, $data);
break;
case 'DELETE':
handleDeleteRequestUsers($conn, $id);
break;
default:
http_response_code(405);
echo json_encode(array("message" => "Metode " . $method . " tidak
didukung untuk resource users."));
break;
}
break;
case 'products': // KASUS BARU UNTUK PRODUCTS
switch ($method) {
case 'GET':
handleGetRequestProducts($conn, $id);
break;
case 'POST':
handlePostRequestProducts($conn, $data); // FUNGSI BARU INI
break;
case 'PUT':
handlePutRequestProducts($conn, $id, $data);
break;
case 'DELETE':
handleDeleteRequestProducts($conn, $id);
break;
default:
http_response_code(405);
echo json_encode(array("message" => "Metode " . $method . " tidak didukung untuk
resource products."));
break;
}
break;
default: // Jika resource tidak ditemukan
http_response_code(404); // Not Found
echo json_encode(array("message" => "Resource tidak ditemukan. Gunakan
/index.php?resource=users atau
/index.php?resource=products"));
break;
}
// --- FUNGSI HANDLER UNTUK USERS (ubah nama fungsi) ---
function handleGetRequestUsers($conn, $id) {
// Implementasi GET untuk users (sama seperti sebelumnya, hanya ubah nama
fungsi)
if ($id) {
$sql = "SELECT id, name, email FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo json_encode($result->fetch_assoc());
} else {
http_response_code(404);
echo json_encode(array("message" => "Pengguna dengan ID " . $id . " tidak ditemukan."));
}
$stmt->close();
} else {
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
$users = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$users[] = $row;
}
}
echo json_encode($users);
}
}
if ($result->num_rows > 0) {
echo json_encode($result->fetch_assoc());
} else {
http_response_code(404);
echo json_encode(array("message" => "Pengguna dengan ID " . $id . " tidak ditemukan."));
}
$stmt->close();
} else {
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
$users = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$users[] = $row;
}
}
echo json_encode($users);
}
}
Menambahkan Data (Post)
Pastikan server Apache dan MySQL kamu berjalan. Buka
Postman.
Base URL API kamu adalah:
http://localhost/REST_API_PHP/index.php
Membuat Pengguna Baru (POST)
1. Metode: POST
2. URL: http://localhost/REST_API_PHP/index.php?resource=users
3. Headers:
Key : Content-Type
Value : application/json
4. Body
Pilih raw dan JSON. Masukkan :
{
"name": “Budi ",
"email": "[email protected]"
}
Menampilkan data (GET)
Pastikan server Apache dan MySQL kamu berjalan. Buka
Postman.
Base URL API kamu adalah:
http://localhost/REST_API_PHP/index.php
Cek koneksi dengan metode GET
1. Metode: GET
2. URL: http://localhost/REST_API_PHP/index.php?resource=users
3. Send
4. Respon 200 ok
Mengubah Data (PUT)
Pastikan server Apache dan MySQL kamu berjalan. Buka
Postman.
Base URL API kamu adalah:
http://localhost/REST_API_PHP/index.php
Merubah data (PUT)
1. Metode: PUT
2. URL: http://localhost/REST_API_PHP/index.php?resource=users
&id=1
3. Headers:
Key : Content-Type
Value : application/json
4. Body
Pilih raw dan JSON. Masukkan :
{
"name": “Aleandro Del Peoro ",
"email": “[email protected]"
}
Menghapus data (DELETE)
Pastikan server Apache dan MySQL kamu berjalan. Buka
Postman.
Base URL API kamu adalah:
http://localhost/REST_API_PHP/index.php
Membuat Pengguna Baru (DELETE)
1. Metode: DELETE
2. URL:
http://localhost/REST_API_PHP/index.php?resource=users&id=1
3. send
Data dengan id 1 akan terhapus
SILAHKAN TAMBAHKAN TABEL
PRODUCTS
LAKUKAN OPERASI
GET : Mengambil semua produk atau satu produk
berdasarkan ID.
POST : Menambahkan produk baru.
contoh :
PUT : Memperbarui produk yang sudah ada.
DELETE : Menghapus produk.
Latihan :
Tampilkan 3 data produk